Merge pull request #127 from Ecodev/reformat

Reformat everything with PHP-Cs-Fixer
pull/131/head
David Goodwin 7 years ago committed by GitHub
commit 06f6c71c56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -13,5 +13,5 @@ before_script:
- composer install
script:
- composer check
- composer check-format

@ -3,35 +3,30 @@
ini_set('include_path', get_include_path() . ':' . dirname(__FILE__));
@include_once('Zend/Version.php');
if(!class_exists('Zend_Version', false)) {
die("Zend Framework not found. Please check the INSTALL File.");
if (!class_exists('Zend_Version', false)) {
die("Zend Framework not found. Please check the INSTALL File.");
}
chdir("..");
if (!defined('SM_PATH'))
{
define('SM_PATH','../');
if (!defined('SM_PATH')) {
define('SM_PATH', '../');
}
include_once(dirname(__FILE__) . '/config.php');
include_once(dirname(__FILE__) . '/functions.inc.php');
include_if_exists(dirname(__FILE__) . '/../include/validate.php');
if (file_exists(dirname(__FILE__) . '/../include/validate.php'))
{
if (file_exists(dirname(__FILE__) . '/../include/validate.php')) {
include_once(dirname(__FILE__) . '/include/validate.php');
}
else {
} else {
include_if_exists(SM_PATH . 'src/validate.php');
}
include_once(SM_PATH . 'functions/page_header.php');
include_once(SM_PATH . 'functions/display_messages.php');
include_once(SM_PATH . 'functions/imap.php');
include_if_exists(SM_PATH . 'functions/array.php');
if (file_exists(SM_PATH . 'src/load_prefs.php'))
{
if (file_exists(SM_PATH . 'src/load_prefs.php')) {
include_once(SM_PATH . 'src/load_prefs.php');
}
else {
} else {
include_if_exists(SM_PATH . 'include/load_prefs.php');
}
// overwrite squirrelmail's content type to utf8...
@ -41,4 +36,3 @@ header("Content-Type: text/html; charset=utf8");
//global $VACCONFMESSAGE;
bindtextdomain('postfixadmin', dirname(__FILE__) . '/postfixadmin/locale');
textdomain('postfixadmin');

@ -22,7 +22,7 @@ function _display_password_form() {
echo _('The PostfixAdmin plugin needs your current mailbox password');
echo "<form action='' method='post'>";
echo _('Password for');
echo " " . $_SESSION['username'] . " :";
echo " " . $_SESSION['username'] . " :";
echo "<input type='password' name='password' value=''>";
echo "<input type='submit' value='" . _('Submit') . "'></form>";
do_footer();
@ -40,37 +40,33 @@ function get_xmlrpc() {
$login_object = $client->getProxy('login');
if(empty($_SESSION['password'])) {
if(empty($_POST['password'])) {
if (empty($_SESSION['password'])) {
if (empty($_POST['password'])) {
_display_password_form();
exit(0);
}
else {
} else {
try {
$success = $login_object->login($_SESSION['username'], $_POST['password']);
}
catch(Exception $e) {
} catch (Exception $e) {
//var_dump($client->getHttpClient()->getLastResponse()->getBody());
error_log("Failed to login to xmlrpc instance - " . $e->getMessage());
die('Failed to login to xmlrpc instance');
}
if($success) {
if ($success) {
$_SESSION['password'] = $_POST['password'];
// reload the current page as a GET request.
header("Location: {$_SERVER['REQUEST_URI']}");
exit(0);
}
else {
} else {
_display_password_form();
exit(0);
}
}
}
else {
} else {
$success = $login_object->login($_SESSION['username'], $_SESSION['password']);
}
if(!$success) {
if (!$success) {
unset($_SESSION['password']);
die("Invalid details cached... refresh this page and re-enter your mailbox password");
}
@ -78,7 +74,7 @@ function get_xmlrpc() {
}
function include_if_exists($filename) {
if(file_exists($filename)) {
if (file_exists($filename)) {
include_once($filename);
}
return;
@ -93,10 +89,8 @@ $optmode = 'display';
//
function check_email($email) {
$return = filter_var($email, FILTER_VALIDATE_EMAIL);
if($return === false) {
if ($return === false) {
return false;
}
return true;
}

@ -23,5 +23,3 @@
****************************************************************************************/
header("Location: ../../index.php");
?>

@ -9,7 +9,7 @@ global $username;
do_header();
$USERID_USERNAME = $username;
$tmp = preg_split ('/@/', $USERID_USERNAME);
$tmp = preg_split('/@/', $USERID_USERNAME);
$USERID_DOMAIN = $tmp[1];
@ -20,15 +20,14 @@ $pPassword_password_current_text = '';
$pPassword_password_text = '';
$error = 0;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//$pPassword_password_text = _("pPassword_password_text");
$fPassword_current = $_POST['fPassword_current'];
$fPassword = $_POST['fPassword'];
$fPassword2 = $_POST['fPassword2'];
$username = $USERID_USERNAME;
if(!$user->login($_SESSION['username'], $_POST['fPassword_current'])) {
if (!$user->login($_SESSION['username'], $_POST['fPassword_current'])) {
$error = 1;
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
@ -37,20 +36,20 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
textdomain('squirrelmail');
}
$min_length = 0;
if(isset($CONF['min_password_length'])) {
if (isset($CONF['min_password_length'])) {
$min_length = $CONF['min_password_length'];
}
if (empty ($fPassword) or ($fPassword != $fPassword2) or ($min_length > 0 && strlen($fPassword) < $min_length)) {
if (empty($fPassword) or ($fPassword != $fPassword2) or ($min_length > 0 && strlen($fPassword) < $min_length)) {
$error = 1;
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
if(empty($fPassword)) {
if (empty($fPassword)) {
$pPassword_password_text .= _("The passwords that you supplied are empty!");
}
if($fPassword != $fPassword2) {
if ($fPassword != $fPassword2) {
$pPassword_password_text .= _("The passwords that you supplied don't match!");
}
if($min_length > 0 && strlen($fPassword) < $min_length) {
if ($min_length > 0 && strlen($fPassword) < $min_length) {
$pPassword_password_text .= _("The password you supplied is too short!");
}
bindtextdomain('squirrelmail', SM_PATH . 'locale');
@ -67,8 +66,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
$stMessage = _("Please sign out and log back again with your new password!");
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
else {
} else {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$tMessage = _("Unable to change your password!");
@ -125,4 +123,3 @@ echo "<table bgcolor=\"$color[0]\" align=\"center\" width=\"95%\" cellpadding=\"
</tr></table></td></tr></table>";
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
?>

@ -5,7 +5,7 @@ require_once(dirname(__FILE__) . '/common.php');
$USERID_USERNAME = $username;
$tmp = preg_split ('/@/', $USERID_USERNAME);
$tmp = preg_split('/@/', $USERID_USERNAME);
$USERID_LOCALPART = $tmp[0];
$USERID_DOMAIN = $tmp[1];
@ -13,10 +13,9 @@ $xmlrpc = get_xmlrpc();
$alias = $xmlrpc->getProxy('alias');
do_header();
// Normal page request (GET)
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$row = $alias->get();
if($row === false) {
if ($row === false) {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$tMessage = _("Unable to locate alias!");
@ -26,29 +25,25 @@ if ($_SERVER['REQUEST_METHOD'] == "GET")
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$pEdit_alias_goto = _("To");
$fGoto = $_POST['fGoto'];
// reform string into a list...
$goto = preg_replace ('/\r\n/', ',', $fGoto);
$goto = preg_replace ('/[\s]+/i', '', $goto);
$goto = preg_replace ('/\,*$/', '', $goto);
$array = preg_split ('/,/', $goto);
$goto = preg_replace('/\r\n/', ',', $fGoto);
$goto = preg_replace('/[\s]+/i', '', $goto);
$goto = preg_replace('/\,*$/', '', $goto);
$array = preg_split('/,/', $goto);
$error = 0;
// check that we have valid addresses in the list
foreach($array as $key => $email_address)
{
if (empty($email_address))
{
unset($array[$key]);
foreach ($array as $key => $email_address) {
if (empty($email_address)) {
unset($array[$key]);
continue;
}
if (!check_email($email_address))
{
if (!check_email($email_address)) {
$error = 1;
$tGoto = $goto;
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
@ -61,15 +56,13 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
if ($error != 1) {
$flag = 'forward_and_store'; // goto = $USERID_USERNAME;
$success = $alias->update($array, $flag);
if(!$success) {
if (!$success) {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$tMessage = _("Unable to modify the alias!");
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
else {
} else {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
echo "<p align=center><b>". _("Alias successfully changed!"). "\n</b></p>";
@ -83,7 +76,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
if(!isset($tMessage)) {
if (!isset($tMessage)) {
$tMessage = '';
}
echo "<table bgcolor=\"$color[0]\" align=\"center\" width=\"95%\" cellpadding=\"1\" cellspacing=\"0\" border=\"0\">
@ -129,8 +122,10 @@ echo "<table bgcolor=\"$color[0]\" align=\"center\" width=\"95%\" cellpadding=\"
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
$aliases = $alias->get();
foreach($aliases as $address) {
if ($address == "" || $address == NULL) { continue; }
foreach ($aliases as $address) {
if ($address == "" || $address == null) {
continue;
}
print "$address\n";
}
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
@ -162,4 +157,3 @@ echo "
";
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
?>

@ -15,14 +15,12 @@ EOM;
do_header();
$USERID_USERNAME = $username;
$tmp = preg_split ('/@/', $USERID_USERNAME);
$tmp = preg_split('/@/', $USERID_USERNAME);
$USERID_DOMAIN = $tmp[1];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$details = $vacation->getDetails();
if($vacation->checkVacation()) {
if ($vacation->checkVacation()) {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$tMessage = _("You already have an auto response configured!");
@ -54,9 +52,7 @@ if ($_SERVER['REQUEST_METHOD'] == "GET")
</tr></table><BR></td></tr></table></td></tr></table>";
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
else
{
} else {
$tSubject = "Out of Office";
$tSubject = $details['subject'];
$VACCONF = $details['body'];
@ -94,64 +90,52 @@ if ($_SERVER['REQUEST_METHOD'] == "GET")
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$fBack = null;
$fAway = null;
foreach(array('fBack', 'fAway', 'fSubject', 'fBody') as $key) {
foreach (array('fBack', 'fAway', 'fSubject', 'fBody') as $key) {
$$key = null;
if(isset($_POST[$key])) {
if (isset($_POST[$key])) {
$$key = $_POST[$key];
}
}
if (!empty($fBack))
{
if (!empty($fBack)) {
$success = $vacation->remove();
if(!$success)
{
if (!$success) {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$tMessage = _("Unable to update your auto response settings!");
echo "<p>This may signify an error; please contact support (1)</p>";
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
else
{
} else {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
echo "<p align=center><b>". _("Your auto response has been removed!") ."</b></p>";
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
}
if (!empty ($fAway))
{
if (!empty($fAway)) {
// add record into vacation
$success = $vacation->setAway($fSubject, $fBody);
if(!$success) {
if (!$success) {
$error = 1;
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$tMessage = _("Unable to update your auto response settings!");
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
else
{
} else {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
echo "<p align=center><b>". _("Your auto response has been set!") ."</b></p>";
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
}
}
}
?>

@ -7,14 +7,13 @@ function squirrelmail_plugin_init_postfixadmin() {
global $squirrelmail_plugin_hooks;
$squirrelmail_plugin_hooks['optpage_register_block']['postfixadmin'] = 'postfixadmin_optpage_register_block';
}
function postfixadmin_version(){
function postfixadmin_version() {
return '2.3.0';
}
function postfixadmin_optpage_register_block () {
function postfixadmin_optpage_register_block() {
// Gets added to the user's OPTIONS page.
global $optpage_blocks;
global $AllowVacation;
@ -24,18 +23,18 @@ function postfixadmin_optpage_register_block () {
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
$optpage_blocks[] = array (
$optpage_blocks[] = array(
'name' => _("Forwarding"),
'url' => '../plugins/postfixadmin/postfixadmin_forward.php',
'desc' => _("Here you can create and edit E-Mail forwards."),
'js' => FALSE
'js' => false
);
bindtextdomain('squirrelmail', SM_PATH . 'locale');
textdomain('squirrelmail');
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
if($AllowVacation) {
if ($AllowVacation) {
$optpage_blocks[] = array(
'name' => _("Auto Response"),
'url' => '../plugins/postfixadmin/postfixadmin_vacation.php',
@ -47,7 +46,7 @@ function postfixadmin_optpage_register_block () {
}
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin');
if($AllowChangePass) {
if ($AllowChangePass) {
$optpage_blocks[] = array(
'name' => _("Change Password"),
'url' => '../plugins/postfixadmin/postfixadmin_changepass.php',
@ -58,4 +57,3 @@ function postfixadmin_optpage_register_block () {
textdomain('squirrelmail');
}
}
?>

@ -8,14 +8,14 @@
0 4 * * * * vmail php -q virtualmaildel.php >/dev/null
Changes:
2017.08.31 updated to use PHP mysqli extension.
2017.08.31 updated to use PHP mysqli extension.
Tadas Ustinavičius <tadas at ring dot lt> ( https://github.com/postfixadmin/postfixadmin/pull/70 )
*/
$CONF = [];
// Either, uncomment this (and change to work)
// Either, uncomment this (and change to work)
//require_once('/path/to/postfixadmin/config.inc.php');
// OR uncomment this.
@ -31,31 +31,26 @@ $CONF = [
$MAKE_CHANGES = false; // change to true when you're happy this isn't going to trash your server.
if(empty($CONF)) {
if (empty($CONF)) {
die("\nPlease configure me\n\n");
}
// Where's the homedir accounts stored. (GET THIS RIGHT OTHERWISE IT THINK NONE EXIST AND DELETES ALL)
$homedir = '/home/virtual';
$homedir = '/home/virtual';
if ( ! is_dir( $homedir ) ) {
die( "Cannot find home directory for virtual mailboxes in $homedir\n" );
if (! is_dir($homedir)) {
die("Cannot find home directory for virtual mailboxes in $homedir\n");
}
//
// Recursive Delete Function
//
function deldir($dir)
{
function deldir($dir) {
$current_dir = opendir($dir);
while($entryname = readdir($current_dir))
{
if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
{
while ($entryname = readdir($current_dir)) {
if (is_dir("$dir/$entryname") and ($entryname != "." and $entryname!="..")) {
deldir("${dir}/${entryname}");
}
elseif($entryname != "." and $entryname!="..")
{
} elseif ($entryname != "." and $entryname!="..") {
unlink("${dir}/${entryname}");
}
}
@ -70,54 +65,47 @@ $dir = [];
//
// Get list of directories
//
$fr = opendir( $homedir );
$fr = opendir($homedir);
// TODO: Would glob($homedir . '/**/*/new') be somewhat quicker/shorter/less effort?
while ( ($domain = readdir($fr)) !== false)
{
while (($domain = readdir($fr)) !== false) {
//
// Check if it's a dir
//
if ( $domain != "." and $domain != ".." and filetype($homedir .'/'. $domain) == "dir" )
{
if ($domain != "." and $domain != ".." and filetype($homedir .'/'. $domain) == "dir") {
//
// Open the (assumed) DOMAIN directory
//
$ff = opendir( $homedir .'/'. $domain );
while ( ($user = readdir($ff)) !== false)
{
$ff = opendir($homedir .'/'. $domain);
while (($user = readdir($ff)) !== false) {
//
// Check for directories assuming it's a user account
//
if ( $user!="." and $user!=".." and filetype($homedir .'/'. $domain .'/'. $user) == "dir" )
{
if ($user!="." and $user!=".." and filetype($homedir .'/'. $domain .'/'. $user) == "dir") {
//
// if the dir 'new' exists inside then it's an account
//
if ( file_exists($homedir .'/'. $domain .'/'. $user .'/'. "new") )
{
if (file_exists($homedir .'/'. $domain .'/'. $user .'/'. "new")) {
$dir[$domain][$user] = "";
}
else
{
} else {
//
// Alert that the dir doesn't have a 'new' dir, possibly not an account. Leave it.
//
echo "UNKNOWN : " . $homedir ."/". $domain ."/". $user ."/new NOT FOUND. Possibly not an account. Leaving untouched\n";
}
}
}
}
}
}
}
//
// OK, got an array of accounts from the dir, Now connect to the DB and check them
//
$conx = mysqli_connect( $CONF['database_host'],$CONF['database_user'],$CONF['database_password'], $CONF['database_name'] );
$conx = mysqli_connect($CONF['database_host'], $CONF['database_user'], $CONF['database_password'], $CONF['database_name']);
//
// Is there a problem connecting?
//
if ( ! $conx || mysqli_connect_errno() ) {
if (! $conx || mysqli_connect_errno()) {
var_dump("DB connection failed." . mysqli_connect_error());
die("Problem connecting to the database. ");
}
@ -126,34 +114,33 @@ if ( ! $conx || mysqli_connect_errno() ) {
// Select all mailboxes to verify against dirs listed in array
//
$query = "SELECT * FROM mailbox";
$result = mysqli_query( $conx, $query );
$result = mysqli_query($conx, $query);
//
// Query the mailbox table
//
if ( ! $result ) {
if (! $result) {
die("Failed to query mailbox table.");
}
//
// Fetch the list of results
//
while ( $row = mysqli_fetch_assoc( $result ) )
{
while ($row = mysqli_fetch_assoc($result)) {
//
// Pull apart the maildir field, needed to figure out the directory structure to compare
//
$strip = explode("/",$row['maildir']);
$strip = explode("/", $row['maildir']);
//
// Unset the array if it exists. This stops it being erased later.
//
unset( $dir[ $strip[0] ][ $strip[1] ] );
unset($dir[ $strip[0] ][ $strip[1] ]);
}
//
// If there are results. unset the domain too.
//
if ( count($dir[$strip[0]])==0 and mysqli_num_rows($result)>0 ) {
unset( $dir[$strip[0]] );
if (count($dir[$strip[0]])==0 and mysqli_num_rows($result)>0) {
unset($dir[$strip[0]]);
}
//
@ -163,29 +150,24 @@ if ( count($dir[$strip[0]])==0 and mysqli_num_rows($result)>0 ) {
//
// If the array still exists (incase nothing there)
//
if ( is_array($dir) )
{
if (is_array($dir)) {
//
// Go through each dir
//
foreach ( $dir as $key => $value )
{
foreach ($dir as $key => $value) {
//
// Is this a user array?
//
if ( is_array( $value) )
{
if (is_array($value)) {
//
// Go through and nuke the folders
//
foreach ( $value as $user => $value2 )
{
foreach ($value as $user => $value2) {
// Nuke.. need any more explanations?
$path = $homedir . '/' . $key . '/' . $user;
if($MAKE_CHANGES) {
deldir( $path );
}
else {
if ($MAKE_CHANGES) {
deldir($path);
} else {
echo " - Would recursively delete : $path \n";
}
}

@ -1,27 +1,27 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: common.php
* All pages should include this file - which itself sets up the necessary
* environment and ensures other functions are loaded.
*/
if(!defined('POSTFIXADMIN')) { # already defined if called from setup.php
if (!defined('POSTFIXADMIN')) { # already defined if called from setup.php
define('POSTFIXADMIN', 1); # checked in included files
if (!defined('POSTFIXADMIN_CLI')) {
// this is the default; see also https://sourceforge.net/p/postfixadmin/bugs/347/
session_cache_limiter('nocache');
session_cache_limiter('nocache');
session_name('postfixadmin_session');
session_start();
@ -31,7 +31,7 @@ if(!defined('POSTFIXADMIN')) { # already defined if called from setup.php
session_start();
}
if(empty($_SESSION['flash'])) {
if (empty($_SESSION['flash'])) {
$_SESSION['flash'] = array();
}
}
@ -41,7 +41,7 @@ $incpath = dirname(__FILE__);
(ini_get('magic_quotes_gpc') ? ini_set('magic_quotes_runtime', '0') : '1');
(ini_get('magic_quotes_gpc') ? ini_set('magic_quotes_sybase', '0') : '1');
if(ini_get('register_globals') == 'on') {
if (ini_get('register_globals') == 'on') {
die("Please turn off register_globals; edit your php.ini");
}
@ -52,7 +52,7 @@ if(ini_get('register_globals') == 'on') {
function postfixadmin_autoload($class) {
$PATH = dirname(__FILE__) . '/model/' . $class . '.php';
if(is_file($PATH)) {
if (is_file($PATH)) {
require_once($PATH);
return true;
}
@ -60,13 +60,13 @@ function postfixadmin_autoload($class) {
}
spl_autoload_register('postfixadmin_autoload');
if(!is_file("$incpath/config.inc.php")) {
if (!is_file("$incpath/config.inc.php")) {
die("config.inc.php is missing!");
}
require_once("$incpath/config.inc.php");
if(isset($CONF['configured'])) {
if($CONF['configured'] == FALSE) {
if (isset($CONF['configured'])) {
if ($CONF['configured'] == false) {
die("Please edit config.inc.php - change \$CONF['configured'] to true after setting your database settings");
}
}
@ -79,15 +79,15 @@ require_once("$incpath/functions.inc.php");
if (defined('POSTFIXADMIN_CLI')) {
$language = 'en'; # TODO: make configurable or autodetect from locale settings
} else {
$language = check_language (); # TODO: storing the language only at login instead of calling check_language() on every page would save some processor cycles ;-)
$language = check_language(); # TODO: storing the language only at login instead of calling check_language() on every page would save some processor cycles ;-)
$_SESSION['lang'] = $language;
}
require_once("$incpath/languages/" . $language . ".lang");
if(!empty($CONF['language_hook']) && function_exists($CONF['language_hook'])) {
if (!empty($CONF['language_hook']) && function_exists($CONF['language_hook'])) {
$hook_func = $CONF['language_hook'];
$PALANG = $hook_func ($PALANG, $language);
$PALANG = $hook_func($PALANG, $language);
}
Config::write('__LANG', $PALANG);
@ -95,11 +95,10 @@ Config::write('__LANG', $PALANG);
unset($incpath);
if (!defined('POSTFIXADMIN_CLI')) {
if(!is_file(dirname(__FILE__) . "/smarty.inc.php")) {
if (!is_file(dirname(__FILE__) . "/smarty.inc.php")) {
die("smarty.inc.php is missing! Something is wrong...");
}
require_once (dirname(__FILE__) . "/smarty.inc.php");
require_once(dirname(__FILE__) . "/smarty.inc.php");
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
<?php
//
// Postfix Admin
//
// Postfix Admin
// by Mischa Peters <mischa at high5 dot net>
// Copyright (c) 2002 - 2005 High5!
// Licensed under GPL for more info check GPL-LICENSE.TXT
@ -17,6 +17,5 @@
//
// -none-
//
header ("Location: ../login.php");
header("Location: ../login.php");
exit;
?>

@ -1,4 +1,6 @@
<?php if( !defined('POSTFIXADMIN') ) die( "This file cannot be used standalone." ); ?>
<?php if (!defined('POSTFIXADMIN')) {
die("This file cannot be used standalone.");
} ?>
<?php
# List of supported languages
$supported_languages = array(

@ -2,21 +2,20 @@
# $Id$
class AdminHandler extends PFAHandler {
protected $db_table = 'admin';
protected $id_field = 'username';
protected function validate_new_id() {
$email_check = check_email($this->id);
protected function validate_new_id() {
$email_check = check_email($this->id);
if ($email_check == '') {
if ($email_check == '') {
return true;
} else {
} else {
$this->errormsg[] = $email_check;
$this->errormsg[$this->id_field] = Config::lang('pAdminCreate_admin_username_text_error1');
return false;
}
}
}
}
protected function no_domain_field() {
# PFAHandler die()s if domain field is not set. Disable this behaviour for AdminHandler.
@ -40,32 +39,72 @@ class AdminHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'username' => pacol( $this->new, 1, 1, 'text', 'admin' , 'email_address' , '', '',
array('linkto' => 'list.php?table=domain&username=%s') ),
'password' => pacol( 1, 1, 0, 'pass', 'password' , '' ),
'password2' => pacol( 1, 1, 0, 'pass', 'password_again' , '' , '', '',
'username' => pacol(
$this->new,
1,
1,
'text',
'admin',
'email_address',
'',
'',
array('linkto' => 'list.php?table=domain&username=%s')
),
'password' => pacol(1, 1, 0, 'pass', 'password', ''),
'password2' => pacol(
1,
1,
0,
'pass',
'password_again',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'password as password2'
),
'superadmin' => pacol( 1, 1, 0, 'bool', 'super_admin' , 'super_admin_desc' , 0
'superadmin' => pacol(
1,
1,
0,
'bool',
'super_admin',
'super_admin_desc',
0
# TODO: (finally) replace the ALL domain with a column in the admin table
# TODO: current status: 'superadmin' column exists and is written when storing an admin with AdminHandler,
# TODO: but the superadmin status is still (additionally) stored in the domain_admins table ("ALL" dummy domain)
# TODO: to keep the database backwards-compatible with 2.3.x.
# TODO: to keep the database backwards-compatible with 2.3.x.
# TODO: Note: superadmins created with 2.3.x after running upgrade_1284() will not work until you re-run upgrade_1284()
# TODO: Create them with the trunk version to avoid this problem.
),
'domains' => pacol( 1, 1, 0, 'list', 'domain' , '' , array(), list_domains(),
'domains' => pacol(
1,
1,
0,
'list',
'domain',
'',
array(),
list_domains(),
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ "coalesce(domains,'') as domains"
/*extrafrom set in domain_count*/
),
'domain_count' => pacol( 0, 0, 1, 'vnum', 'pAdminList_admin_count', '' , '', '',
'domain_count' => pacol(
0,
0,
1,
'vnum',
'pAdminList_admin_count',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'coalesce(__domain_count,0) as domain_count',
@ -73,15 +112,16 @@ class AdminHandler extends PFAHandler {
' SELECT count(*) AS __domain_count, ' . $domains_grouped . ' AS domains, username AS __domain_username ' .
' FROM ' . table_by_key('domain_admins') .
" WHERE domain != 'ALL' GROUP BY username " .
' ) AS __domain on username = __domain_username'),
'active' => pacol( 1, 1, 1, 'bool', 'active' , '' , 1 ),
'phone' => pacol( 1, $passwordReset, 0, 'text', 'pCreate_mailbox_phone', 'pCreate_mailbox_phone_desc', ''),
'email_other' => pacol( 1, $passwordReset, 0, 'mail', 'pCreate_mailbox_email', 'pCreate_mailbox_email_desc', ''),
'token' => pacol( 1, 0, 0, 'text', '' , '' ),
'token_validity' => pacol( 1, 0, 0, 'ts', '' , '', date("Y-m-d H:i:s",time())),
'created' => pacol( 0, 0, 0, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, 1, 'ts', 'last_modified' , '' ),
' ) AS __domain on username = __domain_username'
),
'active' => pacol(1, 1, 1, 'bool', 'active', '', 1),
'phone' => pacol(1, $passwordReset, 0, 'text', 'pCreate_mailbox_phone', 'pCreate_mailbox_phone_desc', ''),
'email_other' => pacol(1, $passwordReset, 0, 'mail', 'pCreate_mailbox_email', 'pCreate_mailbox_email_desc', ''),
'token' => pacol(1, 0, 0, 'text', '', ''),
'token_validity' => pacol(1, 0, 0, 'ts', '', '', date("Y-m-d H:i:s", time())),
'created' => pacol(0, 0, 0, 'ts', 'created', ''),
'modified' => pacol(0, 0, 1, 'ts', 'last_modified', ''),
);
}
@ -154,7 +194,7 @@ class AdminHandler extends PFAHandler {
if ($result['rows'] == 0) {
db_insert('domain_admins', $values, array('created'));
# TODO: check for errors
}
}
} else {
db_delete('domain_admins', 'username', $this->id, "AND domain = 'ALL'");
}
@ -182,7 +222,7 @@ class AdminHandler extends PFAHandler {
* @return true on success false on failure
*/
public function delete() {
if ( ! $this->view() ) {
if (! $this->view()) {
$this->errormsg[] = Config::Lang($this->msg['error_does_not_exist']);
return false;
}
@ -190,14 +230,14 @@ class AdminHandler extends PFAHandler {
db_delete('domain_admins', $this->id_field, $this->id);
db_delete($this->db_table, $this->id_field, $this->id);
db_log ('admin', 'delete_admin', $this->id); # TODO delete_admin is not a valid db_log keyword yet, and 'admin' is not displayed in viewlog.php
db_log('admin', 'delete_admin', $this->id); # TODO delete_admin is not a valid db_log keyword yet, and 'admin' is not displayed in viewlog.php
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->id);
return true;
}
# TODO: generate password if $new, no password specified and $CONF['generate_password'] is set
# TODO: except if $this->admin_username == setup.php --- this exception should be handled directly in setup.php ("if $values['password'] == '' error_out")
# TODO: generate password if $new, no password specified and $CONF['generate_password'] is set
# TODO: except if $this->admin_username == setup.php --- this exception should be handled directly in setup.php ("if $values['password'] == '' error_out")
/**
* compare password / password2 field
@ -206,7 +246,6 @@ class AdminHandler extends PFAHandler {
protected function _validate_password2($field, $val) {
return $this->compare_password_fields('password', 'password2');
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -2,7 +2,6 @@
# $Id$
class AdminpasswordHandler extends PFAHandler {
protected $db_table = 'admin';
protected $id_field = 'username';
@ -24,11 +23,28 @@ class AdminpasswordHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'username' => pacol( 0, 1, 1, 'text', 'admin' , '' ),
'oldpass' => pacol( 1, 1, 0, 'pass', 'pPassword_password_current' , '', '', '',
/*not_in_db*/ 1 ),
'password' => pacol( 1, 1, 0, 'pass', 'pPassword_password' , '' ),
'password2' => pacol( 1, 1, 0, 'pass', 'pPassword_password2' , '' , '', '',
'username' => pacol(0, 1, 1, 'text', 'admin', ''),
'oldpass' => pacol(
1,
1,
0,
'pass',
'pPassword_password_current',
'',
'',
'',
/*not_in_db*/ 1
),
'password' => pacol(1, 1, 0, 'pass', 'pPassword_password', ''),
'password2' => pacol(
1,
1,
0,
'pass',
'pPassword_password2',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'password as password2'
@ -38,7 +54,9 @@ class AdminpasswordHandler extends PFAHandler {
public function init($id) {
# hardcode to logged in admin
if ($this->admin_username == '') die("No admin logged in");
if ($this->admin_username == '') {
die("No admin logged in");
}
$this->id = $this->admin_username;
$this->values['username'] = $this->id;
$this->struct['username']['default'] = $this->id;
@ -79,7 +97,7 @@ class AdminpasswordHandler extends PFAHandler {
* check if old password is correct
*/
protected function _validate_oldpass($field, $val) {
if ( $this->login($this->id, $val) ) {
if ($this->login($this->id, $val)) {
return true;
}
@ -91,7 +109,9 @@ class AdminpasswordHandler extends PFAHandler {
* skip default validation (check if password is good enough) for old password
*/
protected function _inp_pass($field, $val) {
if ($field == 'oldpass') return true;
if ($field == 'oldpass') {
return true;
}
return parent::_inp_pass($field, $val);
}
@ -103,7 +123,6 @@ class AdminpasswordHandler extends PFAHandler {
protected function _validate_password2($field, $val) {
return $this->compare_password_fields('password', 'password2');
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,13 +1,12 @@
<?php
# $Id$
# $Id$
/**
/**
* Handlers User level alias actions - e.g. add alias, get aliases, update etc.
* @property $username name of alias
* @property $return return of methods
*/
class AliasHandler extends PFAHandler {
protected $db_table = 'alias';
protected $id_field = 'address';
protected $domain_field = 'domain';
@ -27,37 +26,104 @@ class AliasHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / ...
# editing? form list
'status' => pacol( 0, 0, 0, 'html', '' , '' , '', '',
array('not_in_db' => 1) ),
'address' => pacol( $this->new, 1, 1, 'mail', 'alias' , 'pCreate_alias_catchall_text' ),
'localpart' => pacol( $this->new, 0, 0, 'text', 'alias' , 'pCreate_alias_catchall_text' , '',
/*options*/ '',
/*not_in_db*/ 1 ),
'domain' => pacol( $this->new, 0, 1, 'enum', '' , '' , '',
/*options*/ $this->allowed_domains ),
'goto' => pacol( 1, 1, 1, 'txtl', 'to' , 'pEdit_alias_help' , array() ),
'is_mailbox' => pacol( 0, 0, 1, 'int', '' , '' , 0 ,
'status' => pacol(
0,
0,
0,
'html',
'',
'',
'',
'',
array('not_in_db' => 1)
),
'address' => pacol($this->new, 1, 1, 'mail', 'alias', 'pCreate_alias_catchall_text'),
'localpart' => pacol(
$this->new,
0,
0,
'text',
'alias',
'pCreate_alias_catchall_text',
'',
/*options*/ '',
/*not_in_db*/ 1
),
'domain' => pacol(
$this->new,
0,
1,
'enum',
'',
'',
'',
/*options*/ $this->allowed_domains
),
'goto' => pacol(1, 1, 1, 'txtl', 'to', 'pEdit_alias_help', array()),
'is_mailbox' => pacol(
0,
0,
1,
'int',
'',
'',
0,
# technically 'is_mailbox' is bool, but the automatic bool conversion breaks the query. Flagging it as int avoids this problem.
# Maybe having a vbool type (without the automatic conversion) would be cleaner - we'll see if we need it.
/*options*/ '',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'coalesce(__is_mailbox,0) as is_mailbox' ),
/*select*/ 'coalesce(__is_mailbox,0) as is_mailbox'
),
/*extrafrom set via set_is_mailbox_extrafrom() */
'__mailbox_username' => pacol( 0, 0, 1, 'vtxt', '' , '' , 0), # filled via is_mailbox
'goto_mailbox' => pacol( $mbgoto, $mbgoto,$mbgoto,'bool', 'pEdit_alias_forward_and_store' , '' , 0,
'__mailbox_username' => pacol(0, 0, 1, 'vtxt', '', '', 0), # filled via is_mailbox
'goto_mailbox' => pacol(
$mbgoto,
$mbgoto,
$mbgoto,
'bool',
'pEdit_alias_forward_and_store',
'',
0,
/*options*/ '',
/*not_in_db*/ 1
), # read_from_db_postprocess() sets the value
'on_vacation' => pacol(
1,
0,
1,
'bool',
'pUsersMenu_vacation',
'',
0,
/*options*/ '',
/*not_in_db*/ 1 ), # read_from_db_postprocess() sets the value
'on_vacation' => pacol( 1, 0, 1, 'bool', 'pUsersMenu_vacation' , '' , 0 ,
/*options*/ '',
/*not_in_db*/ 1 ), # read_from_db_postprocess() sets the value - TODO: read active flag from vacation table instead?
'created' => pacol( 0, 0, 0, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, 1, 'ts', 'last_modified' , '' ),
'active' => pacol( 1, 1, 1, 'bool', 'active' , '' , 1 ),
'_can_edit' => pacol( 0, 0, 1, 'vnum', '' , '' , 0 , '',
array('select' => '1 as _can_edit') ),
'_can_delete' => pacol( 0, 0, 1, 'vnum', '' , '' , 0 , '',
array('select' => '1 as _can_delete') ), # read_from_db_postprocess() updates the value
/*not_in_db*/ 1
), # read_from_db_postprocess() sets the value - TODO: read active flag from vacation table instead?
'created' => pacol(0, 0, 0, 'ts', 'created', ''),
'modified' => pacol(0, 0, 1, 'ts', 'last_modified', ''),
'active' => pacol(1, 1, 1, 'bool', 'active', '', 1),
'_can_edit' => pacol(
0,
0,
1,
'vnum',
'',
'',
0,
'',
array('select' => '1 as _can_edit')
),
'_can_delete' => pacol(
0,
0,
1,
'vnum',
'',
'',
0,
'',
array('select' => '1 as _can_delete')
), # read_from_db_postprocess() updates the value
# aliases listed in $CONF[default_aliases] are read-only for domain admins if $CONF[special_alias_control] is NO.
);
@ -77,7 +143,7 @@ class AliasHandler extends PFAHandler {
' FROM ' . table_by_key('mailbox') .
' WHERE username IS NOT NULL ';
if(isset($condition['domain']) && !isset($searchmode['domain']) && in_array($condition['domain'], $this->allowed_domains)) {
if (isset($condition['domain']) && !isset($searchmode['domain']) && in_array($condition['domain'], $this->allowed_domains)) {
# listing for a specific domain, so restrict subquery to that domain
$extrafrom .= ' AND ' . db_in_clause($this->domain_field, array($condition['domain']));
} else {
@ -140,7 +206,7 @@ class AliasHandler extends PFAHandler {
* It also calls parent::init()
*/
public function init($id) {
@list($local_part,$domain) = explode ('@', $id); # supress error message if $id doesn't contain '@'
@list($local_part, $domain) = explode('@', $id); # supress error message if $id doesn't contain '@'
if ($local_part == '*') { # catchall - postfix expects '@domain', not '*@domain'
$id = '@' . $domain;
@ -148,7 +214,9 @@ class AliasHandler extends PFAHandler {
$retval = parent::init($id);
if (!$retval) return false; # parent::init() failed, no need to continue
if (!$retval) {
return false;
} # parent::init() failed, no need to continue
# hide 'goto_mailbox' for non-mailbox aliases
# parent::init called view() before, so we can rely on having $this->result filled
@ -159,7 +227,7 @@ class AliasHandler extends PFAHandler {
$this->struct['goto_mailbox']['display_in_list'] = 0;
}
if ( !$this->new && $this->result['is_mailbox'] && $this->admin_username != ''&& !authentication_has_role('global-admin') ) {
if (!$this->new && $this->result['is_mailbox'] && $this->admin_username != ''&& !authentication_has_role('global-admin')) {
# domain admins are not allowed to change mailbox alias $CONF['alias_control_admin'] = NO
# TODO: apply the same restriction to superadmins?
if (!Config::bool('alias_control_admin')) {
@ -173,7 +241,7 @@ class AliasHandler extends PFAHandler {
}
protected function domain_from_id() {
list(/*NULL*/,$domain) = explode('@', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
return $domain;
}
@ -183,18 +251,18 @@ class AliasHandler extends PFAHandler {
return false;
}
list($local_part,$domain) = explode ('@', $this->id);
list($local_part, $domain) = explode('@', $this->id);
if(!$this->create_allowed($domain)) {
if (!$this->create_allowed($domain)) {
$this->errormsg[$this->id_field] = Config::lang('pCreate_alias_address_text_error3');
return false;
}
# TODO: already checked in set() - does it make sense to check it here also? Only advantage: it's an early check
# if (!in_array($domain, $this->allowed_domains)) {
# $this->errormsg[] = Config::lang('pCreate_alias_address_text_error1');
# return false;
# }
# if (!in_array($domain, $this->allowed_domains)) {
# $this->errormsg[] = Config::lang('pCreate_alias_address_text_error1');
# return false;
# }
if ($local_part == '') { # catchall
$valid = true;
@ -215,27 +283,37 @@ class AliasHandler extends PFAHandler {
* check number of existing aliases for this domain - is one more allowed?
*/
private function create_allowed($domain) {
if ($this->called_by == 'MailboxHandler') return true; # always allow creating an alias for a mailbox
if ($this->called_by == 'MailboxHandler') {
return true;
} # always allow creating an alias for a mailbox
$limit = get_domain_properties ($domain);
$limit = get_domain_properties($domain);
if ($limit['aliases'] == 0) return true; # unlimited
if ($limit['aliases'] < 0) return false; # disabled
if ($limit['alias_count'] >= $limit['aliases']) return false;
if ($limit['aliases'] == 0) {
return true;
} # unlimited
if ($limit['aliases'] < 0) {
return false;
} # disabled
if ($limit['alias_count'] >= $limit['aliases']) {
return false;
}
return true;
}
/**
* merge localpart and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/
/**
* merge localpart and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/
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 (empty($values['localpart']) || empty($values['domain']) ) { # localpart or domain not set
if (empty($values['localpart']) || empty($values['domain'])) { # localpart or domain not set
return "";
}
if ($values['localpart'] == '*') $values['localpart'] = ''; # catchall
if ($values['localpart'] == '*') {
$values['localpart'] = '';
} # catchall
return $values['localpart'] . '@' . $values['domain'];
} else {
return $values[$this->id_field];
@ -245,7 +323,7 @@ class AliasHandler extends PFAHandler {
protected function setmore($values) {
if ($this->new) {
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']);
$this->values['domain'] = $domain;
}
}
@ -268,7 +346,7 @@ class AliasHandler extends PFAHandler {
$values['on_vacation'] = $oldvalues['on_vacation'];
}
if ($values['on_vacation']) {
if ($values['on_vacation']) {
$values['goto'][] = $this->getVacationAlias();
}
@ -280,7 +358,7 @@ class AliasHandler extends PFAHandler {
$values['goto'][] = $this->id;
# if the alias points to the mailbox, don't display the "empty goto" error message
if (isset($this->errormsg['goto']) && $this->errormsg['goto'] == Config::lang('pEdit_alias_goto_text_error1') ) {
if (isset($this->errormsg['goto']) && $this->errormsg['goto'] == Config::lang('pEdit_alias_goto_text_error1')) {
unset($this->errormsg['goto']);
}
}
@ -302,7 +380,7 @@ class AliasHandler extends PFAHandler {
$db_result[$key]['goto'] = explode(',', $db_result[$key]['goto']);
# Vacation enabled?
list($db_result[$key]['on_vacation'], $db_result[$key]['goto']) = remove_from_array($db_result[$key]['goto'], $this->getVacationAlias() );
list($db_result[$key]['on_vacation'], $db_result[$key]['goto']) = remove_from_array($db_result[$key]['goto'], $this->getVacationAlias());
# if it is a mailbox, does the alias point to the mailbox?
if ($db_result[$key]['is_mailbox']) {
@ -316,8 +394,8 @@ class AliasHandler extends PFAHandler {
# editing a default alias (postmaster@ etc.) is only allowed if special_alias_control is allowed or if the user is a superadmin
$tmp = preg_split('/\@/', $db_result[$key]['address']);
if (!$this->is_superadmin && !Config::bool('special_alias_control') && array_key_exists($tmp[0], Config::Read('default_aliases'))) {
$db_result[$key]['_can_edit'] = 0;
$db_result[$key]['_can_delete'] = 0;
$db_result[$key]['_can_edit'] = 0;
$db_result[$key]['_can_delete'] = 0;
}
if ($this->struct['status']['display_in_list'] && Config::Bool('show_status')) {
@ -335,7 +413,7 @@ class AliasHandler extends PFAHandler {
$searchmode['__mailbox_username'] = 'NULL';
} else {
if ($condition != '') {
$condition = " ( $condition ) AND ";
$condition = " ( $condition ) AND ";
}
$condition = " $condition __mailbox_username IS NULL ";
}
@ -374,10 +452,10 @@ class AliasHandler extends PFAHandler {
# only allowed if $this->id is a catchall
# Note: alias domains are better, but we should keep this way supported for backward compatibility
# and because alias domains can't forward to external domains
list (/*NULL*/, $domain) = explode('@', $singlegoto);
list(/*NULL*/, $domain) = explode('@', $singlegoto);
$domain_check = check_domain($domain);
if ($domain_check != '') {
$errors[] = "$singlegoto: $domain_check";
$errors[] = "$singlegoto: $domain_check";
}
} else {
$email_check = check_email($singlegoto);
@ -398,32 +476,36 @@ class AliasHandler extends PFAHandler {
/**
* on $this->new, set localpart based on address
*/
protected function _missing_localpart ($field) {
protected function _missing_localpart($field) {
if (isset($this->RAWvalues['address'])) {
$parts = explode('@', $this->RAWvalues['address']);
if (count($parts) == 2) $this->RAWvalues['localpart'] = $parts[0];
if (count($parts) == 2) {
$this->RAWvalues['localpart'] = $parts[0];
}
}
}
/**
* on $this->new, set domain based on address
*/
protected function _missing_domain ($field) {
protected function _missing_domain($field) {
if (isset($this->RAWvalues['address'])) {
$parts = explode('@', $this->RAWvalues['address']);
if (count($parts) == 2) $this->RAWvalues['domain'] = $parts[1];
if (count($parts) == 2) {
$this->RAWvalues['domain'] = $parts[1];
}
}
}
/**
* Returns the vacation alias for this user.
* i.e. if this user's username was roger@example.com, and the autoreply domain was set to
* autoreply.fish.net in config.inc.php we'd return roger#example.com@autoreply.fish.net
* @return string an email alias.
*/
/**
* Returns the vacation alias for this user.
* i.e. if this user's username was roger@example.com, and the autoreply domain was set to
* autoreply.fish.net in config.inc.php we'd return roger#example.com@autoreply.fish.net
* @return string an email alias.
*/
protected function getVacationAlias() {
$vacation_goto = str_replace('@', '#', $this->id);
$vacation_goto = str_replace('@', '#', $this->id);
return $vacation_goto . '@' . Config::read('vacation_domain');
}
@ -431,7 +513,7 @@ class AliasHandler extends PFAHandler {
* @return true on success false on failure
*/
public function delete() {
if( ! $this->view() ) {
if (! $this->view()) {
$this->errormsg[] = Config::Lang('alias_does_not_exist');
return false;
}
@ -448,12 +530,11 @@ class AliasHandler extends PFAHandler {
db_delete('alias', 'address', $this->id);
list(/*NULL*/,$domain) = explode('@', $this->id);
db_log ($domain, 'delete_alias', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
db_log($domain, 'delete_alias', $this->id);
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->id);
return true;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -5,7 +5,6 @@
* Handlers User level alias actions - e.g. add alias, get aliases, update etc.
*/
class AliasdomainHandler extends PFAHandler {
protected $db_table = 'alias_domain';
protected $id_field = 'alias_domain';
protected $domain_field = 'alias_domain';
@ -15,14 +14,30 @@ class AliasdomainHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'alias_domain' => pacol( $this->new, 1, 1, 'enum', 'pCreate_alias_domain_alias' , 'pCreate_alias_domain_alias_text' , '',
'alias_domain' => pacol(
$this->new,
1,
1,
'enum',
'pCreate_alias_domain_alias',
'pCreate_alias_domain_alias_text',
'',
/*options, filled below*/ array(),
/* multiopt */ array('linkto' => 'list-virtual.php?domain=%s') ),
'target_domain' => pacol( 1, 1, 1, 'enum', 'pCreate_alias_domain_target' , 'pCreate_alias_domain_target_text', '',
/*options*/ array() /* filled below */ ),
'created' => pacol( 0, 0, 0, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, 1, 'ts', 'last_modified' , '' ),
'active' => pacol( 1, 1, 1, 'bool', 'active' , '' , 1 ),
/* multiopt */ array('linkto' => 'list-virtual.php?domain=%s')
),
'target_domain' => pacol(
1,
1,
1,
'enum',
'pCreate_alias_domain_target',
'pCreate_alias_domain_target_text',
'',
/*options*/ array() /* filled below */
),
'created' => pacol(0, 0, 0, 'ts', 'created', ''),
'modified' => pacol(0, 0, 1, 'ts', 'last_modified', ''),
'active' => pacol(1, 1, 1, 'bool', 'active', '', 1),
);
@ -31,7 +46,7 @@ class AliasdomainHandler extends PFAHandler {
$used_targets = array();
foreach ($this->allowed_domains as $dom) {
if (isset($this->result[$dom]) ) { # already used as alias_domain
if (isset($this->result[$dom])) { # already used as alias_domain
$used_targets[$this->result[$dom]['target_domain']] = $this->result[$dom]['target_domain'];
} else { # might be available
$this->struct['alias_domain']['options'][$dom] = $dom;
@ -40,12 +55,14 @@ class AliasdomainHandler extends PFAHandler {
}
foreach ($this->struct['alias_domain']['options'] as $dom) {
if (isset($used_targets[$dom])) unset ($this->struct['alias_domain']['options'][$dom]); # don't allow chained domain aliases (domain1 -> domain2 -> domain3)
if (isset($used_targets[$dom])) {
unset($this->struct['alias_domain']['options'][$dom]);
} # don't allow chained domain aliases (domain1 -> domain2 -> domain3)
}
if (count($this->struct['alias_domain']['options']) == 1) { # only one alias_domain available - filter it out from target_domain list
$keys = array_keys($this->struct['alias_domain']['options']);
unset ($this->struct['target_domain']['options'][$keys[0]]);
unset($this->struct['target_domain']['options'][$keys[0]]);
}
}
@ -53,8 +70,8 @@ class AliasdomainHandler extends PFAHandler {
$success = parent::init($id);
if ($success) {
if (count($this->struct['alias_domain']['options']) == 0 && $this->new) {
$this->errormsg[] = Config::lang('pCreate_alias_domain_error4');
return false;
$this->errormsg[] = Config::lang('pCreate_alias_domain_error4');
return false;
}
# TODO: check if target domains are available (in new and edit mode)
}
@ -92,23 +109,23 @@ class AliasdomainHandler extends PFAHandler {
);
}
protected function validate_new_id() {
return true; # alias_domain is enum, so we don't need to check its syntax etc.
}
protected function validate_new_id() {
return true; # alias_domain is enum, so we don't need to check its syntax etc.
}
/**
* @return true on success false on failure
*/
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?)
return false;
}
db_delete($this->db_table, $this->id_field, $this->id);
db_log ($this->id, 'delete_alias_domain', $this->result['target_domain']);
db_log($this->id, 'delete_alias_domain', $this->result['target_domain']);
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->result['alias_domain'] . ' -> ' . $this->result['target_domain']);
return true;
@ -124,7 +141,6 @@ class AliasdomainHandler extends PFAHandler {
}
return true;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,5 +1,5 @@
<?php
# $Id$
# $Id$
/**
* class to handle 'delete' in Cli
*/
@ -10,7 +10,6 @@ class CliDelete extends Shell {
* Execution method always used for tasks
*/
public function execute() {
if (empty($this->args)) {
$this->__interactive();
}
@ -33,7 +32,9 @@ class CliDelete extends Shell {
$question = "Do you really want to delete '$address'?";
$create = $this->in($question, array('y','n'));
if ($create == 'y') $this->__handle($address);
if ($create == 'y') {
$this->__handle($address);
}
}
/**
@ -47,7 +48,7 @@ class CliDelete extends Shell {
if (!$handler->init($address)) {
$this->err($handler->errormsg);
return;
}
}
if (!$handler->delete()) {
$this->err($handler->errormsg);
@ -77,10 +78,10 @@ class CliDelete extends Shell {
postfixadmin-cli $module delete <address>
Deletes $module <address> in non-interactive mode.
");
"
);
$this->_stop();
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,5 +1,5 @@
<?php
# $Id$
# $Id$
/**
* class to handle add and edit in Cli
*
@ -7,7 +7,6 @@
*/
class CliEdit extends Shell {
public $handler_to_use = "";
public $new = 0;
@ -29,7 +28,6 @@ class CliEdit extends Shell {
* The list of allowed params is based on $handler->struct
*/
private function __handle_params() {
$handler = new $this->handler_to_use($this->new);
$form_fields = $handler->getStruct();
$id_field = $handler->getId_field();
@ -37,7 +35,7 @@ class CliEdit extends Shell {
$values = array();
$param_error = 0;
foreach($this->params as $key => $val) {
foreach ($this->params as $key => $val) {
$key = preg_replace('/^-/', '', $key); # allow --param, not only -param
$key = str_replace('-', '_', $key); # allow --foo-bar even if field is named foo_bar
@ -45,13 +43,16 @@ class CliEdit extends Shell {
if ($form_fields[$key]['type'] == 'txtl') {
$values[$key] = explode(',', $val);
} elseif ($form_fields[$key]['type'] == 'bool') {
if (strtolower($val) == 'y') $val = 1; # convert y to 1
if (strtolower($val) == 'n') $val = 0; # convert n to 0
if (strtolower($val) == 'y') {
$val = 1;
} # convert y to 1
if (strtolower($val) == 'n') {
$val = 0;
} # convert n to 0
$values[$key] = $val; # don't modify any other value - *Handler will complain if it's invalid ;-)
} else {
$values[$key] = $val;
}
} elseif ($key == 'webroot') {
# always set, ignore
} else { # not editable, unknown field etc.
@ -60,7 +61,9 @@ class CliEdit extends Shell {
}
}
if ($param_error) $this->_stop(1);
if ($param_error) {
$this->_stop(1);
}
$this->__handle($this->args[0], $values);
}
@ -69,16 +72,15 @@ class CliEdit extends Shell {
* Interactive mode
*/
private function __interactive() {
$handler = new $this->handler_to_use($this->new);
$form_fields = $handler->getStruct();
$id_field = $handler->getId_field();
$values[$id_field] = '';
while($form_fields[$id_field]['editable'] != 0) { # endlees loop - except if input is valid or id_field is not editable (like auto_increment)
while ($form_fields[$id_field]['editable'] != 0) { # endlees loop - except if input is valid or id_field is not editable (like auto_increment)
$question = $form_fields[$id_field]['label'] . ":";
if ( $form_fields[$id_field]['desc'] != '') {
if ($form_fields[$id_field]['desc'] != '') {
$question .= "\n(" . $form_fields[$id_field]['desc'] . ')';
}
@ -95,33 +97,30 @@ class CliEdit extends Shell {
# update $form_fields (needed for example to display the correct allowed quota)
# TODO: doesn't (always?) work - wrong time for the refresh?
# $handler->set(array());
# $handler->set(array());
$form_fields = $handler->getStruct();
foreach($form_fields as $key => $field) {
foreach ($form_fields as $key => $field) {
if ($field['editable'] && $field['display_in_form'] && $key != $id_field) {
while(0==0) { # endlees loop - except if input is valid
while (0==0) { # endlees loop - except if input is valid
$question = $field['label'] . ':';
if ($field['desc'] != '') {
$question .= "\n(" . $field['desc'] . ')';
}
if ($field['type'] == 'bool') {
$values[$key] = $this->in($question, array ('y', 'n') );
$values[$key] = $this->in($question, array('y', 'n'));
if ($values[$key] == 'y') {
$values[$key] = 1;
} else {
$values[$key] = 0;
}
} elseif ($field['type'] == 'enum') {
$optiontxt = array();
$optionlist = array();
foreach ($field['options'] AS $optionkey => $optionval) {
foreach ($field['options'] as $optionkey => $optionval) {
// $this->in hates number 0
$optionkey = $optionkey + 1;
$optiontxt[] = '['.$optionkey.'] - '.$optionval;
@ -133,7 +132,6 @@ class CliEdit extends Shell {
$values[$key] = $this->in($question, $optionlist);
$values[$key] = $field['options'][$values[$key]-1]; # convert int to option name
} elseif ($field['type'] == 'txtl') {
$values[$key] = array();
$nextval = $this->in($question);
@ -143,17 +141,16 @@ class CliEdit extends Shell {
}
$nextval = $this->in("");
}
} else {
$values[$key] = $this->in($question);
}
if (is_null($values[$key]) ) { # TODO: insull() is probably obsoleted by change in Shell class
echo "*** value of $key is NULL - this should not happen! ***";
if (is_null($values[$key])) { # TODO: insull() is probably obsoleted by change in Shell class
echo "*** value of $key is NULL - this should not happen! ***";
}
if ($values[$key] == '' && (!$this->new) ) { # edit mode
unset ($values[$key]); # empty input - don't change
if ($values[$key] == '' && (!$this->new)) { # edit mode
unset($values[$key]); # empty input - don't change
}
# always use a fresh handler to avoid problems with previous error messages
@ -162,13 +159,12 @@ echo "*** value of $key is NULL - this should not happen! ***";
$handler->set($values);
if ( isset($handler->errormsg[$key]) ) { # only check the errormessage for this field
if (isset($handler->errormsg[$key])) { # only check the errormessage for this field
$this->err($handler->errormsg[$key]);
} else {
break;
}
} # end while
} # end if $field[editable] etc.
} # end foreach
@ -179,7 +175,6 @@ echo "*** value of $key is NULL - this should not happen! ***";
* (try to) store values
*/
private function __handle($id, $values) {
$handler = new $this->handler_to_use($this->new);
if (!$handler->init($id)) {
$this->err($handler->errormsg);
@ -230,19 +225,22 @@ echo "*** value of $key is NULL - this should not happen! ***";
$cmdtext $module in non-interactive mode.
Available options are:
");
"
);
$handler = new $this->handler_to_use($this->new);
$form_fields = $handler->getStruct();
$id_field = $handler->getId_field();
foreach($form_fields as $key => $field) {
foreach ($form_fields as $key => $field) {
if ($field['editable'] && $field['display_in_form'] && $key != $id_field) {
$optkey = str_replace('_', '-', $key);
$this->out(" --$optkey");
$this->out(" " . $field['label']);
if ($field['desc']) $this->out(" " . $field['desc']);
if ($field['desc']) {
$this->out(" " . $field['desc']);
}
$this->out("");
}
}
@ -251,6 +249,5 @@ echo "*** value of $key is NULL - this should not happen! ***";
$this->_stop();
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,21 +1,19 @@
<?php
# $Id$
# $Id$
class CliHelp extends Shell {
public $handler_to_use = "__not_set__";
/**
* Show help for this shell.
*
* @access public
*/
/**
* Show help for this shell.
*
* @access public
*/
public function execute() {
$this->help();
}
public function help() {
$handler = new $this->handler_to_use;
# TODO: adjust help text according to $handler->taskNames
@ -26,16 +24,17 @@ class CliHelp extends Shell {
"Usage:
postfixadmin-cli $module <task> [<address>] [--option value]
");
/*
View $module in interactive mode.
"
);
/*
View $module in interactive mode.
- or -
- or -
postfixadmin-cli $module view <address>
postfixadmin-cli $module view <address>
View $module <address> in non-interactive mode.
"); */
View $module <address> in non-interactive mode.
"); */
@ -46,11 +45,11 @@ class CliHelp extends Shell {
$commands = array(
'task' => "\t<task>\n" .
"\t\tAvailable values:\n\n".
"\t\t".sprintf("%-20s %s", "view: ", "View an existing $module.")."\n".
"\t\t".sprintf("%-20s %s", "add: ", "Add a $module.")."\n".
"\t\t".sprintf("%-20s %s", "update: ", "Update a $module.")."\n".
"\t\t".sprintf("%-20s %s", "delete: ", "Delete a $module")."\n",
'address' => "\t[<address>]\n" .
"\t\t".sprintf("%-20s %s", "view: ", "View an existing $module.")."\n".
"\t\t".sprintf("%-20s %s", "add: ", "Add a $module.")."\n".
"\t\t".sprintf("%-20s %s", "update: ", "Update a $module.")."\n".
"\t\t".sprintf("%-20s %s", "delete: ", "Delete a $module")."\n",
'address' => "\t[<address>]\n" .
"\t\tA address of recipient.\n",
);
@ -58,8 +57,6 @@ class CliHelp extends Shell {
$this->out("{$cmd}\n\n");
}
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,5 +1,5 @@
<?php
# $Id$
# $Id$
/**
* class to display the database scheme (for usage in upgrade.php) in Cli
*
@ -7,7 +7,6 @@
*/
class CliScheme extends Shell {
public $handler_to_use = "";
public $new = 0;
@ -16,7 +15,6 @@ class CliScheme extends Shell {
* Execution method always used for tasks
*/
public function execute() {
$module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module);
@ -95,10 +93,10 @@ class CliScheme extends Shell {
Print the $module database scheme in a way that can be
pasted into upgrade.php.
");
"
);
$this->_stop();
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,5 +1,5 @@
<?php
# $Id$
# $Id$
/**
* class to handle 'view' in Cli
*/
@ -10,7 +10,6 @@ class CliView extends Shell {
* Execution method always used for tasks
*/
public function execute() {
if (empty($this->args)) {
$this->__interactive();
}
@ -44,7 +43,7 @@ class CliView extends Shell {
if (!$handler->init($address)) {
$this->err($handler->errormsg);
return;
}
}
if (!$handler->view()) {
$this->err($handler->errormsg);
@ -54,7 +53,7 @@ class CliView extends Shell {
$result = $handler->result();
$struct = $handler->getStruct();
foreach(array_keys($struct) as $field) {
foreach (array_keys($struct) as $field) {
if (isset($struct[$field]) && empty($struct[$field]['label'])) {
# $struct[$field]['label'] = "--- $field ---";
$struct[$field]['display_in_list'] = 0;
@ -66,13 +65,13 @@ class CliView extends Shell {
$value = $result[$field];
$func="_formatted_".$field;
if (method_exists($handler, $func) ) {
if (method_exists($handler, $func)) {
$value = $handler->{$func}($result); # call _formatted_$fieldname()
}
}
if ($struct[$field]['type'] == 'txtl') {
# $value = join("\n" . str_repeat(" ", 20 + 2), $value); # multiline, one item per line
# $value = join("\n" . str_repeat(" ", 20 + 2), $value); # multiline, one item per line
$value = join(", ", $value); # one line, comma-separated
} elseif ($struct[$field]['type'] == 'bool') {
$value = Config::Lang($value ? 'YES' : 'NO');
@ -81,7 +80,6 @@ class CliView extends Shell {
$this->out(sprintf("%20s: %s", $struct[$field]['label'], $value));
}
}
}
/**
@ -105,10 +103,10 @@ class CliView extends Shell {
postfixadmin-cli $module view <address>
View $module <address> in non-interactive mode.
");
"
);
$this->_stop();
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,10 +1,9 @@
<?php
# $Id$
# This class is too static - if you inherit a class from it, it will share the static $instance and all its contents
# This class is too static - if you inherit a class from it, it will share the static $instance and all its contents
# Therefore the class is marked as final to prevent someone accidently does this ;-)
final class Config {
private static $instance = null;
# do not error_log() 'undefined config option' for deprecated options
@ -20,7 +19,7 @@ final class Config {
*/
public static function getInstance() {
if(self::$instance == null) {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
@ -62,7 +61,6 @@ final class Config {
break;
}
}
}
/**
@ -81,7 +79,7 @@ final class Config {
if ($var === 'all') {
$return = array();
foreach ($_this AS $key =>$var) {
foreach ($_this as $key =>$var) {
$return[$key] = $var;
}
return $return;
@ -107,14 +105,14 @@ final class Config {
break;
}
if ( !in_array(join('.', $name), self::$deprecated_options) ) {
if (!in_array(join('.', $name), self::$deprecated_options)) {
error_log('Config::read(): attempt to read undefined config option "' . join('.', $name) . '", returning null');
}
return null;
}
/**
/**
* read Config::$var and apply sprintf on it
* also checks if $var is changed by sprintf - if not, it writes a warning to error_log
*
@ -130,7 +128,9 @@ final class Config {
# check if sprintf changed something - if not, there are chances that $text didn't contain a %s
if ($text == $newtext) {
if (is_array($var)) $var = join('.', $var);
if (is_array($var)) {
$var = join('.', $var);
}
error_log("$var used via read_f, but nothing replaced (value $value)");
}
@ -175,19 +175,19 @@ final class Config {
/**
* Get translated text from $PALANG
* (wrapper for self::read(), see also the comments there)
*
* @param string $var Variable to obtain
* @return string value of $PALANG[$var]
* @access public
*/
/**
* Get translated text from $PALANG
* (wrapper for self::read(), see also the comments there)
*
* @param string $var Variable to obtain
* @return string value of $PALANG[$var]
* @access public
*/
public static function lang($var) {
return self::read(array('__LANG', $var));
}
/**
/**
* Get translated text from $PALANG and apply sprintf on it
* (wrapper for self::read_f(), see also the comments there)
*
@ -201,7 +201,7 @@ final class Config {
}
function getAll() {
public function getAll() {
$output = $this->config;
return $output;
}
@ -221,7 +221,6 @@ final class Config {
}
return $name;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -5,7 +5,6 @@
* Handlers User level alias actions - e.g. add alias, get aliases, update etc.
*/
class DomainHandler extends PFAHandler {
protected $db_table = 'domain';
protected $id_field = 'domain';
protected $domain_field = 'domain';
@ -47,64 +46,178 @@ class DomainHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'domain' => pacol( $this->new, 1, 1, 'text', 'domain' , '' , '', '',
array('linkto' => 'list-virtual.php?domain=%s') ),
'description' => pacol( $super, $super, $super, 'text', 'description' , '' ),
'domain' => pacol(
$this->new,
1,
1,
'text',
'domain',
'',
'',
'',
array('linkto' => 'list-virtual.php?domain=%s')
),
'description' => pacol($super, $super, $super, 'text', 'description', ''),
# Aliases
'aliases' => pacol( $super, $super, 0, 'num' , 'aliases' , 'pAdminEdit_domain_aliases_text' , Config::read('aliases') ),
'alias_count' => pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
'aliases' => pacol($super, $super, 0, 'num', 'aliases', 'pAdminEdit_domain_aliases_text', Config::read('aliases')),
'alias_count' => pacol(
0,
0,
1,
'vnum',
'',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'coalesce(__alias_count,0) - coalesce(__mailbox_count,0) as alias_count',
/*extrafrom*/ 'left join ( select count(*) as __alias_count, domain as __alias_domain from ' . table_by_key('alias') .
' group by domain) as __alias on domain = __alias_domain'),
'aliases_quot' => pacol( 0, 0, 1, 'quot', 'aliases' , '' , 0, '',
array('select' => db_quota_text( '__alias_count - coalesce(__mailbox_count,0)', 'aliases', 'aliases_quot')) ),
'_aliases_quot_percent' => pacol( 0, 0, 1, 'vnum', '' ,'' , 0, '',
array('select' => db_quota_percent('__alias_count - coalesce(__mailbox_count,0)', 'aliases', '_aliases_quot_percent')) ),
' group by domain) as __alias on domain = __alias_domain'
),
'aliases_quot' => pacol(
0,
0,
1,
'quot',
'aliases',
'',
0,
'',
array('select' => db_quota_text('__alias_count - coalesce(__mailbox_count,0)', 'aliases', 'aliases_quot'))
),
'_aliases_quot_percent' => pacol(
0,
0,
1,
'vnum',
'',
'',
0,
'',
array('select' => db_quota_percent('__alias_count - coalesce(__mailbox_count,0)', 'aliases', '_aliases_quot_percent'))
),
# Mailboxes
'mailboxes' => pacol( $super, $super, 0, 'num' , 'mailboxes' , 'pAdminEdit_domain_aliases_text' , Config::read('mailboxes') ),
'mailbox_count' => pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
'mailboxes' => pacol($super, $super, 0, 'num', 'mailboxes', 'pAdminEdit_domain_aliases_text', Config::read('mailboxes')),
'mailbox_count' => pacol(
0,
0,
1,
'vnum',
'',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'coalesce(__mailbox_count,0) as mailbox_count',
/*extrafrom*/ 'left join ( select count(*) as __mailbox_count, sum(quota) as __total_quota, domain as __mailbox_domain from ' . table_by_key('mailbox') .
' group by domain) as __mailbox on domain = __mailbox_domain'),
'mailboxes_quot' => pacol( 0, 0, 1, 'quot', 'mailboxes' , '' , 0, '',
array('select' => db_quota_text( '__mailbox_count', 'mailboxes', 'mailboxes_quot')) ),
'_mailboxes_quot_percent' => pacol( 0, 0, 1, 'vnum', '' , '' , 0, '',
array('select' => db_quota_percent('__mailbox_count', 'mailboxes', '_mailboxes_quot_percent')) ),
'maxquota' => pacol($editquota,$editquota,$quota, 'num' , 'pOverview_get_quota' , 'pAdminEdit_domain_maxquota_text' , Config::read('maxquota') ),
' group by domain) as __mailbox on domain = __mailbox_domain'
),
'mailboxes_quot' => pacol(
0,
0,
1,
'quot',
'mailboxes',
'',
0,
'',
array('select' => db_quota_text('__mailbox_count', 'mailboxes', 'mailboxes_quot'))
),
'_mailboxes_quot_percent' => pacol(
0,
0,
1,
'vnum',
'',
'',
0,
'',
array('select' => db_quota_percent('__mailbox_count', 'mailboxes', '_mailboxes_quot_percent'))
),
'maxquota' => pacol($editquota, $editquota, $quota, 'num', 'pOverview_get_quota', 'pAdminEdit_domain_maxquota_text', Config::read('maxquota')),
# Domain quota
'quota' => pacol($edit_dom_q,$edit_dom_q, 0, 'num', 'pAdminEdit_domain_quota' , 'pAdminEdit_domain_maxquota_text' , Config::read('domain_quota_default') ),
'total_quota' => pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
array('select' => "$query_used_domainquota AS total_quota") /*extrafrom*//* already in mailbox_count */ ),
'total_quot' => pacol( 0, 0, $dom_q, 'quot', 'pAdminEdit_domain_quota' , '' , 0, '',
array('select' => db_quota_text( $query_used_domainquota, 'quota', 'total_quot')) ),
'_total_quot_percent'=> pacol( 0, 0, $dom_q, 'vnum', '' , '' , 0, '',
array('select' => db_quota_percent($query_used_domainquota, 'quota', '_total_quot_percent')) ),
'transport' => pacol( $transp, $transp,$transp,'enum', 'transport' , 'pAdminEdit_domain_transport_text' , Config::read('transport_default') ,
/*options*/ Config::read('transport_options') ),
'backupmx' => pacol( $super, $super, 1, 'bool', 'pAdminEdit_domain_backupmx' , '' , 0),
'active' => pacol( $super, $super, 1, 'bool', 'active' , '' , 1 ),
'default_aliases' => pacol( $this->new, $this->new, 0, 'bool', 'pAdminCreate_domain_defaultaliases', '' , 1,'', /*not in db*/ 1 ),
'created' => pacol( 0, 0, 0, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, $super, 'ts', 'last_modified' , '' ),
'_can_edit' => pacol( 0, 0, 1, 'int', '' , '' , 0 ,
'quota' => pacol($edit_dom_q, $edit_dom_q, 0, 'num', 'pAdminEdit_domain_quota', 'pAdminEdit_domain_maxquota_text', Config::read('domain_quota_default')),
'total_quota' => pacol(
0,
0,
1,
'vnum',
'',
'',
'',
'',
array('select' => "$query_used_domainquota AS total_quota") /*extrafrom*//* already in mailbox_count */
),
'total_quot' => pacol(
0,
0,
$dom_q,
'quot',
'pAdminEdit_domain_quota',
'',
0,
'',
array('select' => db_quota_text($query_used_domainquota, 'quota', 'total_quot'))
),
'_total_quot_percent'=> pacol(
0,
0,
$dom_q,
'vnum',
'',
'',
0,
'',
array('select' => db_quota_percent($query_used_domainquota, 'quota', '_total_quot_percent'))
),
'transport' => pacol(
$transp,
$transp,
$transp,
'enum',
'transport',
'pAdminEdit_domain_transport_text',
Config::read('transport_default'),
/*options*/ Config::read('transport_options')
),
'backupmx' => pacol($super, $super, 1, 'bool', 'pAdminEdit_domain_backupmx', '', 0),
'active' => pacol($super, $super, 1, 'bool', 'active', '', 1),
'default_aliases' => pacol($this->new, $this->new, 0, 'bool', 'pAdminCreate_domain_defaultaliases', '', 1, '', /*not in db*/ 1),
'created' => pacol(0, 0, 0, 'ts', 'created', ''),
'modified' => pacol(0, 0, $super, 'ts', 'last_modified', ''),
'_can_edit' => pacol(
0,
0,
1,
'int',
'',
'',
0,
/*options*/ '',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ $this->is_superadmin . ' as _can_edit' ),
'_can_delete' => pacol( 0, 0, 1, 'int', '' , '' , 0 ,
/*select*/ $this->is_superadmin . ' as _can_edit'
),
'_can_delete' => pacol(
0,
0,
1,
'int',
'',
'',
0,
/*options*/ '',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ $this->is_superadmin . ' as _can_delete' ),
/*select*/ $this->is_superadmin . ' as _can_delete'
),
);
}
@ -159,7 +272,7 @@ class DomainHandler extends PFAHandler {
foreach (Config::read('default_aliases') as $address=>$goto) {
$address = $address . "@" . $this->id;
# if $goto doesn't contain @, let the alias point to the same domain
if(!strstr($goto, '@')) {
if (!strstr($goto, '@')) {
$goto = $goto . "@" . $this->id;
}
# TODO: use AliasHandler->add instead of writing directly to the alias table
@ -168,7 +281,7 @@ class DomainHandler extends PFAHandler {
'goto' => $goto,
'domain' => $this->id,
);
$result = db_insert ('alias', $arr);
$result = db_insert('alias', $arr);
# TODO: error checking
}
}
@ -193,13 +306,13 @@ class DomainHandler extends PFAHandler {
return false;
}
if ( ! $this->view() ) {
if (! $this->view()) {
$this->errormsg[] = Config::Lang('domain_does_not_exist'); # TODO: can users hit this message at all? init() should already fail...
return false;
}
if (Config::bool('alias_domain')) {
# check if this domain is an alias domain target - if yes, do not allow to delete it
# check if this domain is an alias domain target - if yes, do not allow to delete it
$handler = new AliasdomainHandler(0, $this->admin_username);
$handler->getList("target_domain = '" . escape_string($this->id) . "'");
$aliasdomains = $handler->result();
@ -210,33 +323,33 @@ class DomainHandler extends PFAHandler {
}
}
# the correct way would be to recursively delete mailboxes, aliases, alias_domains, fetchmail entries
# with *Handler before deleting the domain, but this would be terribly slow on domains with many aliases etc.,
# the correct way would be to recursively delete mailboxes, aliases, alias_domains, fetchmail entries
# with *Handler before deleting the domain, but this would be terribly slow on domains with many aliases etc.,
# so we do it the fast way on the database level
# cleaning up all tables doesn't hurt, even if vacation or displaying the quota is disabled
# some tables don't have a domain field, so we need a workaround
$like_domain = "LIKE '" . escape_string('%@' . $this->id) . "'";
db_delete('domain_admins', 'domain', $this->id);
db_delete('alias', 'domain', $this->id);
db_delete('mailbox', 'domain', $this->id);
db_delete('alias_domain', 'alias_domain', $this->id);
db_delete('vacation', 'domain', $this->id);
db_delete('vacation_notification', 'on_vacation', $this->id, "OR on_vacation $like_domain");
db_delete('quota', 'username', $this->id, "OR username $like_domain");
db_delete('quota2', 'username', $this->id, "OR username $like_domain");
db_delete('fetchmail', 'mailbox', $this->id, "OR mailbox $like_domain");
db_delete('log', 'domain', $this->id); # TODO: should we really delete the log?
db_delete('domain_admins', 'domain', $this->id);
db_delete('alias', 'domain', $this->id);
db_delete('mailbox', 'domain', $this->id);
db_delete('alias_domain', 'alias_domain', $this->id);
db_delete('vacation', 'domain', $this->id);
db_delete('vacation_notification', 'on_vacation', $this->id, "OR on_vacation $like_domain");
db_delete('quota', 'username', $this->id, "OR username $like_domain");
db_delete('quota2', 'username', $this->id, "OR username $like_domain");
db_delete('fetchmail', 'mailbox', $this->id, "OR mailbox $like_domain");
db_delete('log', 'domain', $this->id); # TODO: should we really delete the log?
# finally delete the domain
db_delete($this->db_table, $this->id_field, $this->id);
db_delete($this->db_table, $this->id_field, $this->id);
if ( !$this->domain_postdeletion() ) {
if (!$this->domain_postdeletion()) {
$this->error_msg[] = Config::Lang('domain_postdel_failed');
}
db_log ($this->id, 'delete_domain', $this->id); # TODO delete_domain is not a valid db_log keyword yet
db_log($this->id, 'delete_domain', $this->id); # TODO delete_domain is not a valid db_log keyword yet
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->id);
return true;
}
@ -248,9 +361,15 @@ class DomainHandler extends PFAHandler {
*
* @param array values of current item
*/
public function _formatted_aliases ($item) { return $item['alias_count'] . ' / ' . $item['aliases'] ; }
public function _formatted_mailboxes($item) { return $item['mailbox_count'] . ' / ' . $item['mailboxes']; }
public function _formatted_quota ($item) { return $item['total_quota'] . ' / ' . $item['quota'] ; }
public function _formatted_aliases($item) {
return $item['alias_count'] . ' / ' . $item['aliases'] ;
}
public function _formatted_mailboxes($item) {
return $item['mailbox_count'] . ' / ' . $item['mailboxes'];
}
public function _formatted_quota($item) {
return $item['total_quota'] . ' / ' . $item['quota'] ;
}
/**
* Called after a domain has been added
@ -274,14 +393,14 @@ class DomainHandler extends PFAHandler {
$retval=0;
$output=array();
$firstline='';
$firstline=exec($command,$output,$retval);
$firstline=exec($command, $output, $retval);
if (0!=$retval) {
error_log("Running $command yielded return value=$retval, first line of output=$firstline");
$this->errormsg[] = 'Problems running domain postcreation script!';
return FALSE;
return false;
}
return TRUE;
return true;
}
/**
@ -306,15 +425,14 @@ class DomainHandler extends PFAHandler {
$retval=0;
$output=array();
$firstline='';
$firstline=exec($command,$output,$retval);
$firstline=exec($command, $output, $retval);
if (0!=$retval) {
error_log("Running $command yielded return value=$retval, first line of output=$firstline");
$this->errormsg[] = 'Problems running domain postdeletion script!';
return FALSE;
return false;
}
return TRUE;
return true;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -5,7 +5,6 @@
* Handler for fetchmail jobs
*/
class FetchmailHandler extends PFAHandler {
protected $db_table = 'fetchmail';
protected $id_field = 'id';
protected $domain_field = 'domain';
@ -21,29 +20,29 @@ class FetchmailHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'id' => pacol( 0, 0, 1, 'num' , '' , '' , '', array(), 0, 1),
'domain' => pacol( 0, 0, 1, 'text', '' , '' ),
'mailbox' => pacol( 1, 1, 1, 'enum', 'pFetchmail_field_mailbox' , 'pFetchmail_desc_mailbox' ), # mailbox list
'src_server' => pacol( 1, 1, 1, 'text', 'pFetchmail_field_src_server' , 'pFetchmail_desc_src_server' ),
'src_auth' => pacol( 1, 1, 1, 'enum', 'pFetchmail_field_src_auth' , 'pFetchmail_desc_src_auth' , '', $src_auth_options),
'src_user' => pacol( 1, 1, 1, 'text', 'pFetchmail_field_src_user' , 'pFetchmail_desc_src_user' ),
'src_password' => pacol( 1, 1, 0, 'b64p', 'pFetchmail_field_src_password' , 'pFetchmail_desc_src_password' ),
'src_folder' => pacol( 1, 1, 1, 'text', 'pFetchmail_field_src_folder' , 'pFetchmail_desc_src_folder' ),
'poll_time' => pacol( 1, 1, 1, 'num' , 'pFetchmail_field_poll_time' , 'pFetchmail_desc_poll_time' , 10 ),
'fetchall' => pacol( 1, 1, 1, 'bool', 'pFetchmail_field_fetchall' , 'pFetchmail_desc_fetchall' ),
'keep' => pacol( 1, 1, 1, 'bool', 'pFetchmail_field_keep' , 'pFetchmail_desc_keep' ),
'protocol' => pacol( 1, 1, 1, 'enum', 'pFetchmail_field_protocol' , 'pFetchmail_desc_protocol' , '', $src_protocol_options),
'usessl' => pacol( 1, 1, 1, 'bool', 'pFetchmail_field_usessl' , 'pFetchmail_desc_usessl' ),
'sslcertck' => pacol( 1, 1, 1, 'bool', 'pFetchmail_field_sslcertck' , '' ),
'sslcertpath' => pacol( $extra, $extra, $extra, 'text', 'pFetchmail_field_sslcertpath' , '' ),
'sslfingerprint'=> pacol( $extra, $extra, $extra, 'text', 'pFetchmail_field_sslfingerprint','' ),
'extra_options' => pacol( $extra, $extra, $extra, 'text', 'pFetchmail_field_extra_options', 'pFetchmail_desc_extra_options' ),
'mda' => pacol( $extra, $extra, $extra, 'text', 'pFetchmail_field_mda' , 'pFetchmail_desc_mda' ),
'date' => pacol( 0, 0, 1, 'text', 'pFetchmail_field_date' , 'pFetchmail_desc_date' , '2000-01-01' ),
'returned_text' => pacol( 0, 0, 1, 'text', 'pFetchmail_field_returned_text', 'pFetchmail_desc_returned_text' ),
'active' => pacol( 1, 1, 1, 'bool', 'active' , '' , 1 ),
'created' => pacol( 0, 0, 0, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, 1, 'ts', 'last_modified' , '' ),
'id' => pacol(0, 0, 1, 'num', '', '', '', array(), 0, 1),
'domain' => pacol(0, 0, 1, 'text', '', ''),
'mailbox' => pacol(1, 1, 1, 'enum', 'pFetchmail_field_mailbox', 'pFetchmail_desc_mailbox'), # mailbox list
'src_server' => pacol(1, 1, 1, 'text', 'pFetchmail_field_src_server', 'pFetchmail_desc_src_server'),
'src_auth' => pacol(1, 1, 1, 'enum', 'pFetchmail_field_src_auth', 'pFetchmail_desc_src_auth', '', $src_auth_options),
'src_user' => pacol(1, 1, 1, 'text', 'pFetchmail_field_src_user', 'pFetchmail_desc_src_user'),
'src_password' => pacol(1, 1, 0, 'b64p', 'pFetchmail_field_src_password', 'pFetchmail_desc_src_password'),
'src_folder' => pacol(1, 1, 1, 'text', 'pFetchmail_field_src_folder', 'pFetchmail_desc_src_folder'),
'poll_time' => pacol(1, 1, 1, 'num', 'pFetchmail_field_poll_time', 'pFetchmail_desc_poll_time', 10),
'fetchall' => pacol(1, 1, 1, 'bool', 'pFetchmail_field_fetchall', 'pFetchmail_desc_fetchall'),
'keep' => pacol(1, 1, 1, 'bool', 'pFetchmail_field_keep', 'pFetchmail_desc_keep'),
'protocol' => pacol(1, 1, 1, 'enum', 'pFetchmail_field_protocol', 'pFetchmail_desc_protocol', '', $src_protocol_options),
'usessl' => pacol(1, 1, 1, 'bool', 'pFetchmail_field_usessl', 'pFetchmail_desc_usessl'),
'sslcertck' => pacol(1, 1, 1, 'bool', 'pFetchmail_field_sslcertck', ''),
'sslcertpath' => pacol($extra, $extra, $extra, 'text', 'pFetchmail_field_sslcertpath', ''),
'sslfingerprint'=> pacol($extra, $extra, $extra, 'text', 'pFetchmail_field_sslfingerprint', ''),
'extra_options' => pacol($extra, $extra, $extra, 'text', 'pFetchmail_field_extra_options', 'pFetchmail_desc_extra_options'),
'mda' => pacol($extra, $extra, $extra, 'text', 'pFetchmail_field_mda', 'pFetchmail_desc_mda'),
'date' => pacol(0, 0, 1, 'text', 'pFetchmail_field_date', 'pFetchmail_desc_date', '2000-01-01'),
'returned_text' => pacol(0, 0, 1, 'text', 'pFetchmail_field_returned_text', 'pFetchmail_desc_returned_text'),
'active' => pacol(1, 1, 1, 'bool', 'active', '', 1),
'created' => pacol(0, 0, 0, 'ts', 'created', ''),
'modified' => pacol(0, 0, 1, 'ts', 'last_modified', ''),
);
# get list of mailboxes (for currently logged in user)
@ -89,8 +88,8 @@ class FetchmailHandler extends PFAHandler {
protected function setmore($values) {
# set domain based on the target mailbox
if ($this->new || isset($values['mailbox']) ) {
list(/*NULL*/,$domain) = explode('@', $values['mailbox']);
if ($this->new || isset($values['mailbox'])) {
list(/*NULL*/, $domain) = explode('@', $values['mailbox']);
$this->values['domain'] = $domain;
$this->domain = $domain;
}
@ -112,14 +111,14 @@ class FetchmailHandler extends PFAHandler {
* @return true on success false on failure
*/
public function delete() {
if ( ! $this->view() ) {
if (! $this->view()) {
$this->errormsg[] = Config::lang($this->msg['error_does_not_exist']);
return false;
}
db_delete($this->db_table, $this->id_field, $this->id);
db_log ($this->id, 'delete_fetchmail', $this->result['id']);
db_log($this->id, 'delete_fetchmail', $this->result['id']);
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->result['src_user'] . ' -> ' . $this->result['mailbox']);
return true;
@ -175,7 +174,6 @@ class FetchmailHandler extends PFAHandler {
}
return true;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,11 +1,10 @@
<?php
# $Id$
# $Id$
/**
* Simple class to represent a user.
*/
class MailboxHandler extends PFAHandler {
protected $db_table = 'mailbox';
protected $id_field = 'username';
protected $domain_field = 'domain';
@ -17,39 +16,64 @@ class MailboxHandler extends PFAHandler {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'username' => pacol( $this->new, 1, 1, 'mail', 'pEdit_mailbox_username' , '' , '' ),
'local_part' => pacol( $this->new, 0, 0, 'text', 'pEdit_mailbox_username' , '' , '' ),
'domain' => pacol( $this->new, 0, 1, 'enum', '' , '' , '',
/*options*/ $this->allowed_domains ),
'username' => pacol($this->new, 1, 1, 'mail', 'pEdit_mailbox_username', '', ''),
'local_part' => pacol($this->new, 0, 0, 'text', 'pEdit_mailbox_username', '', ''),
'domain' => pacol(
$this->new,
0,
1,
'enum',
'',
'',
'',
/*options*/ $this->allowed_domains
),
# TODO: maildir: display in list is needed to include maildir in SQL result (for post_edit hook)
# TODO: (not a perfect solution, but works for now - maybe we need a separate "include in SELECT query" field?)
'maildir' => pacol( $this->new, 0, 1, 'text', '' , '' , '' ),
'password' => pacol( 1, 1, 0, 'pass', 'password' , 'pCreate_mailbox_password_text' , '' ),
'password2' => pacol( 1, 1, 0, 'pass', 'password_again' , '' , '',
'maildir' => pacol($this->new, 0, 1, 'text', '', '', ''),
'password' => pacol(1, 1, 0, 'pass', 'password', 'pCreate_mailbox_password_text', ''),
'password2' => pacol(
1,
1,
0,
'pass',
'password_again',
'',
'',
/*options*/ '',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'password as password2'
),
'name' => pacol( 1, 1, 1, 'text', 'name' , 'pCreate_mailbox_name_text' , '' ),
'quota' => pacol( 1, 1, 1, 'int' , 'pEdit_mailbox_quota' , 'pEdit_mailbox_quota_text' , '' ), # in MB
'name' => pacol(1, 1, 1, 'text', 'name', 'pCreate_mailbox_name_text', ''),
'quota' => pacol(1, 1, 1, 'int', 'pEdit_mailbox_quota', 'pEdit_mailbox_quota_text', ''), # in MB
# read_from_db_postprocess() also sets 'quotabytes' for use in init()
# TODO: read used quota from quota/quota2 table
'active' => pacol( 1, 1, 1, 'bool', 'active' , '' , 1 ),
'welcome_mail' => pacol( $this->new, $this->new, 0, 'bool', 'pCreate_mailbox_mail' , '' , 1,
'active' => pacol(1, 1, 1, 'bool', 'active', '', 1),
'welcome_mail' => pacol(
$this->new,
$this->new,
0,
'bool',
'pCreate_mailbox_mail',
'',
1,
/*options*/ '',
/*not_in_db*/ 1 ),
'phone' => pacol( 1, $passwordReset, 0, 'text', 'pCreate_mailbox_phone' , 'pCreate_mailbox_phone_desc' , ''),
'email_other' => pacol( 1, $passwordReset, 0, 'mail', 'pCreate_mailbox_email' , 'pCreate_mailbox_email_desc' , ''),
'token' => pacol( 1, 0, 0, 'text', '' , '' ),
'token_validity'=> pacol( 1, 0, 0, 'ts', '' , '', date("Y-m-d H:i:s",time())),
'created' => pacol( 0, 0, 1, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, 1, 'ts', 'last_modified' , '' ),
/*not_in_db*/ 1
),
'phone' => pacol(1, $passwordReset, 0, 'text', 'pCreate_mailbox_phone', 'pCreate_mailbox_phone_desc', ''),
'email_other' => pacol(1, $passwordReset, 0, 'mail', 'pCreate_mailbox_email', 'pCreate_mailbox_email_desc', ''),
'token' => pacol(1, 0, 0, 'text', '', ''),
'token_validity'=> pacol(1, 0, 0, 'ts', '', '', date("Y-m-d H:i:s", time())),
'created' => pacol(0, 0, 1, 'ts', 'created', ''),
'modified' => pacol(0, 0, 1, 'ts', 'last_modified', ''),
# TODO: add virtual 'notified' column and allow to display who received a vacation response?
);
# update allowed quota
if (count($this->struct['domain']['options']) > 0) $this->prefill('domain', $this->struct['domain']['options'][0]);
if (count($this->struct['domain']['options']) > 0) {
$this->prefill('domain', $this->struct['domain']['options'][0]);
}
}
public function init($id) {
@ -69,7 +93,7 @@ class MailboxHandler extends PFAHandler {
}
protected function domain_from_id() {
list(/*NULL*/,$domain) = explode('@', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
return $domain;
}
@ -78,8 +102,10 @@ class MailboxHandler extends PFAHandler {
* @param string - domain
* @param int - current quota
*/
protected function updateMaxquota ($domain, $currentquota) {
if ($domain == '') return false;
protected function updateMaxquota($domain, $currentquota) {
if ($domain == '') {
return false;
}
$maxquota = $this->allowed_quota($domain, $currentquota);
@ -109,13 +135,13 @@ class MailboxHandler extends PFAHandler {
}
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['local_part']['display_in_form'] = 1;
$this->struct['domain']['display_in_form'] = 1;
}
return array(
return array(
# $PALANG labels
'formtitle_create' => 'pCreate_mailbox_welcome',
'formtitle_edit' => 'pEdit_mailbox_welcome',
@ -137,14 +163,14 @@ class MailboxHandler extends PFAHandler {
}
$email_check = check_email($this->id);
if ( $email_check != '' ) {
if ($email_check != '') {
$this->errormsg[$this->id_field] = $email_check;
return false;
}
list(/*NULL*/,$domain) = explode ('@', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
if(!$this->create_allowed($domain)) {
if (!$this->create_allowed($domain)) {
$this->errormsg[] = Config::lang('pCreate_mailbox_username_text_error3');
return false;
}
@ -166,18 +192,24 @@ class MailboxHandler extends PFAHandler {
* check number of existing mailboxes for this domain - is one more allowed?
*/
private function create_allowed($domain) {
$limit = get_domain_properties ($domain);
$limit = get_domain_properties($domain);
if ($limit['mailboxes'] == 0) return true; # unlimited
if ($limit['mailboxes'] < 0) return false; # disabled
if ($limit['mailbox_count'] >= $limit['mailboxes']) return false;
if ($limit['mailboxes'] == 0) {
return true;
} # unlimited
if ($limit['mailboxes'] < 0) {
return false;
} # disabled
if ($limit['mailbox_count'] >= $limit['mailboxes']) {
return false;
}
return true;
}
/**
* merge local_part and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/
/**
* merge local_part and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/
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
return $values['local_part'] . '@' . $values['domain'];
@ -202,8 +234,7 @@ class MailboxHandler extends PFAHandler {
protected function beforestore() {
if ( isset($this->values['quota']) && $this->values['quota'] != -1 ) {
if (isset($this->values['quota']) && $this->values['quota'] != -1) {
$this->values['quota'] = $this->values['quota'] * Config::read('quota_multiplier'); # convert quota from MB to bytes
}
@ -211,7 +242,7 @@ class MailboxHandler extends PFAHandler {
$ah->calledBy('MailboxHandler');
if ( !$ah->init($this->id) ) {
if (!$ah->init($this->id)) {
$arraykeys = array_keys($ah->errormsg);
$this->errormsg[] = $ah->errormsg[$arraykeys[0]]; # TODO: implement this as PFAHandler->firstErrormsg()
return false;
@ -241,23 +272,20 @@ class MailboxHandler extends PFAHandler {
}
protected function storemore() {
if ($this->new) {
if ( !$this->mailbox_post_script() ) {
if (!$this->mailbox_post_script()) {
# return false; # TODO: should this be fatal?
}
if ($this->values['welcome_mail'] == true) {
if ( !$this->send_welcome_mail() ) {
if (!$this->send_welcome_mail()) {
# return false; # TODO: should this be fatal?
}
}
if ( !$this->create_mailbox_subfolders() ) {
if (!$this->create_mailbox_subfolders()) {
$this->infomsg[] = Config::lang_f('pCreate_mailbox_result_succes_nosubfolders', $this->id);
}
}
} else { # edit mode
# alias active status is updated in before_store()
@ -281,7 +309,7 @@ class MailboxHandler extends PFAHandler {
$quota = $oldvalues['quota'];
}
if ( !$this->mailbox_post_script() ) {
if (!$this->mailbox_post_script()) {
# TODO: should this be fatal?
}
}
@ -290,7 +318,7 @@ class MailboxHandler extends PFAHandler {
}
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...
return false;
}
@ -299,20 +327,20 @@ class MailboxHandler extends PFAHandler {
# deleting the mailbox, but it's easier and a bit faster to do it on the database level.
# cleaning up all tables doesn't hurt, even if vacation or displaying the quota is disabled
db_delete('fetchmail', 'mailbox', $this->id);
db_delete('vacation', 'email', $this->id);
db_delete('vacation_notification', 'on_vacation', $this->id); # should be caught by cascade, if PgSQL
db_delete('quota', 'username', $this->id);
db_delete('quota2', 'username', $this->id);
db_delete('alias', 'address', $this->id);
db_delete($this->db_table, $this->id_field, $this->id); # finally delete the mailbox
db_delete('fetchmail', 'mailbox', $this->id);
db_delete('vacation', 'email', $this->id);
db_delete('vacation_notification', 'on_vacation', $this->id); # should be caught by cascade, if PgSQL
db_delete('quota', 'username', $this->id);
db_delete('quota2', 'username', $this->id);
db_delete('alias', 'address', $this->id);
db_delete($this->db_table, $this->id_field, $this->id); # finally delete the mailbox
if ( !$this->mailbox_postdeletion() ) {
if (!$this->mailbox_postdeletion()) {
$this->error_msg[] = Config::Lang('mailbox_postdel_failed');
}
list(/*NULL*/,$domain) = explode('@', $this->id);
db_log ($domain, 'delete_mailbox', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
db_log($domain, 'delete_mailbox', $this->id);
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->id);
return true;
}
@ -330,7 +358,7 @@ class MailboxHandler extends PFAHandler {
* check if quota is allowed
*/
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');
return false;
}
@ -343,11 +371,13 @@ class MailboxHandler extends PFAHandler {
* - display password on $new if enabled in config or autogenerated
*/
protected function _validate_password($field, $val) {
if (!$this->_validate_password2($field, $val)) return false;
if (!$this->_validate_password2($field, $val)) {
return false;
}
if ($this->new && Config::read('generate_password') == 'YES' && $val == '') {
# auto-generate new password
unset ($this->errormsg[$field]); # remove "password too short" error message
unset($this->errormsg[$field]); # remove "password too short" error message
$val = generate_password();
$this->values[$field] = $val; # we are doing this "behind the back" of set()
$this->infomsg[] = Config::Lang('password') . ": $val";
@ -367,21 +397,21 @@ class MailboxHandler extends PFAHandler {
return $this->compare_password_fields('password', 'password2');
}
/**
* on $this->new, set localpart based on address
*/
protected function _missing_local_part ($field) {
list($local_part,$domain) = explode ('@', $this->id);
$this->RAWvalues['local_part'] = $local_part;
}
/**
* on $this->new, set localpart based on address
*/
protected function _missing_local_part($field) {
list($local_part, $domain) = explode('@', $this->id);
$this->RAWvalues['local_part'] = $local_part;
}
/**
* on $this->new, set domain based on address
*/
protected function _missing_domain ($field) {
list($local_part,$domain) = explode ('@', $this->id);
$this->RAWvalues['domain'] = $domain;
}
/**
* on $this->new, set domain based on address
*/
protected function _missing_domain($field) {
list($local_part, $domain) = explode('@', $this->id);
$this->RAWvalues['domain'] = $domain;
}
# TODO: read used quota from quota/quota2 table, then enable _formatted_quota()
# public function _formatted_quota ($item) { return $item['used_quota'] . ' / ' . $item['quota'] ; }
@ -392,12 +422,12 @@ class MailboxHandler extends PFAHandler {
* calculate maildir path for the mailbox
*/
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');
if($maildir_name_hook != 'NO' && function_exists($maildir_name_hook) ) {
$maildir = $maildir_name_hook ($domain, $this->id);
if ($maildir_name_hook != 'NO' && function_exists($maildir_name_hook)) {
$maildir = $maildir_name_hook($domain, $this->id);
} elseif (Config::bool('domain_path')) {
if (Config::bool('domain_in_mailbox')) {
$maildir = $domain . "/" . $this->id . "/";
@ -415,11 +445,13 @@ class MailboxHandler extends PFAHandler {
private function send_welcome_mail() {
$fTo = $this->id;
$fFrom = smtp_get_admin_email();
if(empty($fFrom) || $fFrom == 'CLI') $fFrom = $this->id;
if (empty($fFrom) || $fFrom == 'CLI') {
$fFrom = $this->id;
}
$fSubject = Config::lang('pSendmail_subject_text');
$fBody = Config::read('welcome_text');
if (!smtp_mail ($fTo, $fFrom, $fSubject, $fBody)) {
if (!smtp_mail($fTo, $fFrom, $fSubject, $fBody)) {
$this->errormsg[] = Config::lang_f('pSendmail_result_error', $this->id);
return false;
}
@ -435,15 +467,15 @@ class MailboxHandler extends PFAHandler {
* @return Boolean - true if requested quota is OK, otherwise false
*/
# TODO: merge with allowed_quota?
protected function check_quota ($quota) {
protected function check_quota($quota) {
$rval = false;
if ( !Config::bool('quota') ) {
if (!Config::bool('quota')) {
return true; # enforcing quotas is disabled - just allow it
}
list(/*NULL*/,$domain) = explode('@', $this->id);
$limit = get_domain_properties ($domain);
list(/*NULL*/, $domain) = explode('@', $this->id);
$limit = get_domain_properties($domain);
if ($limit['maxquota'] == 0) {
$rval = true; # maxquota unlimited -> OK, but domain level quota could still be hit
@ -468,7 +500,7 @@ class MailboxHandler extends PFAHandler {
}
# TODO: detailed error message ("domain quota exceeded", "mailbox quota too big" etc.) via flash_error? Or "available quota: xxx MB"?
if ( !Config::bool('domain_quota') ) {
if (!Config::bool('domain_quota')) {
return true; # enforcing domain_quota is disabled - just allow it
} elseif ($limit['quota'] <= 0) { # TODO: CHECK - 0 (unlimited) is fine, not sure about <= -1 (disabled)...
$rval = true;
@ -478,10 +510,10 @@ class MailboxHandler extends PFAHandler {
$table_mailbox = table_by_key('mailbox');
$query = "SELECT SUM(quota) FROM $table_mailbox WHERE domain = '" . escape_string($domain) . "'";
$query .= " AND username != '" . escape_string($this->id) . "'";
$result = db_query ($query);
$row = db_row ($result['result']);
$result = db_query($query);
$row = db_row($result['result']);
$cur_quota_total = divide_quota($row[0]); # convert to MB
if ( ($quota + $cur_quota_total) > $limit['quota'] ) {
if (($quota + $cur_quota_total) > $limit['quota']) {
$rval = false;
} else {
$rval = true;
@ -500,25 +532,25 @@ class MailboxHandler extends PFAHandler {
* @return Integer allowed maximum quota (in MB)
*/
protected function allowed_quota($domain, $current_user_quota) {
if ( !Config::bool('quota') ) {
return 0; # quota disabled means no limits - no need for more checks
}
if (!Config::bool('quota')) {
return 0; # quota disabled means no limits - no need for more checks
}
$domain_properties = get_domain_properties($domain);
$domain_properties = get_domain_properties($domain);
$tMaxquota = $domain_properties['maxquota'];
$tMaxquota = $domain_properties['maxquota'];
if (Config::bool('domain_quota') && $domain_properties['quota']) {
$dquota = $domain_properties['quota'] - $domain_properties['total_quota'] + divide_quota($current_user_quota);
if ($dquota < $tMaxquota) {
$tMaxquota = $dquota;
}
if (Config::bool('domain_quota') && $domain_properties['quota']) {
$dquota = $domain_properties['quota'] - $domain_properties['total_quota'] + divide_quota($current_user_quota);
if ($dquota < $tMaxquota) {
$tMaxquota = $dquota;
}
if ($tMaxquota == 0) {
$tMaxquota = $dquota;
}
}
return $tMaxquota;
if ($tMaxquota == 0) {
$tMaxquota = $dquota;
}
}
return $tMaxquota;
}
@ -528,7 +560,6 @@ class MailboxHandler extends PFAHandler {
* @return Boolean success/failure status
*/
protected function mailbox_post_script() {
if ($this->new) {
$cmd = Config::read('mailbox_postcreation_script');
$warnmsg = Config::Lang('mailbox_postcreate_failed');
@ -537,33 +568,37 @@ class MailboxHandler extends PFAHandler {
$warnmsg = Config::Lang('mailbox_postedit_failed');
}
if ( empty($cmd) ) return TRUE; # nothing to do
if (empty($cmd)) {
return true;
} # nothing to do
list(/*NULL*/,$domain) = explode('@', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
$quota = $this->values['quota'];
if ( empty($this->id) || empty($domain) || empty($this->values['maildir']) ) {
trigger_error('In '.__FUNCTION__.': empty username, domain and/or maildir parameter',E_USER_ERROR);
return FALSE;
if (empty($this->id) || empty($domain) || empty($this->values['maildir'])) {
trigger_error('In '.__FUNCTION__.': empty username, domain and/or maildir parameter', E_USER_ERROR);
return false;
}
$cmdarg1=escapeshellarg($this->id);
$cmdarg2=escapeshellarg($domain);
$cmdarg3=escapeshellarg($this->values['maildir']);
if ($quota <= 0) $quota = 0; # TODO: check if this is correct behaviour
if ($quota <= 0) {
$quota = 0;
} # TODO: check if this is correct behaviour
$cmdarg4=escapeshellarg($quota);
$command= "$cmd $cmdarg1 $cmdarg2 $cmdarg3 $cmdarg4";
$retval=0;
$output=array();
$firstline='';
$firstline=exec($command,$output,$retval);
$firstline=exec($command, $output, $retval);
if (0!=$retval) {
error_log("Running $command yielded return value=$retval, first line of output=$firstline");
$this->errormsg[] = $warnmsg;
return FALSE;
return false;
}
return TRUE;
return true;
}
/**
@ -575,11 +610,11 @@ class MailboxHandler extends PFAHandler {
protected function mailbox_postdeletion() {
$cmd = Config::read('mailbox_postdeletion_script');
if ( empty($cmd) ) {
if (empty($cmd)) {
return true;
}
list(/*NULL*/,$domain) = explode('@', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
if (empty($this->id) || empty($domain)) {
$this->errormsg[] = 'Empty username and/or domain parameter in mailbox_postdeletion';
@ -592,14 +627,14 @@ class MailboxHandler extends PFAHandler {
$retval=0;
$output=array();
$firstline='';
$firstline=exec($command,$output,$retval);
$firstline=exec($command, $output, $retval);
if (0!=$retval) {
error_log("Running $command yielded return value=$retval, first line of output=$firstline");
$this->errormsg[] = 'Problems running mailbox postdeletion script!';
return FALSE;
return false;
}
return TRUE;
return true;
}
@ -622,26 +657,28 @@ class MailboxHandler extends PFAHandler {
*/
protected function create_mailbox_subfolders() {
$create_mailbox_subdirs = Config::read('create_mailbox_subdirs');
if ( empty($create_mailbox_subdirs) ) return TRUE;
if (empty($create_mailbox_subdirs)) {
return true;
}
if ( !is_array($create_mailbox_subdirs) ) {
trigger_error('create_mailbox_subdirs must be an array',E_USER_ERROR);
return FALSE;
if (!is_array($create_mailbox_subdirs)) {
trigger_error('create_mailbox_subdirs must be an array', E_USER_ERROR);
return false;
}
$s_host = Config::read('create_mailbox_subdirs_host');
if ( empty($s_host) ) {
trigger_error('An IMAP/POP server host ($CONF["create_mailbox_subdirs_host"]) must be configured, if sub-folders are to be created',E_USER_ERROR);
return FALSE;
if (empty($s_host)) {
trigger_error('An IMAP/POP server host ($CONF["create_mailbox_subdirs_host"]) must be configured, if sub-folders are to be created', E_USER_ERROR);
return false;
}
$s_options='';
$create_mailbox_subdirs_hostoptions = Config::read('create_mailbox_subdirs_hostoptions');
if ( !empty($create_mailbox_subdirs_hostoptions )) {
if ( !is_array($create_mailbox_subdirs_hostoptions) ) {
trigger_error('The $CONF["create_mailbox_subdirs_hostoptions"] parameter must be an array',E_USER_ERROR);
return FALSE;
if (!empty($create_mailbox_subdirs_hostoptions)) {
if (!is_array($create_mailbox_subdirs_hostoptions)) {
trigger_error('The $CONF["create_mailbox_subdirs_hostoptions"] parameter must be an array', E_USER_ERROR);
return false;
}
foreach ($create_mailbox_subdirs_hostoptions as $o) {
$s_options.='/'.$o;
@ -650,11 +687,11 @@ class MailboxHandler extends PFAHandler {
$s_port='';
$create_mailbox_subdirs_hostport = Config::read('create_mailbox_subdirs_hostport');
if ( !empty($create_mailbox_subdirs_hostport) ) {
if (!empty($create_mailbox_subdirs_hostport)) {
$s_port = $create_mailbox_subdirs_hostport;
if (intval($s_port)!=$s_port) {
trigger_error('The $CONF["create_mailbox_subdirs_hostport"] parameter must be an integer',E_USER_ERROR);
return FALSE;
trigger_error('The $CONF["create_mailbox_subdirs_hostport"] parameter must be an integer', E_USER_ERROR);
return false;
}
$s_port=':'.$s_port;
}
@ -664,32 +701,32 @@ class MailboxHandler extends PFAHandler {
sleep(1); # give the mail triggering the mailbox creation a chance to do its job
$i=@imap_open($s, $this->id, $this->values['password']);
if (FALSE==$i) {
if (false==$i) {
error_log('Could not log into IMAP/POP server: ' . $this->id . ': ' . imap_last_error());
return FALSE;
return false;
}
$s_prefix = Config::read('create_mailbox_subdirs_prefix');
foreach($create_mailbox_subdirs as $f) {
foreach ($create_mailbox_subdirs as $f) {
$f='{'.$s_host.'}'.$s_prefix.$f;
$res=imap_createmailbox($i,$f);
$res=imap_createmailbox($i, $f);
if (!$res) {
error_log('Could not create IMAP folder $f: ' . $this->id . ': ' . imap_last_error());
@imap_close($i);
return FALSE;
return false;
}
@imap_subscribe($i,$f);
@imap_subscribe($i, $f);
}
@imap_close($i);
return TRUE;
return true;
}
/********************************************************************************************************************
old functions - we'll see what happens to them
(at least they should use the *Handler functions instead of doing SQL)
/********************************************************************************************************************/
/********************************************************************************************************************
old functions - we'll see what happens to them
(at least they should use the *Handler functions instead of doing SQL)
/********************************************************************************************************************/
/**
* @return boolean true on success; false on failure
@ -701,13 +738,13 @@ class MailboxHandler extends PFAHandler {
* as per the configuration in config.inc.php
*/
public function change_pw($new_password, $old_password, $match = true) {
list(/*NULL*/,$domain) = explode('@', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
if ($match == true) {
if (!$this->login($this->id, $old_password)) {
db_log ($domain, 'edit_password', "MATCH FAILURE: " . $this->id);
$this->errormsg[] = Config::Lang('pPassword_password_current_text_error');
return false;
db_log($domain, 'edit_password', "MATCH FAILURE: " . $this->id);
$this->errormsg[] = Config::Lang('pPassword_password_current_text_error');
return false;
}
}
@ -715,21 +752,20 @@ class MailboxHandler extends PFAHandler {
'password' => pacrypt($new_password) ,
);
$result = db_update('mailbox', 'username', $this->id, $set );
$result = db_update('mailbox', 'username', $this->id, $set);
if ($result != 1) {
db_log ($domain, 'edit_password', "FAILURE: " . $this->id);
db_log($domain, 'edit_password', "FAILURE: " . $this->id);
$this->errormsg[] = Config::lang('pEdit_mailbox_result_error');
return false;
}
db_log ($domain, 'edit_password', $this->id);
db_log($domain, 'edit_password', $this->id);
return true;
}
#TODO: more self explaining language strings!
#TODO: more self explaining language strings!
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -117,7 +117,7 @@ abstract class PFAHandler {
# (stored separately to make the functions reuseable)
# filled by initMsg()
protected $msg = array(
'can_create' => True,
'can_create' => true,
'confirm_delete' => 'confirm',
'list_header' => '', # headline used in list view
);
@ -143,9 +143,11 @@ abstract class PFAHandler {
$this->order_by = $this->id_field;
}
if ($new) $this->new = 1;
if ($new) {
$this->new = 1;
}
if ($is_admin) {
if ($is_admin) {
$this->admin_username = $username;
} else {
$this->username = $username;
@ -153,7 +155,7 @@ abstract class PFAHandler {
$this->is_superadmin = 0;
}
if ($username != "" && (! authentication_has_role('global-admin') ) ) {
if ($username != "" && (! authentication_has_role('global-admin'))) {
$this->is_superadmin = 0;
}
@ -174,7 +176,15 @@ abstract class PFAHandler {
$this->initStruct();
if (!isset($this->struct['_can_edit'])) {
$this->struct['_can_edit'] = pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
$this->struct['_can_edit'] = pacol(
0,
0,
1,
'vnum',
'',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ '1 as _can_edit'
@ -182,7 +192,15 @@ abstract class PFAHandler {
}
if (!isset($this->struct['_can_delete'])) {
$this->struct['_can_delete'] = pacol( 0, 0, 1, 'vnum', '' , '' , '', '',
$this->struct['_can_delete'] = pacol(
0,
0,
1,
'vnum',
'',
'',
'',
'',
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ '1 as _can_delete'
@ -190,7 +208,7 @@ abstract class PFAHandler {
}
$struct_hook = Config::read($this->db_table . '_struct_hook');
if ( $struct_hook != 'NO' && function_exists($struct_hook) ) {
if ($struct_hook != 'NO' && function_exists($struct_hook)) {
$this->struct = $struct_hook($this->struct);
}
@ -205,7 +223,9 @@ abstract class PFAHandler {
* to intentionally disable the check if $this->domain_field is empty, override this function
*/
protected function no_domain_field() {
if ($this->admin_username != "") die('Attemp to restrict domains without setting $this->domain_field!');
if ($this->admin_username != "") {
die('Attemp to restrict domains without setting $this->domain_field!');
}
}
/**
@ -214,7 +234,9 @@ abstract class PFAHandler {
* to intentionally disable the check if $this->user_field is empty, override this function
*/
protected function no_user_field() {
if ($this->username != '') die('Attemp to restrict users without setting $this->user_field!');
if ($this->username != '') {
die('Attemp to restrict users without setting $this->user_field!');
}
}
@ -266,7 +288,7 @@ abstract class PFAHandler {
* can also change $this->struct to something that makes the web interface better
* (for example, it can make local_part and domain editable as separate fields
* so that users can choose the domain from a dropdown)
*
*
* @return array
*/
abstract public function webformConfig();
@ -295,10 +317,10 @@ abstract class PFAHandler {
if ($exists) {
$this->errormsg[$this->id_field] = Config::lang($this->msg['error_already_exists']);
return false;
} elseif (!$this->validate_new_id() ) {
} elseif (!$this->validate_new_id()) {
# errormsg filled by validate_new_id()
return false;
# } else {
# } else {
# return true;
}
} else { # view or edit mode
@ -309,7 +331,7 @@ abstract class PFAHandler {
$this->can_edit = $this->result['_can_edit'];
$this->can_delete = $this->result['_can_delete'];
$this->label = $this->result[$this->label_field];
# return true;
# return true;
}
}
@ -349,7 +371,7 @@ abstract class PFAHandler {
*/
public function prefill($field, $val) {
$func="_prefill_".$field;
if (method_exists($this, $func) ) {
if (method_exists($this, $func)) {
$this->{$func}($field, $val); # call _missing_$fieldname()
} else {
$this->struct[$field]['default'] = $val;
@ -363,7 +385,7 @@ abstract class PFAHandler {
* error messages (if any) are stored in $this->errormsg
*/
public function set($values) {
if ( !$this->can_edit ) {
if (!$this->can_edit) {
$this->errormsg[] = Config::Lang_f('edit_not_allowed', $this->label);
return false;
}
@ -376,20 +398,20 @@ abstract class PFAHandler {
# Warning: $this->RAWvalues contains unchecked input data - use it carefully!
if ($this->new) {
foreach($this->struct as $key=>$row) {
if ($row['editable'] && !isset($values[$key]) ) {
foreach ($this->struct as $key=>$row) {
if ($row['editable'] && !isset($values[$key])) {
/**
* when creating a new item:
* if a field is editable and not set,
* if a field is editable and not set,
* - if $this->_missing_$fieldname() exists, call it
* (it can set $this->RAWvalues[$fieldname] - or do nothing if it can't set a useful value)
* - otherwise use the default value from $this->struct
* (if you don't want this, create an empty _missing_$fieldname() function)
*/
$func="_missing_".$key;
if (method_exists($this, $func) ) {
if (method_exists($this, $func)) {
$this->{$func}($key); # call _missing_$fieldname()
} else {
} else {
$this->set_default_value($key); # take default value from $this->struct
}
}
@ -401,7 +423,7 @@ abstract class PFAHandler {
# base validation
$this->values = array();
$this->values_valid = false;
foreach($this->struct as $key=>$row) {
foreach ($this->struct as $key=>$row) {
if ($row['editable'] == 0) { # not editable
if ($this->new == 1) {
# on $new, always set non-editable field to default value on $new (even if input data contains another value)
@ -415,24 +437,30 @@ abstract class PFAHandler {
$this->new == 1 || # create mode - or -
$this->skip_empty_pass != true # skip on empty (aka unchanged) password on edit
) {
# TODO: do not skip "password2" if "password" is filled, but "password2" is empty
# TODO: do not skip "password2" if "password" is filled, but "password2" is empty
$valid = true; # trust input unless validator objects
# validate based on field type ($this->_inp_$type)
$func="_inp_".$row['type'];
if (method_exists($this, $func) ) {
if (!$this->{$func}($key, $values[$key])) $valid = false;
if (method_exists($this, $func)) {
if (!$this->{$func}($key, $values[$key])) {
$valid = false;
}
} else {
# TODO: warning if no validation function exists?
}
# validate based on field name (_validate_$fieldname)
$func="_validate_".$key;
if (method_exists($this, $func) ) {
if (!$this->{$func}($key, $values[$key])) $valid = false;
if (method_exists($this, $func)) {
if (!$this->{$func}($key, $values[$key])) {
$valid = false;
}
}
if (isset($this->errormsg[$key]) && $this->errormsg[$key] != '') $valid = false;
if (isset($this->errormsg[$key]) && $this->errormsg[$key] != '') {
$valid = false;
}
if ($valid) {
$this->values[$key] = $values[$key];
@ -478,13 +506,13 @@ abstract class PFAHandler {
return false;
}
if ( !$this->beforestore() ) {
if (!$this->beforestore()) {
return false;
}
$db_values = $this->values;
foreach(array_keys($db_values) as $key) {
foreach (array_keys($db_values) as $key) {
switch ($this->struct[$key]['type']) { # modify field content for some types
case 'bool':
$db_values[$key] = db_get_boolean($db_values[$key]);
@ -498,11 +526,15 @@ abstract class PFAHandler {
case 'quot':
case 'vnum':
case 'vtxt':
unset ($db_values[$key]); # virtual field, never write it
unset($db_values[$key]); # virtual field, never write it
break;
}
if ($this->struct[$key]['not_in_db'] == 1) unset ($db_values[$key]); # remove 'not in db' columns
if ($this->struct[$key]['dont_write_to_db'] == 1) unset ($db_values[$key]); # remove 'dont_write_to_db' columns
if ($this->struct[$key]['not_in_db'] == 1) {
unset($db_values[$key]);
} # remove 'not in db' columns
if ($this->struct[$key]['dont_write_to_db'] == 1) {
unset($db_values[$key]);
} # remove 'dont_write_to_db' columns
}
if ($this->new) {
@ -518,7 +550,7 @@ abstract class PFAHandler {
$result = $this->storemore();
# db_log() even if storemore() failed
db_log ($this->domain, $this->msg['logname'], $this->id);
db_log($this->domain, $this->msg['logname'], $this->id);
if ($result) {
# return success message
@ -533,9 +565,9 @@ abstract class PFAHandler {
* called by $this->store() before storing the values in the database
* @return bool - if false, store() will abort
*/
protected function beforestore() {
protected function beforestore() {
return true; # do nothing, successfully ;-)
}
}
/**
* called by $this->store() after storing $this->values in the database
@ -570,7 +602,6 @@ abstract class PFAHandler {
} elseif (db_sqlite()) {
$formatted_date = "strftime(###KEY###, '" . escape_string(Config::Lang('dateformat_mysql')) . "')";
# $base64_decode = "base64_decode(###KEY###)";
} else {
$formatted_date = "DATE_FORMAT(###KEY###, '" . escape_string(Config::Lang('dateformat_mysql')) . "')";
# $base64_decode = "FROM_BASE64(###KEY###)"; # requires MySQL >= 5.6
@ -587,18 +618,21 @@ abstract class PFAHandler {
# get list of fields to display
$extrafrom = "";
foreach($this->struct as $key=>$row) {
if ( ($row['display_in_list'] != 0 || $row['display_in_form'] != 0) && $row['not_in_db'] == 0 ) {
if ($row['select'] != '') $key = $row['select'];
foreach ($this->struct as $key=>$row) {
if (($row['display_in_list'] != 0 || $row['display_in_form'] != 0) && $row['not_in_db'] == 0) {
if ($row['select'] != '') {
$key = $row['select'];
}
if ($row['extrafrom'] != '') $extrafrom = $extrafrom . " " . $row['extrafrom'] . "\n";
if ($row['extrafrom'] != '') {
$extrafrom = $extrafrom . " " . $row['extrafrom'] . "\n";
}
if (isset($colformat[$row['type']])) {
$select_cols[] = str_replace('###KEY###', $key, $colformat[$row['type']] );
$select_cols[] = str_replace('###KEY###', $key, $colformat[$row['type']]);
} else {
$select_cols[] = $key;
}
}
}
@ -611,7 +645,7 @@ abstract class PFAHandler {
}
# if logged in as user, restrict to the items the user is allowed to see
if ( (!$this->is_admin) && $this->user_field != '') {
if ((!$this->is_admin) && $this->user_field != '') {
$additional_where .= " AND " . $this->user_field . " = '" . escape_string($this->username) . "' ";
}
@ -626,7 +660,9 @@ abstract class PFAHandler {
}
$where = db_where_clause($condition, $this->struct, $additional_where, $searchmode);
} else {
if ($condition == "") $condition = '1=1';
if ($condition == "") {
$condition = '1=1';
}
$where = " WHERE ( $condition ) $additional_where";
}
@ -677,7 +713,7 @@ abstract class PFAHandler {
$db_result = array();
if ($result['rows'] != 0) {
while ($row = db_assoc ($result['result'])) {
while ($row = db_assoc($result['result'])) {
$db_result[$row[$this->id_field]] = $row;
}
}
@ -697,20 +733,22 @@ abstract class PFAHandler {
/**
* get the values of an item
* @param boolean (optional) - if false, $this->errormsg[] will not be filled in case of errors
* @param boolean (optional) - if false, $this->errormsg[] will not be filled in case of errors
* @return bool - true if item was found
* The data is stored in $this->result (as associative array of column => value)
* error messages (if any) are stored in $this->errormsg
*/
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) {
$this->result = $result[$this->id];
return true;
}
if ($errors) $this->errormsg[] = Config::lang($this->msg['error_does_not_exist']);
# $this->errormsg[] = $result['error'];
if ($errors) {
$this->errormsg[] = Config::lang($this->msg['error_does_not_exist']);
}
# $this->errormsg[] = $result['error'];
return false;
}
@ -729,7 +767,7 @@ abstract class PFAHandler {
$real_condition = array();
foreach ($condition as $key => $value) {
# allow only access to fields the user can access to avoid information leaks via search parameters
if (isset($this->struct[$key]) && ($this->struct[$key]['display_in_list'] || $this->struct[$key]['display_in_form']) ) {
if (isset($this->struct[$key]) && ($this->struct[$key]['display_in_list'] || $this->struct[$key]['display_in_form'])) {
$real_condition[$key] = $value;
} elseif (($key == '_') && count($this->searchfields)) {
$real_condition[$key] = $value;
@ -765,15 +803,15 @@ abstract class PFAHandler {
$username = escape_string($username);
$table = table_by_key($this->db_table);
$active = db_get_boolean(True);
$active = db_get_boolean(true);
$query = "SELECT password FROM $table WHERE " . $this->id_field . "='$username' AND active='$active'";
$result = db_query ($query);
$result = db_query($query);
if ($result['rows'] == 1) {
$row = db_array ($result['result']);
$crypt_password = pacrypt ($password, $row['password']);
$row = db_array($result['result']);
$crypt_password = pacrypt($password, $row['password']);
if($row['password'] == $crypt_password) {
if ($row['password'] == $crypt_password) {
return true;
}
}
@ -785,7 +823,7 @@ abstract class PFAHandler {
* @param string $username
* @return false|string
*/
function getPasswordRecoveryCode($username) {
public function getPasswordRecoveryCode($username) {
if ($this->init($username)) {
$token = generate_password();
$updatedRows = db_update($this->db_table, $this->id_field, $username, array(
@ -810,15 +848,15 @@ abstract class PFAHandler {
$username = escape_string($username);
$table = table_by_key($this->db_table);
$active = db_get_boolean(True);
$active = db_get_boolean(true);
$query = "SELECT token FROM $table WHERE " . $this->id_field . "='$username' AND token <> '' AND active='$active' AND NOW() < token_validity";
$result = db_query ($query);
$result = db_query($query);
if ($result['rows'] == 1) {
$row = db_array($result['result']);
$crypt_token = pacrypt($token, $row['token']);
if($row['token'] == $crypt_token) {
if ($row['token'] == $crypt_token) {
db_update($this->db_table, $this->id_field, $username, array(
'token' => '',
'token_validity' => '2000-01-01 00:00:00',
@ -860,7 +898,7 @@ abstract class PFAHandler {
*/
protected function compare_password_fields($field1, $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;
}
@ -891,8 +929,12 @@ abstract class PFAHandler {
*/
protected function _inp_num($field, $val) {
$valid = is_numeric($val);
if ($val < -1) $valid = false;
if (!$valid) $this->errormsg[$field] = Config::Lang_f('must_be_numeric', $field);
if ($val < -1) {
$valid = false;
}
if (!$valid) {
$this->errormsg[$field] = Config::Lang_f('must_be_numeric', $field);
}
return $valid;
# return (int)($val);
}
@ -901,7 +943,9 @@ abstract class PFAHandler {
* check if value is (numeric) boolean - in other words: 0 or 1
*/
protected function _inp_bool($field, $val) {
if ($val == "0" || $val == "1") return true;
if ($val == "0" || $val == "1") {
return true;
}
$this->errormsg[$field] = Config::Lang_f('must_be_boolean', $field);
return false;
# return $val ? db_get_boolean(true): db_get_boolean(false);
@ -911,7 +955,9 @@ abstract class PFAHandler {
* check if value of an enum field is in the list of allowed values
*/
protected function _inp_enum($field, $val) {
if(in_array($val, $this->struct[$field]['options'])) return true;
if (in_array($val, $this->struct[$field]['options'])) {
return true;
}
$this->errormsg[$field] = Config::Lang_f('invalid_value_given', $field);
return false;
}
@ -920,7 +966,9 @@ abstract class PFAHandler {
* check if value of an enum field is in the list of allowed values
*/
protected function _inp_enma($field, $val) {
if(array_key_exists($val, $this->struct[$field]['options'])) return true;
if (array_key_exists($val, $this->struct[$field]['options'])) {
return true;
}
$this->errormsg[$field] = Config::Lang_f('invalid_value_given', $field);
return false;
}
@ -928,14 +976,15 @@ abstract class PFAHandler {
/**
* check if a password is secure enough
*/
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
if(count($validpass) == 0) return true;
if (count($validpass) == 0) {
return true;
}
$this->errormsg[$field] = $validpass[0]; # TODO: honor all error messages, not only the first one?
return false;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,36 +1,34 @@
<?php
# $Id$
# $Id$
class VacationHandler extends PFAHandler {
protected $db_table = 'vacation';
protected $id_field = 'email';
protected $domain_field = 'domain';
function init($id) {
die('VacationHandler is not yet ready to be used with *Handler methods'); # obvious TODO: remove when it's ready ;-)
public function init($id) {
die('VacationHandler is not yet ready to be used with *Handler methods'); # obvious TODO: remove when it's ready ;-)
}
protected function initStruct() {
$this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list
'email' => pacol( $this->new, 1, 1, 'text', 'pLogin_username' , '' , '' ),
'domain' => pacol( 1, 0, 0, 'text', '' , '' , '' ),
'subject' => pacol( 1, 1, 0, 'text', 'pUsersVacation_subject' , '' , '' ),
'body' => pacol( 1, 1, 0, 'text', 'pUsersVacation_body' , '' , '' ),
'activefrom' => pacol( 1, 1, 1, 'text', 'pUsersVacation_activefrom' , '' , '' ),
'activeuntil' => pacol( 1, 1, 1, 'text', 'pUsersVacation_activeuntil' , '' , '' ),
'active' => pacol( 1, 1, 1, 'bool', 'active' , '' , 1 ),
'created' => pacol( 0, 0, 1, 'ts', 'created' , '' ),
'modified' => pacol( 0, 0, 1, 'ts', 'last_modified' , '' ),
'email' => pacol($this->new, 1, 1, 'text', 'pLogin_username', '', ''),
'domain' => pacol(1, 0, 0, 'text', '', '', ''),
'subject' => pacol(1, 1, 0, 'text', 'pUsersVacation_subject', '', ''),
'body' => pacol(1, 1, 0, 'text', 'pUsersVacation_body', '', ''),
'activefrom' => pacol(1, 1, 1, 'text', 'pUsersVacation_activefrom', '', ''),
'activeuntil' => pacol(1, 1, 1, 'text', 'pUsersVacation_activeuntil', '', ''),
'active' => pacol(1, 1, 1, 'bool', 'active', '', 1),
'created' => pacol(0, 0, 1, 'ts', 'created', ''),
'modified' => pacol(0, 0, 1, 'ts', 'last_modified', ''),
# TODO: add virtual 'notified' column and allow to display who received a vacation response?
);
if ( ! db_pgsql() ) {
$this->struct['cache'] = pacol( 0, 0, 0, 'text', '' , '' , '' ); # leftover from 2.2
if (! db_pgsql()) {
$this->struct['cache'] = pacol(0, 0, 0, 'text', '', '', ''); # leftover from 2.2
}
}
protected function initMsg() {
@ -66,31 +64,32 @@ class VacationHandler extends PFAHandler {
protected function validate_new_id() {
# vacation can only be enabled if a mailbox with this name exists
$handler = new MailboxHandler();
return $handler->init($address);
return $handler->init($address);
}
public function delete() {
$this->errormsg[] = '*** deletion not implemented yet ***';
return false; # XXX function aborts here! XXX
}
protected $username = null;
function __construct($username) {
public function __construct($username) {
$this->username = $username;
$this->id = $username;
}
/**
* Removes the autoreply alias etc for this user; namely, if they're away we remove their vacation alias and
* Removes the autoreply alias etc for this user; namely, if they're away we remove their vacation alias and
* set the vacation table record to false.
* @return boolean true on success.
*/
function remove() {
if (!$this->updateAlias(0)) return false;
public function remove() {
if (!$this->updateAlias(0)) {
return false;
}
// tidy up vacation table.
$vacation_data = array(
@ -106,7 +105,7 @@ class VacationHandler extends PFAHandler {
/**
* @return boolean true indicates this server supports vacation messages, and users are able to change their own.
*/
function vacation_supported() {
public function vacation_supported() {
return Config::bool('vacation') && Config::bool('vacation_control');
}
@ -114,7 +113,7 @@ class VacationHandler extends PFAHandler {
* @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?
*/
function check_vacation() {
public function check_vacation() {
$handler = new AliasHandler();
if (!$handler->init($this->id)) {
@ -129,29 +128,31 @@ class VacationHandler extends PFAHandler {
$result = $handler->result();
if ($result['on_vacation']) return true;
if ($result['on_vacation']) {
return true;
}
return false;
}
/**
* Retrieve information on someone who is on vacation
* @return struct|boolean stored information on vacation - array(subject - string, message - string, active - boolean, activeFrom - date, activeUntil - date)
* will return false if no existing data
* @return struct|boolean stored information on vacation - array(subject - string, message - string, active - boolean, activeFrom - date, activeUntil - date)
* will return false if no existing data
*/
function get_details() {
public function get_details() {
$table_vacation = table_by_key('vacation');
$E_username = escape_string($this->username);
$sql = "SELECT * FROM $table_vacation WHERE email = '$E_username'";
$result = db_query($sql);
if($result['rows'] != 1) {
if ($result['rows'] != 1) {
return false;
}
$row = db_array($result['result']);
$boolean = ($row['active'] == db_get_boolean(true));
# TODO: only return true and store the db result array in $this->whatever for consistency with the other classes
return array(
return array(
'subject' => $row['subject'],
'body' => $row['body'],
'active' => $boolean ,
@ -167,13 +168,13 @@ class VacationHandler extends PFAHandler {
* @param date $activeFrom
* @param date $activeUntil
*/
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.
$E_username = escape_string($this->username);
$activeFrom = date ("Y-m-d 00:00:00", strtotime ($activeFrom)); # TODO check if result looks like a valid date
$activeUntil = date ("Y-m-d 23:59:59", strtotime ($activeUntil)); # TODO check if result looks like a valid date
list(/*NULL*/,$domain) = explode('@', $this->username);
$activeFrom = date("Y-m-d 00:00:00", strtotime($activeFrom)); # TODO check if result looks like a valid date
$activeUntil = date("Y-m-d 23:59:59", strtotime($activeUntil)); # TODO check if result looks like a valid date
list(/*NULL*/, $domain) = explode('@', $this->username);
$vacation_data = array(
'email' => $this->username,
@ -186,14 +187,14 @@ class VacationHandler extends PFAHandler {
'activeuntil' => $activeUntil,
);
if ( ! db_pgsql() ) {
if (! db_pgsql()) {
$vacation_data['cache'] = ''; # leftover from 2.2
}
// is there an entry in the vacaton table for the user, or do we need to insert?
$table_vacation = table_by_key('vacation');
$result = db_query("SELECT * FROM $table_vacation WHERE email = '$E_username'");
if($result['rows'] == 1) {
if ($result['rows'] == 1) {
$result = db_update('vacation', 'email', $this->username, $vacation_data);
} else {
$result = db_insert('vacation', $vacation_data);
@ -216,7 +217,7 @@ class VacationHandler extends PFAHandler {
return false;
}
$values = array (
$values = array(
'on_vacation' => $vacationActive,
);
@ -235,6 +236,5 @@ class VacationHandler extends PFAHandler {
# still here? then everything worked
return true;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: backup.php
* Used to save all settings - but only works for MySQL databases.
* Template File: -none-
@ -28,60 +28,56 @@ authentication_require_role('global-admin');
// TODO: make backup supported for postgres
if (db_pgsql()) {
flash_error('Sorry: Backup is currently not supported for your DBMS ('.$CONF['database_type'].').');
$smarty->assign ('smarty_template', 'message');
$smarty->display ('index.tpl');
die;
flash_error('Sorry: Backup is currently not supported for your DBMS ('.$CONF['database_type'].').');
$smarty->assign('smarty_template', 'message');
$smarty->display('index.tpl');
die;
}
if (safeget('download') == "") {
$smarty->assign ('smarty_template', 'backupwarning');
$smarty->display ('index.tpl');
die;
$smarty->assign('smarty_template', 'backupwarning');
$smarty->display('index.tpl');
die;
}
# Still here? Then let's create the database dump...
/*
SELECT attnum,attname,typname,atttypmod-4,attnotnull,atthasdef,adsrc
AS def FROM pg_attribute,pg_class,pg_type,pg_attrdef
WHERE pg_class.oid=attrelid AND pg_type.oid=atttypid
AND attnum>0 AND pg_class.oid=adrelid AND adnum=attnum AND atthasdef='t' AND lower(relname)='admin'
UNION SELECT attnum,attname,typname,atttypmod-4,attnotnull,atthasdef,''
AS def FROM pg_attribute,pg_class,pg_type
WHERE pg_class.oid=attrelid
AND pg_type.oid=atttypid
AND attnum>0
AND atthasdef='f'
AND lower(relname)='admin'
SELECT attnum,attname,typname,atttypmod-4,attnotnull,atthasdef,adsrc
AS def FROM pg_attribute,pg_class,pg_type,pg_attrdef
WHERE pg_class.oid=attrelid AND pg_type.oid=atttypid
AND attnum>0 AND pg_class.oid=adrelid AND adnum=attnum AND atthasdef='t' AND lower(relname)='admin'
UNION SELECT attnum,attname,typname,atttypmod-4,attnotnull,atthasdef,''
AS def FROM pg_attribute,pg_class,pg_type
WHERE pg_class.oid=attrelid
AND pg_type.oid=atttypid
AND attnum>0
AND atthasdef='f'
AND lower(relname)='admin'
$db = $_GET['db'];
$cmd = "pg_dump -c -D -f /tix/miner/miner.sql -F p -N -U postgres $db";
$res = `$cmd`;
// Alternate: $res = shell_exec($cmd);
echo $res;
echo $res;
*/
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
umask (077);
$path = (ini_get('upload_tmp_dir') != '') ? ini_get('upload_tmp_dir') : '/tmp';
date_default_timezone_set(@date_default_timezone_get()); # Suppress date.timezone warnings
$filename = "postfixadmin-" . date ("Ymd") . "-" . getmypid() . ".sql";
$backup = $path . DIRECTORY_SEPARATOR . $filename;
if ($_SERVER['REQUEST_METHOD'] == "GET") {
umask(077);
$path = (ini_get('upload_tmp_dir') != '') ? ini_get('upload_tmp_dir') : '/tmp';
date_default_timezone_set(@date_default_timezone_get()); # Suppress date.timezone warnings
$filename = "postfixadmin-" . date("Ymd") . "-" . getmypid() . ".sql";
$backup = $path . DIRECTORY_SEPARATOR . $filename;
$header = "#\n# Postfix Admin $version\n# Date: " . date ("D M j G:i:s T Y") . "\n#\n";
$header = "#\n# Postfix Admin $version\n# Date: " . date("D M j G:i:s T Y") . "\n#\n";
if (!$fh = fopen ($backup, 'w'))
{
flash_error("<div class=\"error_msg\">Cannot open file ($backup)</div>");
$smarty->assign ('smarty_template', 'message');
$smarty->display ('index.tpl');
}
else
{
fwrite ($fh, $header);
if (!$fh = fopen($backup, 'w')) {
flash_error("<div class=\"error_msg\">Cannot open file ($backup)</div>");
$smarty->assign('smarty_template', 'message');
$smarty->display('index.tpl');
} else {
fwrite($fh, $header);
$tables = array(
$tables = array(
'admin',
'alias',
'alias_domain',
@ -91,50 +87,43 @@ if ($_SERVER['REQUEST_METHOD'] == "GET")
'fetchmail',
'log',
'mailbox',
'quota',
'quota2',
'quota',
'quota2',
'vacation',
'vacation_notification'
);
for ($i = 0 ; $i < sizeof ($tables) ; ++$i)
{
$result = db_query ("SHOW CREATE TABLE " . table_by_key($tables[$i]));
if ($result['rows'] > 0)
{
while ($row = db_array ($result['result']))
{
fwrite ($fh, "$row[1];\n\n");
for ($i = 0 ; $i < sizeof($tables) ; ++$i) {
$result = db_query("SHOW CREATE TABLE " . table_by_key($tables[$i]));
if ($result['rows'] > 0) {
while ($row = db_array($result['result'])) {
fwrite($fh, "$row[1];\n\n");
}
}
}
}
}
for ($i = 0 ; $i < sizeof ($tables) ; ++$i)
{
$result = db_query ("SELECT * FROM " . table_by_key($tables[$i]));
if ($result['rows'] > 0)
{
while ($row = db_assoc ($result['result']))
{
$fields = array_keys($row);
$values = array_values($row);
$values = array_map('escape_string', $values);
for ($i = 0 ; $i < sizeof($tables) ; ++$i) {
$result = db_query("SELECT * FROM " . table_by_key($tables[$i]));
if ($result['rows'] > 0) {
while ($row = db_assoc($result['result'])) {
$fields = array_keys($row);
$values = array_values($row);
$values = array_map('escape_string', $values);
fwrite ($fh, "INSERT INTO ". $tables[$i] . " (". implode (',',$fields) . ") VALUES ('" . implode ('\',\'',$values) . "');\n");
$fields = "";
$values = "";
fwrite($fh, "INSERT INTO ". $tables[$i] . " (". implode(',', $fields) . ") VALUES ('" . implode('\',\'', $values) . "');\n");
$fields = "";
$values = "";
}
}
}
}
}
header ("Content-Type: text/plain");
header ("Content-Disposition: attachment; filename=\"$filename\"");
header ("Content-Transfer-Encoding: binary");
header ("Content-Length: " . filesize("$backup"));
header ("Content-Description: Postfix Admin");
$download_backup = fopen ("$backup", "r");
unlink ("$backup");
fpassthru ($download_backup);
}
}
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize("$backup"));
header("Content-Description: Postfix Admin");
$download_backup = fopen("$backup", "r");
unlink("$backup");
fpassthru($download_backup);
}
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: broadcast-message.php
* Used to send a message to _ALL_ users with mailboxes on this server.
*
@ -28,14 +28,14 @@
require_once('common.php');
if (Config::bool('sendmail_all_admins')) {
authentication_require_role('admin');
authentication_require_role('admin');
} else {
authentication_require_role('global-admin');
authentication_require_role('global-admin');
}
if ($CONF['sendmail'] != 'YES') {
header("Location: main.php");
exit;
header("Location: main.php");
exit;
}
$error = 0;
@ -43,82 +43,75 @@ $error = 0;
$smtp_from_email = smtp_get_admin_email();
$allowed_domains = list_domains_for_admin(authentication_get_username());
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if (empty($_POST['subject']) || empty($_POST['message']) || empty($_POST['name']))
{
$error = 1;
flash_error($PALANG['pBroadcast_error_empty']);
}
else
{
$wanted_domains = array_intersect($allowed_domains, $_POST['domains']);
$table_mailbox = table_by_key('mailbox');
$table_alias = table_by_key('alias');
$recipients = array();
$q = "SELECT username from $table_mailbox WHERE active='" . db_get_boolean(true) . "' AND ".db_in_clause("domain", $wanted_domains);
if (intval(safepost('mailboxes_only')) == 0) {
$q .= " UNION SELECT goto FROM $table_alias WHERE active='" . db_get_boolean(true) . "' AND ".db_in_clause("domain", $wanted_domains)."AND goto NOT IN ($q)";
}
$result = db_query($q);
if($result['rows'] > 0) {
while($row = db_array($result['result'])) {
$recipients[] = $row[0];
}
}
$recipients = array_unique($recipients);
if(count($recipients)>0) {
mb_internal_encoding("UTF-8");
$b_name = mb_encode_mimeheader( $_POST['name'], 'UTF-8', 'Q');
$b_subject = mb_encode_mimeheader( $_POST['subject'], 'UTF-8', 'Q');
$b_message = base64_encode($_POST['message']);
$i = 0;
foreach ($recipients as $rcpt) {
$fTo = $rcpt;
$fHeaders = 'To: ' . $fTo . "\n";
$fHeaders .= 'From: ' . $b_name . ' <' . $smtp_from_email . ">\n";
$fHeaders .= 'Subject: ' . $b_subject . "\n";
$fHeaders .= 'MIME-Version: 1.0' . "\n";
$fHeaders .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
$fHeaders .= 'Content-Transfer-Encoding: base64' . "\n";
$fHeaders .= $b_message;
if (!smtp_mail ($fTo, $smtp_from_email, $fHeaders))
{
flash_error(Config::lang_f('pSendmail_result_error', $fTo));
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
if (empty($_POST['subject']) || empty($_POST['message']) || empty($_POST['name'])) {
$error = 1;
flash_error($PALANG['pBroadcast_error_empty']);
} else {
$wanted_domains = array_intersect($allowed_domains, $_POST['domains']);
$table_mailbox = table_by_key('mailbox');
$table_alias = table_by_key('alias');
$recipients = array();
$q = "SELECT username from $table_mailbox WHERE active='" . db_get_boolean(true) . "' AND ".db_in_clause("domain", $wanted_domains);
if (intval(safepost('mailboxes_only')) == 0) {
$q .= " UNION SELECT goto FROM $table_alias WHERE active='" . db_get_boolean(true) . "' AND ".db_in_clause("domain", $wanted_domains)."AND goto NOT IN ($q)";
}
$result = db_query($q);
if ($result['rows'] > 0) {
while ($row = db_array($result['result'])) {
$recipients[] = $row[0];
}
else
{
flash_info(Config::lang_f('pSendmail_result_success', $fTo));
}
$recipients = array_unique($recipients);
if (count($recipients)>0) {
mb_internal_encoding("UTF-8");
$b_name = mb_encode_mimeheader($_POST['name'], 'UTF-8', 'Q');
$b_subject = mb_encode_mimeheader($_POST['subject'], 'UTF-8', 'Q');
$b_message = base64_encode($_POST['message']);
$i = 0;
foreach ($recipients as $rcpt) {
$fTo = $rcpt;
$fHeaders = 'To: ' . $fTo . "\n";
$fHeaders .= 'From: ' . $b_name . ' <' . $smtp_from_email . ">\n";
$fHeaders .= 'Subject: ' . $b_subject . "\n";
$fHeaders .= 'MIME-Version: 1.0' . "\n";
$fHeaders .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
$fHeaders .= 'Content-Transfer-Encoding: base64' . "\n";
$fHeaders .= $b_message;
if (!smtp_mail($fTo, $smtp_from_email, $fHeaders)) {
flash_error(Config::lang_f('pSendmail_result_error', $fTo));
} else {
flash_info(Config::lang_f('pSendmail_result_success', $fTo));
}
}
}
}
flash_info($PALANG['pBroadcast_success']);
$smarty->assign ('smarty_template', 'message');
$smarty->display ('index.tpl');
// echo '<p>'.$PALANG['pBroadcast_success'].'</p>';
}
}
flash_info($PALANG['pBroadcast_success']);
$smarty->assign('smarty_template', 'message');
$smarty->display('index.tpl');
// echo '<p>'.$PALANG['pBroadcast_success'].'</p>';
}
}
if ($_SERVER['REQUEST_METHOD'] == "GET" || $error == 1)
{
$smarty->assign ('allowed_domains', $allowed_domains);
$smarty->assign ('smtp_from_email', $smtp_from_email);
$smarty->assign ('error', $error);
$smarty->assign ('smarty_template', 'broadcast-message');
$smarty->display ('index.tpl');
if ($_SERVER['REQUEST_METHOD'] == "GET" || $error == 1) {
$smarty->assign('allowed_domains', $allowed_domains);
$smarty->assign('smtp_from_email', $smtp_from_email);
$smarty->assign('error', $error);
$smarty->assign('smarty_template', 'broadcast-message');
$smarty->display('index.tpl');
// include ("templates/broadcast-message.tpl");
// include ("templates/broadcast-message.tpl");
}
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -1,3 +1,2 @@
<?php
require_once(dirname(__FILE__) . '/../common.php');

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: delete.php
* Used to delete admins, domains, mailboxes, aliases etc.
*
@ -19,7 +19,9 @@
require_once('common.php');
if (safeget('token') != $_SESSION['PFA_token']) die('Invalid token!');
if (safeget('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
$username = authentication_get_username(); # enforce login
@ -28,8 +30,8 @@ $table = safeget('table');
$handlerclass = ucfirst($table) . 'Handler';
if ( !preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die ("Invalid table name given!");
if (!preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die("Invalid table name given!");
}
$is_admin = authentication_has_role('admin');
@ -52,8 +54,7 @@ if ($handler->init($id)) { # errors will be displayed as last step anyway, no ne
flash_error($handler->errormsg);
flash_info($handler->infomsg);
header ("Location: " . $formconf['listview']);
header("Location: " . $formconf['listview']);
exit;
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: edit.php
* This file implements the handling of edit forms.
* The form layout is retrieved from the *Handler classes, which also do
@ -29,15 +29,17 @@ $username = authentication_get_username(); # enforce login
$table = safepost('table', safeget('table'));
$handlerclass = ucfirst($table) . 'Handler';
if ( !preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die ("Invalid table name given!");
if (!preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die("Invalid table name given!");
}
$error = 0;
$edit = safepost('edit', safeget('edit'));
$new = 0;
if ($edit == "") $new = 1;
if ($edit == "") {
$new = 1;
}
$is_admin = authentication_has_role('admin');
@ -59,7 +61,7 @@ if ($new == 0 || $formconf['early_init']) {
flash_error($handlerclass . "->init() failed, but didn't set any error message");
}
flash_error($handler->errormsg);
header ("Location: " . $formconf['listview']);
header("Location: " . $formconf['listview']);
exit;
}
}
@ -69,7 +71,7 @@ $id_field = $handler->getId_field();
if ($_SERVER['REQUEST_METHOD'] == "GET") {
if ($new) { # new - prefill fields from URL parameters if allowed in $formconf['prefill']
if ( isset($formconf['prefill']) ) {
if (isset($formconf['prefill'])) {
foreach ($formconf['prefill'] as $field) {
$prefillvalue = safeget($field, safesession("prefill:$table:$field"));
if ($prefillvalue != '') {
@ -82,7 +84,7 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
} else { # edit mode - read values from database
if (!$handler->view()) {
flash_error($handler->errormsg);
header ("Location: " . $formconf['listview']);
header("Location: " . $formconf['listview']);
exit;
} else {
$values = $handler->result;
@ -93,25 +95,27 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
$inp_values = safepost('value', array() );
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
$inp_values = safepost('value', array());
foreach($form_fields as $key => $field) {
foreach ($form_fields as $key => $field) {
if ($field['editable'] && $field['display_in_form']) {
if (!isset($inp_values[$key])) {
$inp_values[$key] = ''; # newer PHP versions don't include empty fields in $_POST (noticed with PHP 5.6.6)
}
if($field['type'] == 'bool' && $inp_values[$key] == '') {
if ($field['type'] == 'bool' && $inp_values[$key] == '') {
$values[$key] = 0; # isset() for unchecked checkboxes is always false
} elseif($field['type'] == 'txtl') {
} elseif ($field['type'] == 'txtl') {
$values[$key] = $inp_values[$key];
$values[$key] = preg_replace ('/\\\r\\\n/', ',', $values[$key]);
$values[$key] = preg_replace ('/\r\n/', ',', $values[$key]);
$values[$key] = preg_replace ('/,[\s]+/i', ',', $values[$key]);
$values[$key] = preg_replace ('/[\s]+,/i', ',', $values[$key]);
$values[$key] = preg_replace ('/,,*/', ',', $values[$key]);
$values[$key] = preg_replace ('/,*$|^,*/', '', $values[$key]);
$values[$key] = preg_replace('/\\\r\\\n/', ',', $values[$key]);
$values[$key] = preg_replace('/\r\n/', ',', $values[$key]);
$values[$key] = preg_replace('/,[\s]+/i', ',', $values[$key]);
$values[$key] = preg_replace('/[\s]+,/i', ',', $values[$key]);
$values[$key] = preg_replace('/,,*/', ',', $values[$key]);
$values[$key] = preg_replace('/,*$|^,*/', '', $values[$key]);
if ($values[$key] == '') {
$values[$key] = array();
} else {
@ -160,7 +164,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
}
# remember prefill values for next usage of the form
if ( isset($formconf['prefill']) ) {
if (isset($formconf['prefill'])) {
foreach ($formconf['prefill'] as $field) {
if (isset($values[$field])) {
$_SESSION["prefill:$table:$field"] = $values[$field];
@ -169,7 +173,7 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
}
if ($new == 0) {
header ("Location: " . $formconf['listview']);
header("Location: " . $formconf['listview']);
exit;
} else {
header("Location: edit.php?table=$table");
@ -189,41 +193,41 @@ if ($error != 1 && $new) { # no error and not in edit mode - reset fields to def
$errormsg = $handler->errormsg;
$fielderror = array();
foreach($form_fields as $key => $field) {
if($form_fields[$key]['display_in_form']) {
if (isset($errormsg[$key])) {
$fielderror[$key] = $errormsg[$key];
unset ($errormsg[$key]);
} else {
$fielderror[$key] = '';
}
foreach ($form_fields as $key => $field) {
if ($form_fields[$key]['display_in_form']) {
if (isset($errormsg[$key])) {
$fielderror[$key] = $errormsg[$key];
unset($errormsg[$key]);
} else {
$fielderror[$key] = '';
}
if (isset($values[$key])) {
$smarty->assign ("value_$key", $values[$key]);
} else {
$smarty->assign ("value_$key", $form_fields[$key]['default']);
if (isset($values[$key])) {
$smarty->assign("value_$key", $values[$key]);
} else {
$smarty->assign("value_$key", $form_fields[$key]['default']);
}
}
}
}
if (count($errormsg)) flash_error($errormsg); # display the remaining error messages (not related to a field) with flash_error
if (count($errormsg)) {
flash_error($errormsg);
} # display the remaining error messages (not related to a field) with flash_error
if ($new) {
$smarty->assign ('mode', 'create');
$smarty->assign('mode', 'create');
$smarty->assign('formtitle', Config::lang($formconf['formtitle_create']));
$smarty->assign('submitbutton', Config::lang($formconf['create_button']));
} else {
$smarty->assign ('mode', 'edit');
$smarty->assign('mode', 'edit');
$smarty->assign('formtitle', Config::lang($formconf['formtitle_edit']));
$smarty->assign('submitbutton', Config::lang('save'));
}
$smarty->assign ('struct', $form_fields);
$smarty->assign ('fielderror', $fielderror);
$smarty->assign ('table', $table);
$smarty->assign ('smarty_template', 'editform');
$smarty->display ('index.tpl');
$smarty->assign('struct', $form_fields);
$smarty->assign('fielderror', $fielderror);
$smarty->assign('table', $table);
$smarty->assign('smarty_template', 'editform');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -19,7 +19,9 @@
require_once('common.php');
if (safeget('token') != $_SESSION['PFA_token']) die('Invalid token!');
if (safeget('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
$username = authentication_get_username(); # enforce login
@ -29,8 +31,8 @@ $active = safeget('active');
$handlerclass = ucfirst($table) . 'Handler';
if ( !preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die ("Invalid table name given!");
if (!preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die("Invalid table name given!");
}
$handler = new $handlerclass(0, $username);
@ -44,7 +46,7 @@ if ($handler->init($id)) { # errors will be displayed as last step anyway, no ne
die(Config::Lang('invalid_parameter'));
}
if ( $handler->set(array('active' => $active)) ) {
if ($handler->set(array('active' => $active))) {
$handler->store();
}
}
@ -52,8 +54,7 @@ if ($handler->init($id)) { # errors will be displayed as last step anyway, no ne
flash_error($handler->errormsg);
flash_info($handler->infomsg);
header ("Location: " . $formconf['listview']);
header("Location: " . $formconf['listview']);
exit;
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -12,6 +12,5 @@
//
// -none-
//
header ("Location: ../login.php");
header("Location: ../login.php");
exit;
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net or https://github.com/postfixadmin/postfixadmin
*
* @version $Id$
* @license GNU GPL v2 or later.
*
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: index.php
* Shows a sort-of welcome page.
* Template File: -none-
@ -20,15 +20,14 @@
* Form POST \ GET Variables: -none-
*/
$CONF = array('configured' => FALSE);
$CONF = array('configured' => false);
if(file_exists(dirname(__FILE__) . '/../config.inc.php')) {
if (file_exists(dirname(__FILE__) . '/../config.inc.php')) {
require_once(dirname(__FILE__) . '/../config.inc.php');
}
if ( $CONF['configured'] === TRUE )
{
header ("Location: login.php");
if ($CONF['configured'] === true) {
header("Location: login.php");
exit;
}
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: list-virtual.php
* List virtual users for a domain.
*
@ -38,7 +38,7 @@ if (safesession('list-virtual:domain') != $fDomain) {
unset($_SESSION['list-virtual:limit']);
}
$fDisplay = (int) safepost('limit', safeget('limit', safesession('list-virtual:limit')));
$search = safepost('search', safeget('search', array())); # not remembered in the session
$search = safepost('search', safeget('search', array())); # not remembered in the session
if (!is_array($search)) {
die(Config::Lang('invalid_parameter'));
}
@ -53,21 +53,21 @@ if (count($list_domains) == 0) {
exit;
}
if ((is_array ($list_domains) and sizeof ($list_domains) > 0)) {
if (empty ($fDomain)) {
if ((is_array($list_domains) and sizeof($list_domains) > 0)) {
if (empty($fDomain)) {
$fDomain = escape_string($list_domains[0]);
}
}
if(!in_array($fDomain, $list_domains)) {
flash_error( $PALANG['invalid_parameter'] );
if (!in_array($fDomain, $list_domains)) {
flash_error($PALANG['invalid_parameter']);
unset($_SESSION['list-virtual:domain']);
header("Location: list.php?table=domain"); # invalid domain, or not owned by this admin
exit;
}
if (!check_owner(authentication_get_username(), $fDomain)) {
flash_error( $PALANG['invalid_parameter'] . " If you see this message, please open a bugreport"); # this check is most probably obsoleted by the in_array() check above
if (!check_owner(authentication_get_username(), $fDomain)) {
flash_error($PALANG['invalid_parameter'] . " If you see this message, please open a bugreport"); # this check is most probably obsoleted by the in_array() check above
unset($_SESSION['list-virtual:domain']);
header("Location: list.php?table=domain"); # domain not owned by this admin
exit(0);
@ -95,13 +95,15 @@ if (Config::bool('alias_domain')) {
'msg' => $handler->getMsg(),
'formconf' => $formconf,
);
$aliasdomain_data['msg']['show_simple_search'] = False; # hide search box
$aliasdomain_data['msg']['show_simple_search'] = false; # hide search box
$aliasdomain_data['msg']['can_create'] = 1;
# hide create button if all domains (of this admin) are already used as alias domains
$handler->getList("");
if ( count($handler->result()) + 1 >= count($list_domains) ) $aliasdomain_data['msg']['can_create'] = 0; # all domains (of this admin) are already alias domains
if (count($handler->result()) + 1 >= count($list_domains)) {
$aliasdomain_data['msg']['can_create'] = 0;
} # all domains (of this admin) are already alias domains
# get the really requested list
if (count($search) == 0) {
@ -150,7 +152,7 @@ $alias_data = array(
);
$alias_data['struct']['goto_mailbox']['display_in_list'] = 0; # not useful/defined for non-mailbox aliases
$alias_data['struct']['on_vacation']['display_in_list'] = 0;
$alias_data['msg']['show_simple_search'] = False; # hide search box
$alias_data['msg']['show_simple_search'] = false; # hide search box
$handler->getList($search_alias, array(), $page_size, $fDisplay);
$pagebrowser_alias = $handler->getPagebrowser($search_alias, array());
@ -180,7 +182,7 @@ if (count($search) == 0 || !isset($search['_'])) {
$sql_where .= " AND ( $table_mailbox.username LIKE '%$searchterm%' OR $table_mailbox.name LIKE '%$searchterm%' ";
if ($display_mailbox_aliases) {
$sql_where .= " OR $table_alias.goto LIKE '%$searchterm%' ";
}
}
$sql_where .= " ) "; # $search is already escaped
}
if ($display_mailbox_aliases) {
@ -200,7 +202,7 @@ if (Config::bool('used_quotas') && Config::bool('new_quota_table')) {
$sql_join .= " LEFT JOIN $table_quota2 ON $table_mailbox.username=$table_quota2.username ";
}
if (Config::bool('used_quotas') && ( ! Config::bool('new_quota_table') ) ) {
if (Config::bool('used_quotas') && (! Config::bool('new_quota_table'))) {
$table_quota = table_by_key('quota');
$sql_select .= ", $table_quota.current ";
$sql_join .= " LEFT JOIN $table_quota ON $table_mailbox.username=$table_quota.username ";
@ -210,7 +212,7 @@ if (Config::bool('used_quotas') && ( ! Config::bool('new_quota_table') ) ) {
$mailbox_pagebrowser_query = "$sql_from\n$sql_join\n$sql_where\n$sql_order" ;
$query = "$sql_select\n$mailbox_pagebrowser_query\n$sql_limit";
$result = db_query ($query);
$result = db_query($query);
$tMailbox = array();
@ -218,7 +220,7 @@ if ($result['rows'] > 0) {
$delimiter = preg_quote($CONF['recipient_delimiter'], "/");
$goto_single_rec_del = "";
while ($row = db_array ($result['result'])) {
while ($row = db_array($result['result'])) {
if ($display_mailbox_aliases) {
$goto_split = explode(",", $row['goto']);
$row['goto_mailbox'] = 0;
@ -231,7 +233,7 @@ if ($result['rows'] > 0) {
if ($goto_single == $row['username'] || $goto_single_rec_del == $row['username']) { # delivers to mailbox
$row['goto_mailbox'] = 1;
} elseif (Config::bool('vacation') && strstr($goto_single, '@' . $CONF['vacation_domain']) ) { # vacation alias - TODO: check for full vacation alias
} elseif (Config::bool('vacation') && strstr($goto_single, '@' . $CONF['vacation_domain'])) { # vacation alias - TODO: check for full vacation alias
# skip the vacation alias, vacation status is detected otherwise
} else { # forwarding to other alias
$row['goto_other'][] = $goto_single;
@ -245,7 +247,7 @@ if ($result['rows'] > 0) {
$row['active']=('t'==$row['active']) ? 1 : 0;
if (Config::bool('vacation_control_admin')) {
if($row['v_active'] == NULL) {
if ($row['v_active'] == null) {
$row['v_active'] = 'f';
}
$row['v_active']=('t'==$row['v_active']) ? 1 : 0;
@ -265,7 +267,7 @@ $tDisplay_next = "";
$tDisplay_next_show = "";
$limit = get_domain_properties($fDomain);
if (isset ($limit)) {
if (isset($limit)) {
if ($fDisplay >= $page_size) {
$tDisplay_back_show = 1;
$tDisplay_back = $fDisplay - $page_size;
@ -274,70 +276,73 @@ if (isset ($limit)) {
$tDisplay_up_show = 1;
}
if (
(($fDisplay + $page_size) < $limit['alias_count']) or
(($fDisplay + $page_size) < $limit['alias_count']) or
(($fDisplay + $page_size) < $limit['mailbox_count'])
) {
$tDisplay_next_show = 1;
$tDisplay_next = $fDisplay + $page_size;
}
if($limit['aliases'] == 0) {
if ($limit['aliases'] == 0) {
$alias_data['msg']['can_create'] = true;
}
elseif($limit['alias_count'] < $limit['aliases']) {
} elseif ($limit['alias_count'] < $limit['aliases']) {
$alias_data['msg']['can_create'] = true;
}
if($limit['mailboxes'] == 0) {
if ($limit['mailboxes'] == 0) {
$tCanAddMailbox = true;
}
elseif($limit['mailbox_count'] < $limit['mailboxes']) {
} elseif ($limit['mailbox_count'] < $limit['mailboxes']) {
$tCanAddMailbox = true;
}
$limit ['aliases'] = eval_size ($limit ['aliases']);
$limit ['mailboxes'] = eval_size ($limit ['mailboxes']);
$limit ['aliases'] = eval_size($limit ['aliases']);
$limit ['mailboxes'] = eval_size($limit ['mailboxes']);
if (Config::bool('quota')) {
$limit ['maxquota'] = eval_size ($limit ['maxquota']);
$limit ['maxquota'] = eval_size($limit ['maxquota']);
}
}
$gen_show_status_mailbox = array ();
$divide_quota = array ('current' => array(), 'quota' => array());
if ((is_array ($tMailbox) and sizeof ($tMailbox) > 0)) {
for ($i = 0; $i < sizeof ($tMailbox); $i++) {
$gen_show_status_mailbox = array();
$divide_quota = array('current' => array(), 'quota' => array());
if ((is_array($tMailbox) and sizeof($tMailbox) > 0)) {
for ($i = 0; $i < sizeof($tMailbox); $i++) {
$gen_show_status_mailbox [$i] = gen_show_status($tMailbox[$i]['username']);
if(isset($tMailbox[$i]['current'])) {
$divide_quota ['current'][$i] = divide_quota ($tMailbox[$i]['current']);
if (isset($tMailbox[$i]['current'])) {
$divide_quota ['current'][$i] = divide_quota($tMailbox[$i]['current']);
}
if(isset($tMailbox[$i]['quota'])) {
$divide_quota ['quota'][$i] = divide_quota ($tMailbox[$i]['quota']);
if (isset($tMailbox[$i]['quota'])) {
$divide_quota ['quota'][$i] = divide_quota($tMailbox[$i]['quota']);
}
if(isset($tMailbox[$i]['quota']) && isset($tMailbox[$i]['current']))
{
$divide_quota ['percent'][$i] = min(100, round(($divide_quota ['current'][$i]/max(1,$divide_quota ['quota'][$i]))*100));
$divide_quota ['quota_width'][$i] = ($divide_quota ['percent'][$i] / 100 * 120);
if (isset($tMailbox[$i]['quota']) && isset($tMailbox[$i]['current'])) {
$divide_quota ['percent'][$i] = min(100, round(($divide_quota ['current'][$i]/max(1, $divide_quota ['quota'][$i]))*100));
$divide_quota ['quota_width'][$i] = ($divide_quota ['percent'][$i] / 100 * 120);
} else {
$divide_quota ['current'][$i] = Config::Lang('unknown');
$divide_quota ['quota_width'][$i] = 0; # TODO: use special value?
$divide_quota ['current'][$i] = Config::Lang('unknown');
$divide_quota ['quota_width'][$i] = 0; # TODO: use special value?
}
}
}
}
class cNav_bar
{
protected $count, $title, $limit, $page_size, $pages, $search; //* arguments
class cNav_bar {
protected $count;
protected $title;
protected $limit;
protected $page_size;
protected $pages;
protected $search; //* arguments
/* @var string - appended to page link href */
public $append_to_url = '';
protected $have_run_init = false;
protected $arr_prev, $arr_next, $arr_top; //* internal
protected $arr_prev;
protected $arr_next;
protected $arr_top; //* internal
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->title = $aTitle;
$this->limit = $aLimit;
@ -350,8 +355,8 @@ class cNav_bar
}
}
private function init () {
$this->anchor = 'a'.substr ($this->title, 3);
private function init() {
$this->anchor = 'a'.substr($this->title, 3);
$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 > 0) ? $this->arr_top = '&nbsp;<a href="?limit=0' .$this->search.$this->append_to_url.'"><img border="0" src="images/arrow-u.png" title="'.$GLOBALS ['PALANG']['pOverview_up_arrow'].'" alt="'.$GLOBALS ['PALANG']['pOverview_up_arrow'].'"/></a>&nbsp;' : $this->arr_top = '';
@ -375,18 +380,19 @@ class cNav_bar
public function display_top() {
$ret_val = '';
if ($this->count < 1)
if ($this->count < 1) {
return $ret_val;
if (!$this->have_run_init)
$this->init ();
}
if (!$this->have_run_init) {
$this->init();
}
$ret_val .= '<a name="'.$this->anchor.'"></a>';
$ret_val .= $this->display_pre ();
$ret_val .= $this->display_pre();
$ret_val .= '<b>'.$this->title.'</b>&nbsp;&nbsp;';
($this->limit >= $this->page_size) ? $highlight_at = $this->limit / $this->page_size : $highlight_at = 0;
for ($i = 0; $i < count ($this->pages); $i++)
{
for ($i = 0; $i < count($this->pages); $i++) {
$lPage = $this->pages [$i];
if ($i == $highlight_at) {
$ret_val .= '<b>'.$lPage.'</b>'."\n";
@ -406,78 +412,81 @@ class cNav_bar
public function display_bottom() {
$ret_val = '';
if ($this->count < 1)
if ($this->count < 1) {
return $ret_val;
if (!$this->have_run_init)
$this->init ();
$ret_val .= $this->display_pre ();
}
if (!$this->have_run_init) {
$this->init();
}
$ret_val .= $this->display_pre();
$ret_val .= '</td><td valign="middle" align="right">';
$ret_val .= $this->arr_prev;
$ret_val .= $this->arr_top;
$ret_val .= $this->arr_next;
$ret_val .= $this->display_post ();
$ret_val .= $this->display_post();
return $ret_val;
}
}
$nav_bar_alias = new cNav_bar ($PALANG['pOverview_alias_title'], $fDisplay, $CONF['page_size'], $pagebrowser_alias, $search);
$nav_bar_alias = new cNav_bar($PALANG['pOverview_alias_title'], $fDisplay, $CONF['page_size'], $pagebrowser_alias, $search);
$nav_bar_alias->append_to_url = '&amp;domain='.$fDomain;
$pagebrowser_mailbox = create_page_browser("$table_mailbox.username", $mailbox_pagebrowser_query);
$nav_bar_mailbox = new cNav_bar ($PALANG['pOverview_mailbox_title'], $fDisplay, $CONF['page_size'], $pagebrowser_mailbox, $search);
$nav_bar_mailbox = new cNav_bar($PALANG['pOverview_mailbox_title'], $fDisplay, $CONF['page_size'], $pagebrowser_mailbox, $search);
$nav_bar_mailbox->append_to_url = '&amp;domain='.$fDomain;
// this is why we need a proper template layer.
$fDomain = htmlentities($fDomain, ENT_QUOTES);
if(empty($_GET['domain'])) {
if (empty($_GET['domain'])) {
$_GET['domain'] = '';
}
$smarty->assign ('admin_list', array());
$smarty->assign ('domain_list', $list_domains);
$smarty->assign ('domain_selected', $fDomain);
$smarty->assign ('nav_bar_alias', array ('top' => $nav_bar_alias->display_top (), 'bottom' => $nav_bar_alias->display_bottom ()), false);
$smarty->assign ('nav_bar_mailbox', array ('top' => $nav_bar_mailbox->display_top (), 'bottom' => $nav_bar_mailbox->display_bottom ()), false);
$smarty->assign('admin_list', array());
$smarty->assign('domain_list', $list_domains);
$smarty->assign('domain_selected', $fDomain);
$smarty->assign('nav_bar_alias', array('top' => $nav_bar_alias->display_top(), 'bottom' => $nav_bar_alias->display_bottom()), false);
$smarty->assign('nav_bar_mailbox', array('top' => $nav_bar_mailbox->display_top(), 'bottom' => $nav_bar_mailbox->display_bottom()), false);
$smarty->assign ('fDomain', $fDomain, false);
$smarty->assign('fDomain', $fDomain, false);
$smarty->assign ('search', $search);
$smarty->assign('search', $search);
$smarty->assign ('list_domains', $list_domains);
$smarty->assign ('limit', $limit);
$smarty->assign ('tDisplay_back_show', $tDisplay_back_show);
$smarty->assign ('tDisplay_back', $tDisplay_back);
$smarty->assign ('tDisplay_up_show', $tDisplay_up_show);
$smarty->assign ('tDisplay_next_show', $tDisplay_next_show);
$smarty->assign ('tDisplay_next', $tDisplay_next);
$smarty->assign('list_domains', $list_domains);
$smarty->assign('limit', $limit);
$smarty->assign('tDisplay_back_show', $tDisplay_back_show);
$smarty->assign('tDisplay_back', $tDisplay_back);
$smarty->assign('tDisplay_up_show', $tDisplay_up_show);
$smarty->assign('tDisplay_next_show', $tDisplay_next_show);
$smarty->assign('tDisplay_next', $tDisplay_next);
if (Config::bool('alias_domain')) {
$smarty->assign ('tAliasDomains', $tAliasDomains);
$smarty->assign ('aliasdomain_data', $aliasdomain_data);
$smarty->assign('tAliasDomains', $tAliasDomains);
$smarty->assign('aliasdomain_data', $aliasdomain_data);
}
$smarty->assign ('tAlias', $tAlias);
$smarty->assign ('alias_data', $alias_data);
$smarty->assign('tAlias', $tAlias);
$smarty->assign('alias_data', $alias_data);
$smarty->assign ('tMailbox', $tMailbox);
$smarty->assign ('gen_show_status_mailbox', $gen_show_status_mailbox, false);
$smarty->assign ('boolconf_used_quotas', Config::bool('used_quotas'));
$smarty->assign ('divide_quota', $divide_quota);
$smarty->assign ('tCanAddMailbox', $tCanAddMailbox);
$smarty->assign ('display_mailbox_aliases', $display_mailbox_aliases);
if (isset ($_GET ['tab']))
$smarty->assign('tMailbox', $tMailbox);
$smarty->assign('gen_show_status_mailbox', $gen_show_status_mailbox, false);
$smarty->assign('boolconf_used_quotas', Config::bool('used_quotas'));
$smarty->assign('divide_quota', $divide_quota);
$smarty->assign('tCanAddMailbox', $tCanAddMailbox);
$smarty->assign('display_mailbox_aliases', $display_mailbox_aliases);
if (isset($_GET ['tab'])) {
$_SESSION ['tab'] = $_GET ['tab'];
}
//if (empty ($_GET ['tab']))
// unset ($_SESSION ['tab']);
if (!isset ($_SESSION ['tab']))
if (!isset($_SESSION ['tab'])) {
$_SESSION ['tab'] = 'all';
$smarty->assign ('tab', $_SESSION ['tab']);
$smarty->assign ('smarty_template', 'list-virtual');
$smarty->display ('index.tpl');
}
$smarty->assign('tab', $_SESSION ['tab']);
$smarty->assign('smarty_template', 'list-virtual');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -1,15 +1,15 @@
<?php /**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: list.php
* List all items as a quick overview.
*
@ -25,8 +25,8 @@ $table = safeget('table');
$handlerclass = ucfirst($table) . 'Handler';
if ( !preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die ("Invalid table name given!");
if (!preg_match('/^[a-z]+$/', $table) || !file_exists(dirname(__FILE__) . "/../model/$handlerclass.php")) { # validate $table
die("Invalid table name given!");
}
# default: domain admin restrictions
@ -78,15 +78,18 @@ if (count($search)) {
}
$items = $handler->result();
if (count($handler->errormsg)) flash_error($handler->errormsg);
if (count($handler->infomsg)) flash_error($handler->infomsg);
if (count($handler->errormsg)) {
flash_error($handler->errormsg);
}
if (count($handler->infomsg)) {
flash_error($handler->infomsg);
}
if (safeget('output') == 'csv') {
$out = fopen('php://output', 'w');
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment;filename='.$table.'.csv');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename='.$table.'.csv');
print "\xEF\xBB\xBF"; # utf8 byte-order to indicate the file is utf8 encoded
# print "sep=;"; # hint that ; is used as seperator - breaks the utf8 flag in excel import!
@ -101,8 +104,8 @@ if (safeget('output') == 'csv') {
$columns = array();
foreach ($handler->getStruct() as $key => $field) {
if ($field['display_in_list'] && $field['label'] != '') { # don't show fields without a label
$header[] = html_entity_decode ( $field['label'], ENT_COMPAT | ENT_HTML401, 'UTF-8' );
$columns[] = $key;
$header[] = html_entity_decode($field['label'], ENT_COMPAT | ENT_HTML401, 'UTF-8');
$columns[] = $key;
}
}
fputcsv($out, $header, ';');
@ -117,7 +120,6 @@ if (safeget('output') == 'csv') {
}
fclose($out);
} else { # HTML output
$smarty->assign('admin_list', $list_admins);
@ -132,9 +134,7 @@ if (safeget('output') == 'csv') {
$smarty->assign('search', $search);
$smarty->assign('searchmode', $searchmode);
$smarty->display ('index.tpl');
$smarty->display('index.tpl');
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: login.php
* Authenticates a user, and populates their $_SESSION as appropriate.
* Template File: login.tpl
@ -29,30 +29,29 @@
require_once('common.php');
if($CONF['configured'] !== true) {
if ($CONF['configured'] !== true) {
print "Installation not yet configured; please edit config.inc.php or write your settings to config.local.php";
exit;
}
check_db_version(); # check if the database layout is up to date (and error out if not)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
$lang = safepost('lang');
$fUsername = trim(safepost('fUsername'));
$fPassword = safepost('fPassword');
if ( $lang != check_language(0) ) { # only set cookie if language selection was changed
if ($lang != check_language(0)) { # only set cookie if language selection was changed
setcookie('lang', $lang, time() + 60*60*24*30); # language cookie, lifetime 30 days
# (language preference cookie is processed even if username and/or password are invalid)
}
$h = new AdminHandler;
if ( $h->login($fUsername, $fPassword) ) {
if ($h->login($fUsername, $fPassword)) {
init_session($fUsername, true);
# they've logged in, so see if they are a domain admin, as well.
@ -73,7 +72,6 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
header("Location: main.php");
exit(0);
} else { # $h->login failed
error_log("PostfixAdmin login failed (username: $fUsername, ip_address: {$_SERVER['REMOTE_ADDR']})");
flash_error($PALANG['pLogin_failed']);
@ -82,11 +80,10 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
$_SESSION['PFA_token'] = md5(uniqid(rand(), true));
$smarty->assign ('language_selector', language_selector(), false);
$smarty->assign ('smarty_template', 'login');
$smarty->assign ('logintype', 'admin');
$smarty->assign ('forgotten_password_reset', Config::read('forgotten_admin_password_reset'));
$smarty->display ('index.tpl');
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('smarty_template', 'login');
$smarty->assign('logintype', 'admin');
$smarty->assign('forgotten_password_reset', Config::read('forgotten_admin_password_reset'));
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: main.php
* Displays a menu/home page.
* Template File: main.php
@ -25,7 +25,7 @@ require_once('common.php');
$SESSID_USERNAME = authentication_get_username();
authentication_require_role('admin');
$smarty->assign ('smarty_template', 'main');
$smarty->display ('index.tpl');
$smarty->assign('smarty_template', 'main');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */ ?>
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: sendmail.php
* Used to send an email to a user.
* Template File: sendmail.tpl
@ -37,44 +37,41 @@ authentication_require_role('admin');
$smtp_from_email = smtp_get_admin_email();
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
$fTo = safepost('fTo');
$fFrom = $smtp_from_email;
$fSubject = safepost('fSubject');
$fTo = safepost('fTo');
$fFrom = $smtp_from_email;
$fSubject = safepost('fSubject');
$tBody = $_POST['fBody'];
if (get_magic_quotes_gpc ())
{
$tBody = stripslashes($tBody); # TODO: check for get_magic_quotes_gpc inside safepost/safeget
}
$tBody = $_POST['fBody'];
if (get_magic_quotes_gpc()) {
$tBody = stripslashes($tBody); # TODO: check for get_magic_quotes_gpc inside safepost/safeget
}
$error = 0;
$email_check = check_email ($fTo);
if (empty ($fTo) or ($email_check != ''))
{
$error = 1;
$tTo = escape_string ($_POST['fTo']);
$tSubject = escape_string ($_POST['fSubject']);
flash_error($PALANG['pSendmail_to_text_error']); # TODO: superfluous?
flash_error($email_check);
}
$error = 0;
$email_check = check_email($fTo);
if (empty($fTo) or ($email_check != '')) {
$error = 1;
$tTo = escape_string($_POST['fTo']);
$tSubject = escape_string($_POST['fSubject']);
flash_error($PALANG['pSendmail_to_text_error']); # TODO: superfluous?
flash_error($email_check);
}
if ($error != 1)
{
if (!smtp_mail ($fTo, $fFrom, $fSubject, $tBody)) {
flash_error(Config::lang_f('pSendmail_result_error', $fTo));
} else {
flash_info(Config::lang_f('pSendmail_result_success', $fTo));
}
}
if ($error != 1) {
if (!smtp_mail($fTo, $fFrom, $fSubject, $tBody)) {
flash_error(Config::lang_f('pSendmail_result_error', $fTo));
} else {
flash_info(Config::lang_f('pSendmail_result_success', $fTo));
}
}
}
$smarty->assign ('smtp_from_email', $smtp_from_email);
$smarty->assign ('smarty_template', 'sendmail');
$smarty->display ('index.tpl');
$smarty->assign('smtp_from_email', $smtp_from_email);
$smarty->assign('smarty_template', 'sendmail');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -41,20 +41,20 @@ require(dirname(__FILE__) . '/../templates/header.php');
//
// Check for availablilty functions
//
$f_phpversion = function_exists ("phpversion");
$f_apache_get_version = function_exists ("apache_get_version");
$f_get_magic_quotes_gpc = function_exists ("get_magic_quotes_gpc");
$f_mysql_connect = function_exists ("mysql_connect");
$f_mysqli_connect = function_exists ("mysqli_connect");
$f_pg_connect = function_exists ("pg_connect");
$f_phpversion = function_exists("phpversion");
$f_apache_get_version = function_exists("apache_get_version");
$f_get_magic_quotes_gpc = function_exists("get_magic_quotes_gpc");
$f_mysql_connect = function_exists("mysql_connect");
$f_mysqli_connect = function_exists("mysqli_connect");
$f_pg_connect = function_exists("pg_connect");
$f_sqlite_open = class_exists("SQLite3");
$f_session_start = function_exists ("session_start");
$f_preg_match = function_exists ("preg_match");
$f_mb_encode_mimeheader = function_exists ("mb_encode_mimeheader");
$f_imap_open = function_exists ("imap_open");
$f_session_start = function_exists("session_start");
$f_preg_match = function_exists("preg_match");
$f_mb_encode_mimeheader = function_exists("mb_encode_mimeheader");
$f_imap_open = function_exists("imap_open");
$file_config = file_exists (realpath ("./../config.inc.php"));
$file_local_config = file_exists (realpath ("./../config.local.php"));
$file_config = file_exists(realpath("./../config.inc.php"));
$file_local_config = file_exists(realpath("./../config.local.php"));
$error = 0;
@ -65,8 +65,7 @@ $errormsg = array();
//
$phpversion = 'unknown-version';
if ($f_phpversion == 1)
{
if ($f_phpversion == 1) {
if (phpversion() < 5) {
print "<li><b>Error: Depends on: PHP v5+</b><br /></li>\n";
$error += 1;
@ -74,27 +73,22 @@ if ($f_phpversion == 1)
# smarty uses htmlentities() with 4 parameters, the 4th parameter was introduced in PHP 5.2.3
# older PHP versions will cause warnings
$phpversion = 5;
print "<li><b>Recommended PHP version: >= 5.2.3, you have " . phpversion () . "</b></li>\n";
print "<li><b>Recommended PHP version: >= 5.2.3, you have " . phpversion() . "</b></li>\n";
} else {
$phpversion = 5;
print "<li>PHP version " . phpversion () . "</li>\n";
print "<li>PHP version " . phpversion() . "</li>\n";
}
# TODO: check for PHP >= 5.2.3 - smarty uses htmlentities with 4 parameters. The forth parameter was added in PHP 5.2.3, older versions will give a warning
}
else
{
# TODO: check for PHP >= 5.2.3 - smarty uses htmlentities with 4 parameters. The forth parameter was added in PHP 5.2.3, older versions will give a warning
} else {
print "<li><b>Unable to check for PHP version. (missing function: phpversion())</b></li>\n";
}
//
// Check for Apache version
//
if ($f_apache_get_version == 1)
{
if ($f_apache_get_version == 1) {
print "<li>" . apache_get_version() . "</li>\n";
}
else
{
} else {
# not running on Apache.
# However postfixadmin _is_ running, so obviously we are on a supported webserver ;-))
# No need to confuse the user with a warning.
@ -107,19 +101,13 @@ print "<ul>\n";
//
// Check for Magic Quotes
//
if ($f_get_magic_quotes_gpc == 1)
{
if (get_magic_quotes_gpc () == 0)
{
if ($f_get_magic_quotes_gpc == 1) {
if (get_magic_quotes_gpc() == 0) {
print "<li>Magic Quotes: Disabled - OK</li>\n";
}
else
{
} else {
print "<li><b>Warning: Magic Quotes: ON (internal workaround used)</b></li>\n";
}
}
else
{
} else {
print "<li><b>Unable to check for Magic Quotes. (missing function: get_magic_quotes_gpc())</b></li>\n";
}
@ -127,23 +115,20 @@ else
// Check for config.inc.php
//
$config_loaded = 0;
if ($file_config == 1)
{
if ($file_config == 1) {
print "<li>Depends on: presence config.inc.php - OK</li>\n";
require_once(dirname(__FILE__) .'/../config.inc.php');
$config_loaded = 1;
if(isset($CONF['configured'])) {
if($CONF['configured'] === TRUE) {
if (isset($CONF['configured'])) {
if ($CONF['configured'] === true) {
print "<li>Checking \$CONF['configured'] - OK\n";
} else {
print "<li><b>Warning: \$CONF['configured'] is 'false'.<br>\n";
print "You must edit your config.local.php and change this to true (this indicates you've created the database and user)</b>\n";
}
}
}
else
{
} else {
print "<li><b>Error: Depends on: presence config.inc.php - NOT FOUND</b><br /></li>\n";
print "Create the file, and edit as appropriate (e.g. select database type etc)<br />";
print "For example:<br />\n";
@ -165,16 +150,14 @@ if ($file_local_config == 1) {
//
// Check if there is support for at least 1 database
//
if (($f_mysql_connect == 0) and ($f_mysqli_connect == 0) and ($f_pg_connect == 0) and ($f_sqlite_open == 0))
{
if (($f_mysql_connect == 0) and ($f_mysqli_connect == 0) and ($f_pg_connect == 0) and ($f_sqlite_open == 0)) {
print "<li><b>Error: There is no database support in your PHP setup</b><br />\n";
print "To install MySQL 3.23 or 4.0 support on FreeBSD:<br />\n";
print "<pre>% cd /usr/ports/databases/php{$phpversion}-mysql/\n";
print "% make clean install\n";
print " - or with portupgrade -\n";
print "% portinstall php{$phpversion}-mysql</pre>\n";
if ($phpversion >= 5)
{
if ($phpversion >= 5) {
print "To install MySQL 4.1 support on FreeBSD:<br />\n";
print "<pre>% cd /usr/ports/databases/php5-mysqli/\n";
print "% make clean install\n";
@ -191,20 +174,17 @@ if (($f_mysql_connect == 0) and ($f_mysqli_connect == 0) and ($f_pg_connect == 0
//
// MySQL 3.23, 4.0 functions
//
if ($f_mysql_connect == 1)
{
if ($f_mysql_connect == 1) {
print "<li>Depends on: MySQL 3.23, 4.0 - OK</li>\n";
}
//
// MySQL 4.1 functions
//
if ($phpversion >= 5)
{
if ($f_mysqli_connect == 1)
{
if ($phpversion >= 5) {
if ($f_mysqli_connect == 1) {
print "<li>Depends on: MySQL 4.1 - OK\n";
if ( !($config_loaded && $CONF['database_type'] == 'mysqli') ) {
if (!($config_loaded && $CONF['database_type'] == 'mysqli')) {
print "<br>(change the database_type to 'mysqli' in config.local.php if you want to use MySQL)\n";
}
print "</li>";
@ -214,19 +194,17 @@ if ($phpversion >= 5)
//
// PostgreSQL functions
//
if ($f_pg_connect == 1)
{
if ($f_pg_connect == 1) {
print "<li>Depends on: PostgreSQL - OK \n";
if ( !($config_loaded && $CONF['database_type'] == 'pgsql') ) {
if (!($config_loaded && $CONF['database_type'] == 'pgsql')) {
print "<br>(change the database_type to 'pgsql' in config.local.php if you want to use PostgreSQL)\n";
}
print "</li>";
}
if ($f_sqlite_open == 1)
{
if ($f_sqlite_open == 1) {
print "<li>Depends on: SQLite - OK \n";
if ( !($config_loaded && db_sqlite()) ) {
if (!($config_loaded && db_sqlite())) {
print "<br>(change the database_type to 'sqlite' in config.local.php if you want to use SQLite)\n";
}
print "</li>";
@ -236,7 +214,7 @@ if ($f_sqlite_open == 1)
// Database connection
//
if ($config_loaded) {
list ($link, $error_text) = db_connect(TRUE);
list($link, $error_text) = db_connect(true);
if ($error_text == "") {
print "<li>Testing database connection (using {$CONF['database_type']}) - OK</li>";
} else {
@ -250,12 +228,9 @@ if ($config_loaded) {
//
// Session functions
//
if ($f_session_start == 1)
{
if ($f_session_start == 1) {
print "<li>Depends on: session - OK</li>\n";
}
else
{
} else {
print "<li><b>Error: Depends on: session - NOT FOUND</b><br />\n";
print "To install session support on FreeBSD:<br />\n";
print "<pre>% cd /usr/ports/www/php$phpversion-session/\n";
@ -268,12 +243,9 @@ else
//
// PCRE functions
//
if ($f_preg_match == 1)
{
if ($f_preg_match == 1) {
print "<li>Depends on: pcre - OK</li>\n";
}
else
{
} else {
print "<li><b>Error: Depends on: pcre - NOT FOUND</b><br />\n";
print "To install pcre support on FreeBSD:<br />\n";
print "<pre>% cd /usr/ports/devel/php$phpversion-pcre/\n";
@ -286,12 +258,9 @@ else
//
// Multibyte functions
//
if ( $f_mb_encode_mimeheader == 1 )
{
if ($f_mb_encode_mimeheader == 1) {
print "<li>Depends on: multibyte string - OK</li>\n";
}
else
{
} else {
print "<li><b>Error: Depends on: multibyte string - NOT FOUND</b><br />\n";
print "To install multibyte string support, install php$phpversion-mbstring</li>\n";
$error += 1;
@ -301,12 +270,9 @@ else
//
// Imap functions
//
if ( $f_imap_open == 1)
{
if ($f_imap_open == 1) {
print "<li>Depends on: IMAP functions - OK</li>\n";
}
else
{
} else {
print "<li><b>Warning: Depends on: IMAP functions - NOT FOUND</b><br />\n";
print "To install IMAP support, install php$phpversion-imap<br />\n";
print "Without IMAP support, you won't be able to create subfolders when creating mailboxes.</li>\n";
@ -320,12 +286,9 @@ else
print "</ul>";
if ($error != 0)
{
if ($error != 0) {
print "<p><b>Please fix the errors listed above.</b></p>";
}
else
{
} else {
print "<p>Everything seems fine... attempting to create/update database structure</p>\n";
require_once(dirname(__FILE__) .'/upgrade.php');
@ -334,7 +297,9 @@ else
$lostpw_error = 0;
$setuppw = "";
if (isset($CONF['setup_password'])) $setuppw = $CONF['setup_password'];
if (isset($CONF['setup_password'])) {
$setuppw = $CONF['setup_password'];
}
if (safepost("form") == "setuppw") {
# "setup password" form submitted
@ -342,24 +307,24 @@ else
$setupMessage = "The two passwords differ!";
$lostpw_error = 1;
} else {
list ($lostpw_error, $lostpw_result) = check_setup_password(safepost('setup_password'), 1);
list($lostpw_error, $lostpw_result) = check_setup_password(safepost('setup_password'), 1);
$setupMessage = $lostpw_result;
$setuppw = "changed";
}
} elseif (safepost("form") == "createadmin") {
# "create admin" form submitted
list ($pw_check_error, $pw_check_result) = check_setup_password(safepost('setup_password'));
list($pw_check_error, $pw_check_result) = check_setup_password(safepost('setup_password'));
if ($pw_check_result != 'pass_OK') {
$error += 1;
$setupMessage = $pw_check_result;
}
if($error == 0 && $pw_check_result == 'pass_OK') {
if ($error == 0 && $pw_check_result == 'pass_OK') {
// XXX need to ensure domains table includes an 'ALL' entry.
$table_domain = table_by_key('domain');
$r = db_query("SELECT * FROM $table_domain WHERE domain = 'ALL'");
if($r['rows'] == 0) {
db_insert('domain', array('domain' => 'ALL', 'description' => '', 'transport' => '') ); // all other fields should default through the schema.
if ($r['rows'] == 0) {
db_insert('domain', array('domain' => 'ALL', 'description' => '', 'transport' => '')); // all other fields should default through the schema.
}
$values = array(
@ -371,7 +336,7 @@ else
'active' => 1,
);
list ($error, $setupMessage, $errormsg) = create_admin($values);
list($error, $setupMessage, $errormsg) = create_admin($values);
if ($error != 0) {
$tUsername = htmlentities($values['username']);
@ -379,13 +344,11 @@ else
$setupMessage .= "<p>You are done with your basic setup. ";
$setupMessage .= "<p><b>You can now <a href='login.php'>login to PostfixAdmin</a> using the account you just created.</b>";
}
}
}
if ( ($setuppw == "" || $setuppw == "changeme" || safeget("lostpw") == 1 || $lostpw_error != 0) /* && $_SERVER['REQUEST_METHOD'] != "POST" */ ) {
# show "create setup password" form
?>
if (($setuppw == "" || $setuppw == "changeme" || safeget("lostpw") == 1 || $lostpw_error != 0) /* && $_SERVER['REQUEST_METHOD'] != "POST" */) {
# show "create setup password" form?>
<div class="standout"><?php print $setupMessage; ?></div>
<div id="edit_form">
@ -413,11 +376,10 @@ else
</div>
<?php
} elseif (
(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "GET") ||
$error != 0 ||
$lostpw_error == 0 ) {
(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "GET") ||
$error != 0 ||
$lostpw_error == 0) {
?>
<div class="standout"><?php print $setupMessage; ?></div>
@ -455,8 +417,7 @@ else
</div>
<?php
}
?>
} ?>
<b>Since version 2.3 there is no requirement to delete setup.php!</b><br />
<b>Check the config.inc.php file for any other settings that you might need to change!<br />
<?php
@ -468,14 +429,14 @@ else
<?php
function _error_field($errors, $key) {
if(!isset($errors[$key])) {
if (!isset($errors[$key])) {
return '';
}
return "<span style='color: red'>{$errors[$key]}</span>";
}
function generate_setup_password_salt() {
$salt = time() . '*' . $_SERVER['REMOTE_ADDR'] . '*' . mt_rand(0,60000);
$salt = time() . '*' . $_SERVER['REMOTE_ADDR'] . '*' . mt_rand(0, 60000);
$salt = md5($salt);
return $salt;
}
@ -496,14 +457,16 @@ function check_setup_password($password, $lostpw_mode = 0) {
$error = 1; # be pessimistic
$setuppw = "";
if (isset($CONF['setup_password'])) $setuppw = $CONF['setup_password'];
if (isset($CONF['setup_password'])) {
$setuppw = $CONF['setup_password'];
}
list($confsalt, $confpass, $trash) = explode(':', $setuppw . '::');
$pass = encrypt_setup_password($password, $confsalt);
$validpass = validate_password($password);
if ($password == "" ) { # no password specified?
if ($password == "") { # no password specified?
$result = "Setup password must be specified<br />If you didn't set up a setup password yet, enter the password you want to use.";
} elseif (count($validpass) > 0) {
$result = $validpass[0]; # TODO: honor all error messages, not only the first one
@ -521,11 +484,10 @@ function check_setup_password($password, $lostpw_mode = 0) {
$result .= '<p>If you want to use the password you entered as setup password, edit config.inc.php or config.local.php and set</p>';
$result .= "<pre>\$CONF['setup_password'] = '$pass';</pre>";
}
return array ($error, $result);
return array($error, $result);
}
function create_admin($values) {
DEFINE('POSTFIXADMIN_SETUP', 1); # avoids instant redirect to login.php after creating the admin
$handler = new AdminHandler(1, 'setup.php');

@ -1,16 +1,16 @@
<?php
if(!defined('POSTFIXADMIN')) {
if (!defined('POSTFIXADMIN')) {
require_once('common.php');
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
# @version $Id$
# @version $Id$
# Note: run with upgrade.php?debug=1 to see all SQL error messages
/**
* Use this to check whether an object (Table, index etc) exists within a
/**
* Use this to check whether an object (Table, index etc) exists within a
* PostgreSQL database.
* @param String the object name
* @return boolean true if it exists
@ -18,7 +18,7 @@ if(!defined('POSTFIXADMIN')) {
function _pgsql_object_exists($name) {
$sql = "select relname from pg_class where relname = '$name'";
$r = db_query($sql);
if($r['rows'] == 1) {
if ($r['rows'] == 1) {
return true;
}
return false;
@ -45,7 +45,7 @@ function _pgsql_field_exists($table, $field) {
AND a.attname = '$field' ";
$r = db_query($sql);
$row = db_row($r['result']);
if($row) {
if ($row) {
return true;
}
return false;
@ -57,7 +57,7 @@ function _mysql_field_exists($table, $field) {
$r = db_query($sql);
$row = db_row($r['result']);
if($row) {
if ($row) {
return true;
}
return false;
@ -66,7 +66,7 @@ function _mysql_field_exists($table, $field) {
function _sqlite_field_exists($table, $field) {
$sql = "PRAGMA table_info($table)";
$r = db_query($sql);
while($row = db_row($r['result'])) {
while ($row = db_row($r['result'])) {
if ($row[1] == $field) {
return true;
}
@ -76,40 +76,42 @@ function _sqlite_field_exists($table, $field) {
function _db_field_exists($table, $field) {
global $CONF;
if($CONF['database_type'] == 'pgsql') {
return _pgsql_field_exists($table, $field);
if ($CONF['database_type'] == 'pgsql') {
return _pgsql_field_exists($table, $field);
} else {
return _mysql_field_exists($table, $field);
}
}
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) {
global $CONF;
$query = "ALTER TABLE " . table_by_key($table) . " ADD COLUMN $field $fieldtype";
if($CONF['database_type'] != 'pgsql') {
if ($CONF['database_type'] != 'pgsql') {
$query .= " AFTER $after "; # PgSQL does not support to specify where to add the column, MySQL does
}
if(! _db_field_exists(table_by_key($table), $field)) {
if (! _db_field_exists(table_by_key($table), $field)) {
$result = db_query_parsed($query);
} else {
printdebug ("field already exists: $table.$field");
} else {
printdebug("field already exists: $table.$field");
}
}
function printdebug($text) {
if (safeget('debug') != "") print "<p style='color:#999'>$text</p>";
if (safeget('debug') != "") {
print "<p style='color:#999'>$text</p>";
}
}
$table = table_by_key('config');
if($CONF['database_type'] == 'pgsql') {
if ($CONF['database_type'] == 'pgsql') {
// check if table already exists, if so, don't recreate it
$r = db_query("SELECT relname FROM pg_class WHERE relname = '$table'");
if($r['rows'] == 0) {
if ($r['rows'] == 0) {
$pgsql = "
CREATE TABLE $table (
id SERIAL,
@ -119,7 +121,7 @@ if($CONF['database_type'] == 'pgsql') {
)";
db_query_parsed($pgsql);
}
} elseif(db_sqlite()) {
} elseif (db_sqlite()) {
$enc = 'PRAGMA encoding = "UTF-8"';
db_query_parsed($enc);
$sql = "
@ -142,7 +144,7 @@ if($CONF['database_type'] == 'pgsql') {
db_query_parsed($mysql, 0, " COMMENT = 'PostfixAdmin settings'");
}
$version = check_db_version(False);
$version = check_db_version(false);
_do_upgrade($version);
function _do_upgrade($current_version) {
@ -153,10 +155,10 @@ function _do_upgrade($current_version) {
// $target_version = preg_replace('/[^0-9]/', '', '$Revision$');
$funclist = get_defined_functions();
$our_upgrade_functions = array_filter($funclist['user'], '_upgrade_filter_function');
foreach($our_upgrade_functions as $function_name) {
foreach ($our_upgrade_functions as $function_name) {
$bits = explode("_", $function_name);
$function_number = $bits[1];
if($function_number > $current_version && $function_number > $target_version) {
if ($function_number > $current_version && $function_number > $target_version) {
$target_version = $function_number;
}
}
@ -194,25 +196,25 @@ function _do_upgrade($current_version) {
echo " &nbsp; done";
}
}
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli' ) {
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli') {
if (function_exists($function_mysql)) {
echo "<p>updating to version $i (MySQL)...";
$function_mysql();
echo " &nbsp; done";
}
} elseif(db_sqlite()) {
} elseif (db_sqlite()) {
if (function_exists($function_sqlite)) {
echo "<p>updating to version $i (SQLite)...";
$function_sqlite();
echo " &nbsp; done";
}
} elseif($CONF['database_type'] == 'pgsql') {
} elseif ($CONF['database_type'] == 'pgsql') {
if (function_exists($function_pgsql)) {
echo "<p>updating to version $i (PgSQL)...";
$function_pgsql();
echo " &nbsp; done";
}
}
}
// Update config table so we don't run the same query twice in the future.
$i = (int) $i;
$table = table_by_key('config');
@ -227,19 +229,18 @@ function _do_upgrade($current_version) {
* @param int (optional) whether errors should be ignored (0=false)
* @param String (optional) MySQL specific code to attach, useful for COMMENT= on CREATE TABLE
* @return String sql query
*/
*/
function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") {
global $CONF;
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli' ) {
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli') {
$replace = array(
'{AUTOINCREMENT}' => 'int(11) not null auto_increment',
'{AUTOINCREMENT}' => 'int(11) not null auto_increment',
'{PRIMARY}' => 'primary key',
'{UNSIGNED}' => 'unsigned' ,
'{FULLTEXT}' => 'FULLTEXT',
'{BOOLEAN}' => "tinyint(1) NOT NULL DEFAULT '" . db_get_boolean(False) . "'",
'{UNSIGNED}' => 'unsigned' ,
'{FULLTEXT}' => 'FULLTEXT',
'{BOOLEAN}' => "tinyint(1) NOT NULL DEFAULT '" . db_get_boolean(false) . "'",
'{UTF-8}' => '/*!40100 CHARACTER SET utf8 */',
'{LATIN1}' => '/*!40100 CHARACTER SET latin1 */',
'{IF_NOT_EXISTS}' => 'IF NOT EXISTS',
@ -254,15 +255,14 @@ function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") {
'{DATECURRENT}' => 'timestamp NOT NULL default CURRENT_TIMESTAMP', # only allowed once per table in MySQL
);
$sql = "$sql $attach_mysql";
} elseif(db_sqlite()) {
} elseif (db_sqlite()) {
$replace = array(
'{AUTOINCREMENT}' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
'{PRIMARY}' => 'PRIMARY KEY',
'{UNSIGNED}' => 'unsigned',
'{FULLTEXT}' => 'text',
'{BOOLEAN}' => "tinyint(1) NOT NULL DEFAULT '" . db_get_boolean(False) . "'",
'{BOOLEAN_TRUE}' => "tinyint(1) NOT NULL DEFAULT '" . db_get_boolean(True) . "'",
'{BOOLEAN}' => "tinyint(1) NOT NULL DEFAULT '" . db_get_boolean(false) . "'",
'{BOOLEAN_TRUE}' => "tinyint(1) NOT NULL DEFAULT '" . db_get_boolean(true) . "'",
'{UTF-8}' => '',
'{LATIN1}' => '',
'{IF_NOT_EXISTS}' => 'IF NOT EXISTS',
@ -276,13 +276,13 @@ function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") {
'{DATEFUTURE}' => "datetime NOT NULL default '2038-01-18'", # different default timestamp for vacation.activeuntil
'{DATECURRENT}' => 'datetime NOT NULL default CURRENT_TIMESTAMP',
);
} elseif($CONF['database_type'] == 'pgsql') {
} elseif ($CONF['database_type'] == 'pgsql') {
$replace = array(
'{AUTOINCREMENT}' => 'SERIAL',
'{PRIMARY}' => 'primary key',
'{UNSIGNED}' => '',
'{FULLTEXT}' => '',
'{BOOLEAN}' => "BOOLEAN NOT NULL DEFAULT '" . db_get_boolean(False) . "'",
'{AUTOINCREMENT}' => 'SERIAL',
'{PRIMARY}' => 'primary key',
'{UNSIGNED}' => '',
'{FULLTEXT}' => '',
'{BOOLEAN}' => "BOOLEAN NOT NULL DEFAULT '" . db_get_boolean(false) . "'",
'{UTF-8}' => '', # UTF-8 is simply ignored.
'{LATIN1}' => '', # same for latin1
'{IF_NOT_EXISTS}' => '', # does not work with PgSQL
@ -292,27 +292,26 @@ function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") {
'{INT}' => 'integer NOT NULL DEFAULT 0',
'{BIGINT}' => 'bigint NOT NULL DEFAULT 0',
'int(1)' => 'int',
'int(10)' => 'int',
'int(11)' => 'int',
'int(4)' => 'int',
'int(10)' => 'int',
'int(11)' => 'int',
'int(4)' => 'int',
'{DATETIME}' => "timestamp with time zone default '2000-01-01'", # stay in sync with MySQL
'{DATE}' => "timestamp with time zone default '2000-01-01'", # stay in sync with MySQL
'{DATEFUTURE}' => "timestamp with time zone default '2038-01-18'", # stay in sync with MySQL
'{DATECURRENT}' => 'timestamp with time zone default now()',
);
} else {
echo "Sorry, unsupported database type " . $conf['database_type'];
exit;
}
$replace['{BOOL_TRUE}'] = db_get_boolean(True);
$replace['{BOOL_FALSE}'] = db_get_boolean(False);
$replace['{BOOL_TRUE}'] = db_get_boolean(true);
$replace['{BOOL_FALSE}'] = db_get_boolean(false);
$query = trim(str_replace(array_keys($replace), $replace, $sql));
if (safeget('debug') != "") {
printdebug ($query);
printdebug($query);
}
$result = db_query($query, $ignore_errors);
if (safeget('debug') != "") {
@ -321,13 +320,13 @@ function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") {
return $result;
}
function _drop_index ($table, $index) {
function _drop_index($table, $index) {
global $CONF;
$table = table_by_key ($table);
$table = table_by_key($table);
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli' ) {
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli') {
return "ALTER TABLE $table DROP INDEX $index";
} elseif($CONF['database_type'] == 'pgsql' || db_sqlite()) {
} elseif ($CONF['database_type'] == 'pgsql' || db_sqlite()) {
return "DROP INDEX $index"; # Index names are unique with a DB for PostgreSQL
} else {
echo "Sorry, unsupported database type " . $conf['database_type'];
@ -337,19 +336,18 @@ function _drop_index ($table, $index) {
function _add_index($table, $indexname, $fieldlist) {
global $CONF;
$table = table_by_key ($table);
$table = table_by_key($table);
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli' ) {
if ($CONF['database_type'] == 'mysql' || $CONF['database_type'] == 'mysqli') {
$fieldlist = str_replace(',', '`,`', $fieldlist); # fix quoting if index contains multiple fields
return "ALTER TABLE $table ADD INDEX `$indexname` ( `$fieldlist` )";
} elseif($CONF['database_type'] == 'pgsql') {
} elseif ($CONF['database_type'] == 'pgsql') {
$pgindexname = $table . "_" . $indexname . '_idx';
return "CREATE INDEX $pgindexname ON $table($fieldlist);"; # Index names are unique with a DB for PostgreSQL
} else {
echo "Sorry, unsupported database type " . $conf['database_type'];
exit;
}
}
function upgrade_1_mysql() {
@ -357,7 +355,7 @@ 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)
# therefore:
return; # <-- skip running this function at all.
return; # <-- skip running this function at all.
# (remove the above "return" if you really want to start with a pre-2.1 database layout)
@ -454,7 +452,7 @@ function upgrade_1_mysql() {
KEY email (email)
) {INNODB} DEFAULT CHARSET=latin1 COMMENT='Postfix Admin - Virtual Vacation' ;";
foreach($sql as $query) {
foreach ($sql as $query) {
db_query_parsed($query);
}
}
@ -464,24 +462,23 @@ 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)
# therefore:
return; # <-- skip running this function at all.
return; # <-- skip running this function at all.
# (remove the above "return" if you really want to update a pre-2.1 database)
# upgrade pre-2.1 database
# from TABLE_BACKUP_MX.TXT
$table_domain = table_by_key ('domain');
if(!_mysql_field_exists($table_domain, 'transport')) {
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN transport VARCHAR(255) AFTER maxquota;", TRUE);
$table_domain = table_by_key('domain');
if (!_mysql_field_exists($table_domain, 'transport')) {
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN transport VARCHAR(255) AFTER maxquota;", true);
}
if(!_mysql_field_exists($table_domain, 'backupmx')) {
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN backupmx {BOOLEAN} AFTER transport;", TRUE);
if (!_mysql_field_exists($table_domain, 'backupmx')) {
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN backupmx {BOOLEAN} AFTER transport;", true);
}
}
function upgrade_2_pgsql() {
if(!_pgsql_object_exists(table_by_key('domain'))) {
if (!_pgsql_object_exists(table_by_key('domain'))) {
db_query_parsed("
CREATE TABLE " . table_by_key('domain') . " (
domain character varying(255) NOT NULL,
@ -501,7 +498,7 @@ function upgrade_2_pgsql() {
COMMENT ON TABLE " . table_by_key('domain') . " IS 'Postfix Admin - Virtual Domains';
");
}
if(!_pgsql_object_exists(table_by_key('admin'))) {
if (!_pgsql_object_exists(table_by_key('admin'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key("admin") . ' (
"username" character varying(255) NOT NULL,
@ -515,7 +512,7 @@ function upgrade_2_pgsql() {
");
}
if(!_pgsql_object_exists(table_by_key('alias'))) {
if (!_pgsql_object_exists(table_by_key('alias'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key("alias") . ' (
address character varying(255) NOT NULL,
@ -531,7 +528,7 @@ function upgrade_2_pgsql() {
');
}
if(!_pgsql_object_exists(table_by_key('domain_admins'))) {
if (!_pgsql_object_exists(table_by_key('domain_admins'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key('domain_admins') . ' (
username character varying(255) NOT NULL,
@ -540,10 +537,10 @@ function upgrade_2_pgsql() {
active boolean NOT NULL default true
);
COMMENT ON TABLE ' . table_by_key('domain_admins') . ' IS \'Postfix Admin - Domain Admins\';
');
');
}
if(!_pgsql_object_exists(table_by_key('log'))) {
if (!_pgsql_object_exists(table_by_key('log'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key('log') . ' (
timestamp timestamp with time zone default now(),
@ -555,7 +552,7 @@ function upgrade_2_pgsql() {
COMMENT ON TABLE ' . table_by_key('log') . ' IS \'Postfix Admin - Log\';
');
}
if(!_pgsql_object_exists(table_by_key('mailbox'))) {
if (!_pgsql_object_exists(table_by_key('mailbox'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key('mailbox') . ' (
username character varying(255) NOT NULL,
@ -574,7 +571,7 @@ function upgrade_2_pgsql() {
');
}
if(!_pgsql_object_exists(table_by_key('vacation'))) {
if (!_pgsql_object_exists(table_by_key('vacation'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key('vacation') . ' (
email character varying(255) PRIMARY KEY,
@ -588,7 +585,7 @@ function upgrade_2_pgsql() {
CREATE INDEX vacation_email_active ON ' . table_by_key('vacation') . '(email,active);');
}
if(!_pgsql_object_exists(table_by_key('vacation_notification'))) {
if (!_pgsql_object_exists(table_by_key('vacation_notification'))) {
db_query_parsed('
CREATE TABLE ' . table_by_key('vacation_notification') . ' (
on_vacation character varying(255) NOT NULL REFERENCES ' . table_by_key('vacation') . '(email) ON DELETE CASCADE,
@ -600,9 +597,9 @@ function upgrade_2_pgsql() {
}
// this handles anyone who is upgrading... (and should have no impact on new installees)
$table_domain = table_by_key ('domain');
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN transport VARCHAR(255)", TRUE);
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN backupmx BOOLEAN DEFAULT false", TRUE);
$table_domain = table_by_key('domain');
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN transport VARCHAR(255)", true);
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN backupmx BOOLEAN DEFAULT false", true);
}
function upgrade_3_mysql() {
@ -610,67 +607,67 @@ 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)
# therefore:
return; # <-- skip running this function at all.
return; # <-- skip running this function at all.
# (remove the above "return" if you really want to update a pre-2.1 database)
# upgrade pre-2.1 database
# from TABLE_CHANGES.TXT
$table_admin = table_by_key ('admin');
$table_alias = table_by_key ('alias');
$table_domain = table_by_key ('domain');
$table_mailbox = table_by_key ('mailbox');
$table_vacation = table_by_key ('vacation');
$table_admin = table_by_key('admin');
$table_alias = table_by_key('alias');
$table_domain = table_by_key('domain');
$table_mailbox = table_by_key('mailbox');
$table_vacation = table_by_key('vacation');
if(!_mysql_field_exists($table_admin, 'created')) {
if (!_mysql_field_exists($table_admin, 'created')) {
db_query_parsed("ALTER TABLE $table_admin {RENAME_COLUMN} create_date created {DATETIME};");
}
if(!_mysql_field_exists($table_admin, 'modified')) {
if (!_mysql_field_exists($table_admin, 'modified')) {
db_query_parsed("ALTER TABLE $table_admin {RENAME_COLUMN} change_date modified {DATETIME};");
}
if(!_mysql_field_exists($table_alias, 'created')) {
if (!_mysql_field_exists($table_alias, 'created')) {
db_query_parsed("ALTER TABLE $table_alias {RENAME_COLUMN} create_date created {DATETIME};");
}
if(!_mysql_field_exists($table_alias, 'modified')) {
if (!_mysql_field_exists($table_alias, 'modified')) {
db_query_parsed("ALTER TABLE $table_alias {RENAME_COLUMN} change_date modified {DATETIME};");
}
if(!_mysql_field_exists($table_domain, 'created')) {
if (!_mysql_field_exists($table_domain, 'created')) {
db_query_parsed("ALTER TABLE $table_domain {RENAME_COLUMN} create_date created {DATETIME};");
}
if(!_mysql_field_exists($table_domain, 'modified')) {
if (!_mysql_field_exists($table_domain, 'modified')) {
db_query_parsed("ALTER TABLE $table_domain {RENAME_COLUMN} change_date modified {DATETIME};");
}
if(!_mysql_field_exists($table_domain, 'aliases')) {
if (!_mysql_field_exists($table_domain, 'aliases')) {
db_query_parsed("ALTER TABLE $table_domain ADD COLUMN aliases INT(10) DEFAULT '-1' NOT NULL AFTER description;");
}
if(!_mysql_field_exists($table_domain, 'mailboxes')) {
if (!_mysql_field_exists($table_domain, 'mailboxes')) {
db_query_parsed("ALTER TABLE $table_domain ADD COLUMN mailboxes INT(10) DEFAULT '-1' NOT NULL AFTER aliases;");
}
if(!_mysql_field_exists($table_domain, 'maxquota')) {
if (!_mysql_field_exists($table_domain, 'maxquota')) {
db_query_parsed("ALTER TABLE $table_domain ADD COLUMN maxquota INT(10) DEFAULT '-1' NOT NULL AFTER mailboxes;");
}
if(!_mysql_field_exists($table_domain, 'transport')) {
if (!_mysql_field_exists($table_domain, 'transport')) {
db_query_parsed("ALTER TABLE $table_domain ADD COLUMN transport VARCHAR(255) AFTER maxquota;");
}
if(!_mysql_field_exists($table_domain, 'backupmx')) {
if (!_mysql_field_exists($table_domain, 'backupmx')) {
db_query_parsed("ALTER TABLE $table_domain ADD COLUMN backupmx TINYINT(1) DEFAULT '0' NOT NULL AFTER transport;");
}
if(!_mysql_field_exists($table_mailbox, 'created')) {
if (!_mysql_field_exists($table_mailbox, 'created')) {
db_query_parsed("ALTER TABLE $table_mailbox {RENAME_COLUMN} create_date created {DATETIME};");
}
if(!_mysql_field_exists($table_mailbox, 'modified')) {
if (!_mysql_field_exists($table_mailbox, 'modified')) {
db_query_parsed("ALTER TABLE $table_mailbox {RENAME_COLUMN} change_date modified {DATETIME};");
}
if(!_mysql_field_exists($table_mailbox, 'quota')) {
if (!_mysql_field_exists($table_mailbox, 'quota')) {
db_query_parsed("ALTER TABLE $table_mailbox ADD COLUMN quota INT(10) DEFAULT '-1' NOT NULL AFTER maildir;");
}
if(!_mysql_field_exists($table_vacation, 'domain')) {
if (!_mysql_field_exists($table_vacation, 'domain')) {
db_query_parsed("ALTER TABLE $table_vacation ADD COLUMN domain VARCHAR(255) DEFAULT '' NOT NULL AFTER cache;");
}
if(!_mysql_field_exists($table_vacation, 'created')) {
if (!_mysql_field_exists($table_vacation, 'created')) {
db_query_parsed("ALTER TABLE $table_vacation ADD COLUMN created {DATETIME} AFTER domain;");
}
if(!_mysql_field_exists($table_vacation, 'active')) {
if (!_mysql_field_exists($table_vacation, 'active')) {
db_query_parsed("ALTER TABLE $table_vacation ADD COLUMN active TINYINT(1) DEFAULT '1' NOT NULL AFTER created;");
}
db_query_parsed("ALTER TABLE $table_vacation DROP PRIMARY KEY");
@ -680,8 +677,8 @@ function upgrade_3_mysql() {
function upgrade_4_mysql() { # MySQL only
# changes between 2.1 and moving to sourceforge
$table_domain = table_by_key ('domain');
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN quota int(10) NOT NULL default '0' AFTER maxquota", TRUE);
$table_domain = table_by_key('domain');
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN quota int(10) NOT NULL default '0' AFTER maxquota", true);
# Possible errors that can be ignored:
# - Invalid query: Table 'postfix.domain' doesn't exist
}
@ -689,7 +686,7 @@ function upgrade_4_mysql() { # MySQL only
/**
* Changes between 2.1 and moving to sf.net
*/
function upgrade_4_pgsql() {
function upgrade_4_pgsql() {
$table_domain = table_by_key('domain');
$table_admin = table_by_key('admin');
$table_alias = table_by_key('alias');
@ -699,19 +696,19 @@ function upgrade_4_pgsql() {
$table_vacation = table_by_key('vacation');
$table_vacation_notification = table_by_key('vacation_notification');
if(!_pgsql_field_exists($table_domain, 'quota')) {
if (!_pgsql_field_exists($table_domain, 'quota')) {
$result = db_query_parsed("ALTER TABLE $table_domain ADD COLUMN quota int NOT NULL default '0'");
}
$result = db_query_parsed("ALTER TABLE $table_domain ALTER COLUMN domain DROP DEFAULT");
if(!_pgsql_object_exists('domain_domain_active')) {
if (!_pgsql_object_exists('domain_domain_active')) {
$result = db_query_parsed("CREATE INDEX domain_domain_active ON $table_domain(domain,active)");
}
$result = db_query_parsed("ALTER TABLE $table_domain_admins ALTER COLUMN domain DROP DEFAULT");
$result = db_query_parsed("ALTER TABLE $table_alias ALTER COLUMN address DROP DEFAULT");
$result = db_query_parsed("ALTER TABLE $table_alias ALTER COLUMN domain DROP DEFAULT");
if(!_pgsql_object_exists('alias_address_active')) {
if (!_pgsql_object_exists('alias_address_active')) {
$result = db_query_parsed("CREATE INDEX alias_address_active ON $table_alias(address,active)");
}
@ -729,7 +726,8 @@ function upgrade_4_pgsql() {
$result = db_query_parsed("ALTER TABLE $table_mailbox ALTER COLUMN username DROP DEFAULT");
$result = db_query_parsed("ALTER TABLE $table_mailbox ALTER COLUMN domain DROP DEFAULT");
$result = db_query_parsed("
$result = db_query_parsed(
"
BEGIN;
ALTER TABLE $table_mailbox RENAME COLUMN domain TO domain_old;
ALTER TABLE $table_mailbox ADD COLUMN domain varchar(255) REFERENCES $table_domain (domain);
@ -737,13 +735,13 @@ function upgrade_4_pgsql() {
ALTER TABLE $table_mailbox DROP COLUMN domain_old;
COMMIT;"
);
if(!_pgsql_object_exists('mailbox_username_active')) {
if (!_pgsql_object_exists('mailbox_username_active')) {
db_query_parsed("CREATE INDEX mailbox_username_active ON $table_mailbox(username,active)");
}
$result = db_query_parsed("ALTER TABLE $table_vacation ALTER COLUMN body SET DEFAULT ''");
if(_pgsql_field_exists($table_vacation, 'cache')) {
if (_pgsql_field_exists($table_vacation, 'cache')) {
$result = db_query_parsed("ALTER TABLE $table_vacation DROP COLUMN cache");
}
@ -756,11 +754,11 @@ function upgrade_4_pgsql() {
COMMIT;
");
if(!_pgsql_object_exists('vacation_email_active')) {
if (!_pgsql_object_exists('vacation_email_active')) {
$result = db_query_parsed("CREATE INDEX vacation_email_active ON $table_vacation(email,active)");
}
if(!_pgsql_object_exists($table_vacation_notification)) {
if (!_pgsql_object_exists($table_vacation_notification)) {
$result = db_query_parsed("
CREATE TABLE $table_vacation_notification (
on_vacation character varying(255) NOT NULL REFERENCES $table_vacation(email) ON DELETE CASCADE,
@ -772,7 +770,7 @@ function upgrade_4_pgsql() {
# Possible errors that can be ignored:
#
#
# NO MySQL errors should be ignored below this line!
@ -785,7 +783,6 @@ function upgrade_4_pgsql() {
* - removed creation of default superadmin
*/
function upgrade_5_mysql() {
$result = db_query_parsed("
CREATE TABLE {IF_NOT_EXISTS} " . table_by_key('admin') . " (
`username` varchar(255) NOT NULL default '',
@ -884,14 +881,14 @@ function upgrade_5_mysql() {
* drop useless indicies (already available as primary key)
*/
function upgrade_79_mysql() { # MySQL only
$result = db_query_parsed(_drop_index('admin', 'username'), True);
$result = db_query_parsed(_drop_index('alias', 'address'), True);
$result = db_query_parsed(_drop_index('domain', 'domain'), True);
$result = db_query_parsed(_drop_index('mailbox', 'username'), True);
$result = db_query_parsed(_drop_index('admin', 'username'), true);
$result = db_query_parsed(_drop_index('alias', 'address'), true);
$result = db_query_parsed(_drop_index('domain', 'domain'), true);
$result = db_query_parsed(_drop_index('mailbox', 'username'), true);
}
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');
$all_sql = explode("\n", trim("
@ -906,30 +903,28 @@ function upgrade_81_mysql() { # MySQL only
"));
foreach ($all_sql as $sql) {
$result = db_query_parsed($sql, TRUE);
$result = db_query_parsed($sql, true);
}
}
/**
* Make logging translatable - i.e. create alias => create_alias
*/
function upgrade_90_mysql_pgsql() {
$result = db_query_parsed("UPDATE " . table_by_key ('log') . " SET action = REPLACE(action,' ','_')", TRUE);
$result = db_query_parsed("UPDATE " . table_by_key('log') . " SET action = REPLACE(action,' ','_')", true);
# change edit_alias_state to edit_alias_active
$result = db_query_parsed("UPDATE " . table_by_key ('log') . " SET action = 'edit_alias_state' WHERE action = 'edit_alias_active'", TRUE);
$result = db_query_parsed("UPDATE " . table_by_key('log') . " SET action = 'edit_alias_state' WHERE action = 'edit_alias_active'", true);
}
/**
* MySQL only allow quota > 2 GB
*/
function upgrade_169_mysql() {
$table_domain = table_by_key ('domain');
$table_mailbox = table_by_key ('mailbox');
$result = db_query_parsed("ALTER TABLE $table_domain MODIFY COLUMN `quota` bigint(20) NOT NULL default '0'", TRUE);
$result = db_query_parsed("ALTER TABLE $table_domain MODIFY COLUMN `maxquota` bigint(20) NOT NULL default '0'", TRUE);
$result = db_query_parsed("ALTER TABLE $table_mailbox MODIFY COLUMN `quota` bigint(20) NOT NULL default '0'", TRUE);
function upgrade_169_mysql() {
$table_domain = table_by_key('domain');
$table_mailbox = table_by_key('mailbox');
$result = db_query_parsed("ALTER TABLE $table_domain MODIFY COLUMN `quota` bigint(20) NOT NULL default '0'", true);
$result = db_query_parsed("ALTER TABLE $table_domain MODIFY COLUMN `maxquota` bigint(20) NOT NULL default '0'", true);
$result = db_query_parsed("ALTER TABLE $table_mailbox MODIFY COLUMN `quota` bigint(20) NOT NULL default '0'", true);
}
@ -942,7 +937,7 @@ function upgrade_318_mysql() {
$table_vacation_notification = table_by_key('vacation_notification');
$table_vacation = table_by_key('vacation');
db_query_parsed( "
db_query_parsed("
CREATE TABLE {IF_NOT_EXISTS} $table_vacation_notification (
on_vacation varchar(255) NOT NULL,
notified varchar(255) NOT NULL,
@ -962,13 +957,12 @@ function upgrade_318_mysql() {
"));
# Possible errors that can be ignored:
# None.
# If something goes wrong, the user should drop the vacation_notification table
# If something goes wrong, the user should drop the vacation_notification table
# (not a great loss) and re-create it using this function.
foreach ($all_sql as $sql) {
$result = db_query_parsed($sql);
}
}
@ -976,10 +970,9 @@ function upgrade_318_mysql() {
* Create fetchmail table
*/
function upgrade_344_mysql() {
$table_fetchmail = table_by_key('fetchmail');
db_query_parsed( "
db_query_parsed("
CREATE TABLE IF NOT EXISTS $table_fetchmail(
id int(11) unsigned not null auto_increment,
mailbox varchar(255) not null default '',
@ -1003,9 +996,9 @@ function upgrade_344_mysql() {
function upgrade_344_pgsql() {
$fetchmail = table_by_key('fetchmail');
// a field name called 'date' is probably a bad idea.
if(!_pgsql_object_exists('fetchmail')) {
db_query_parsed( "
// a field name called 'date' is probably a bad idea.
if (!_pgsql_object_exists('fetchmail')) {
db_query_parsed("
create table $fetchmail(
id serial,
mailbox varchar(255) not null default '',
@ -1032,12 +1025,12 @@ function upgrade_344_pgsql() {
// fetchmail.php requires id parameters to be > 0, as it does if($id) like logic... hence if we don't
// fudge the sequence starting point, you cannot delete/edit the first entry if using PostgreSQL.
// I'm sure there's a more elegant way of fixing it properly.... but this should work for now.
if(_pgsql_object_exists('fetchmail_id_seq')) {
db_query_parsed("SELECT nextval('{$fetchmail}_id_seq')"); // I don't care about number waste.
if (_pgsql_object_exists('fetchmail_id_seq')) {
db_query_parsed("SELECT nextval('{$fetchmail}_id_seq')"); // I don't care about number waste.
}
}
/**
/**
* Create alias_domain table - MySQL
*/
# function upgrade_362_mysql() # renamed to _438 to make sure it runs after an upgrade from 2.2.x
@ -1059,7 +1052,7 @@ function upgrade_438_mysql() {
");
}
/**
/**
* Create alias_domain table - PgSQL
*/
# function upgrade_362_pgsql() # renamed to _438 to make sure it runs after an upgrade from 2.2.x
@ -1067,7 +1060,7 @@ function upgrade_438_pgsql() {
# Table structure for table alias_domain
$table_alias_domain = table_by_key('alias_domain');
$table_domain = table_by_key('domain');
if(_pgsql_object_exists($table_alias_domain)) {
if (_pgsql_object_exists($table_alias_domain)) {
return;
}
db_query_parsed("
@ -1086,7 +1079,7 @@ function upgrade_438_pgsql() {
* Change description fields to UTF-8
*/
function upgrade_373_mysql() { # MySQL only
$table_domain = table_by_key ('domain');
$table_domain = table_by_key('domain');
$table_mailbox = table_by_key('mailbox');
$all_sql = explode("\n", trim("
@ -1105,13 +1098,13 @@ function upgrade_373_mysql() { # MySQL only
*/
function upgrade_439_mysql() {
$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` ; ");
}
}
function upgrade_439_pgsql() {
$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");
}
}
@ -1171,21 +1164,21 @@ function upgrade_473_mysql() {
}
}
function upgrade_479_mysql () {
function upgrade_479_mysql() {
# ssl is a reserved word in MySQL and causes several problems. Renaming the field...
$table_fmail = table_by_key('fetchmail');
if(!_mysql_field_exists($table_fmail, 'usessl')) {
if (!_mysql_field_exists($table_fmail, 'usessl')) {
db_query_parsed("ALTER TABLE $table_fmail CHANGE `ssl` `usessl` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0'");
}
}
function upgrade_479_pgsql () {
function upgrade_479_pgsql() {
$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");
}
}
function upgrade_483_mysql () {
function upgrade_483_mysql() {
$table_log = table_by_key('log');
db_query_parsed("ALTER TABLE $table_log CHANGE `data` `data` TEXT {LATIN1} NOT NULL");
}
@ -1195,7 +1188,7 @@ function upgrade_483_mysql () {
# See https://sourceforge.net/forum/message.php?msg_id=5394663
function upgrade_495_pgsql() {
$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("UPDATE $table_mailbox SET local_part = substring(username from '^(.*)@')");
db_query_parsed("ALTER TABLE $table_mailbox alter column local_part SET NOT NULL");
@ -1204,7 +1197,7 @@ function upgrade_495_pgsql() {
# See https://sourceforge.net/forum/message.php?msg_id=5394663
function upgrade_495_mysql() {
$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("UPDATE $table_mailbox SET local_part = substring_index(username, '@', 1)");
db_query_parsed("ALTER TABLE $table_mailbox change local_part local_part varchar(255) NOT NULL"); // remove null-ness...
@ -1218,10 +1211,10 @@ function upgrade_504_mysql() {
function upgrade_655_mysql_pgsql() {
db_query_parsed(_add_index('mailbox', 'domain', 'domain'));
db_query_parsed(_add_index('alias', 'domain', 'domain'));
db_query_parsed(_add_index('alias', 'domain', 'domain'));
}
/*
/*
function number too small for upgrades from 2.3.x
-> adding activefrom and activeuntil to vacation table is now upgrade_964
-> the tables client_access, from_access, helo_access, rcpt_access, user_whitelist
@ -1290,7 +1283,7 @@ function upgrade_729_mysql_pgsql() {
# table for dovecot v1.0 & 1.1
# note: quota table created with old versions of upgrade.php (before r1605)
# will not have explicit "NOT NULL DEFAULT 0" for the "current" field
# (shouldn't hurt)
# (shouldn't hurt)
db_query_parsed("
CREATE TABLE {IF_NOT_EXISTS} $table_quota (
username VARCHAR(255) {LATIN1} NOT NULL,
@ -1385,12 +1378,12 @@ function upgrade_945_mysql_pgsql() {
function upgrade_946_mysql_pgsql() {
# 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');
}
function upgrade_968_pgsql() {
# 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');
db_query_parsed("ALTER TABLE $table_domain ALTER COLUMN quota type bigint");
db_query_parsed("ALTER TABLE $table_domain ALTER COLUMN maxquota type bigint");
@ -1412,9 +1405,9 @@ function upgrade_1284_mysql_pgsql() {
$result = db_query("SELECT username FROM " . table_by_key('domain_admins') . " where domain='ALL'");
if ($result['rows'] > 0) {
while ($row = db_array ($result['result'])) {
printdebug ("Setting superadmin flag for " . $row['username']);
db_update('admin', 'username', $row['username'], array('superadmin' => db_get_boolean(true)) );
while ($row = db_array($result['result'])) {
printdebug("Setting superadmin flag for " . $row['username']);
db_update('admin', 'username', $row['username'], array('superadmin' => db_get_boolean(true)));
}
}
}
@ -1428,8 +1421,8 @@ function upgrade_1345_mysql() {
}
function upgrade_1519_mysql_pgsql() {
_db_add_field('fetchmail', 'sslcertck', '{BOOLEAN}', 'usessl' );
_db_add_field('fetchmail', 'sslcertpath', "VARCHAR(255) {UTF-8} DEFAULT ''", 'sslcertck' );
_db_add_field('fetchmail', 'sslcertck', '{BOOLEAN}', 'usessl');
_db_add_field('fetchmail', 'sslcertpath', "VARCHAR(255) {UTF-8} DEFAULT ''", 'sslcertck');
_db_add_field('fetchmail', 'sslfingerprint', "VARCHAR(255) {LATIN1} DEFAULT ''", 'sslcertpath');
}
@ -1458,14 +1451,14 @@ function upgrade_1761_mysql() {
}
function upgrade_1762_mysql_pgsql() {
_db_add_field('fetchmail', 'domain', "VARCHAR(255) {LATIN1} DEFAULT ''", 'id');
_db_add_field('fetchmail', 'active', '{BOOLEAN}', 'date');
_db_add_field('fetchmail', 'created', '{DATE}', 'date');
_db_add_field('fetchmail', 'domain', "VARCHAR(255) {LATIN1} DEFAULT ''", 'id');
_db_add_field('fetchmail', 'active', '{BOOLEAN}', 'date');
_db_add_field('fetchmail', 'created', '{DATE}', 'date');
# If you followed SVN and got upgrade failures here, you might need to
# UPDATE config SET value=1760 WHERE name='version';
# and run setup.php again (upgrade_1761_mysql was added later).
_db_add_field('fetchmail', 'modified', '{DATECURRENT}', 'created');
_db_add_field('fetchmail', 'modified', '{DATECURRENT}', 'created');
}
function upgrade_1763_mysql() {
@ -1650,7 +1643,6 @@ function upgrade_1824_sqlite() {
{PRIMARY} (`on_vacation`,`notified`),
CONSTRAINT `vacation_notification_pkey` FOREIGN KEY (`on_vacation`) REFERENCES `vacation` (`email`) ON DELETE CASCADE);
");
}
@ -1672,7 +1664,7 @@ function upgrade_1835_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');
$all_sql = explode("\n", trim("
@ -1682,14 +1674,13 @@ function upgrade_1836_mysql() {
"));
foreach ($all_sql as $sql) {
$result = db_query_parsed($sql, TRUE);
$result = db_query_parsed($sql, true);
}
}
function upgrade_1837() {
# alternative contact means to reset a forgotten password
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, 'email_other', "varchar(255) {UTF-8} NOT NULL DEFAULT ''", 'phone');
_db_add_field($table, 'token', "varchar(255) {UTF-8} NOT NULL DEFAULT ''", 'email_other');
@ -1713,22 +1704,21 @@ function upgrade_1837() {
function upgrade_1837_sqlite() {
# 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);
if(!_sqlite_field_exists($table, 'phone')) {
if (!_sqlite_field_exists($table, 'phone')) {
db_query_parsed("ALTER TABLE `$table` ADD COLUMN `phone` varchar(30) NOT NULL DEFAULT ''");
}
if(!_sqlite_field_exists($table, 'email_other')) {
if (!_sqlite_field_exists($table, 'email_other')) {
db_query_parsed("ALTER TABLE `$table` ADD COLUMN `email_other` varchar(255) NOT NULL DEFAULT ''");
}
}
}
/* https://github.com/postfixadmin/postfixadmin/issues/89 */
# upgrade_1838_mysql() renamed to upgrade_1839() to keep all databases in sync
function upgrade_1839() {
_db_add_field('log', 'id', '{AUTOINCREMENT} {PRIMARY}' , 'data');
_db_add_field('log', 'id', '{AUTOINCREMENT} {PRIMARY}', 'data');
}
function upgrade_1840_mysql_pgsql() {

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: edit-alias.php
* Users can use this to set forwards etc for their mailbox.
*
@ -20,48 +20,50 @@
$rel_path = '../';
require_once('../common.php');
$smarty->assign ('smarty_template', 'users_edit-alias');
$smarty->assign('smarty_template', 'users_edit-alias');
authentication_require_role('user');
$USERID_USERNAME = authentication_get_username();
// is edit-alias support enabled in $CONF ?
if (! Config::bool('edit_alias')) {
header ("Location: main.php");
exit(0);
if (! Config::bool('edit_alias')) {
header("Location: main.php");
exit(0);
}
$ah = new AliasHandler();
$ah->init($USERID_USERNAME);
$smarty->assign ('USERID_USERNAME', $USERID_USERNAME);
$smarty->assign('USERID_USERNAME', $USERID_USERNAME);
if ( ! $ah->view() ) die("Can't get alias details. Invalid alias?"); # this can only happen if a admin deleted the user since the user logged in
if (! $ah->view()) {
die("Can't get alias details. Invalid alias?");
} # this can only happen if a admin deleted the user since the user logged in
$result = $ah->result();
$tGotoArray = $result['goto'];
$tStoreAndForward = $result['goto_mailbox'];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if ($_SERVER['REQUEST_METHOD'] == "GET") {
if ($tStoreAndForward) {
$smarty->assign ('forward_and_store', ' checked="checked"');
$smarty->assign ('forward_only', '');
$smarty->assign('forward_and_store', ' checked="checked"');
$smarty->assign('forward_only', '');
} else {
$smarty->assign ('forward_and_store', '');
$smarty->assign ('forward_only', ' checked="checked"');
$smarty->assign('forward_and_store', '');
$smarty->assign('forward_only', ' checked="checked"');
}
$smarty->assign ('tGotoArray', $tGotoArray);
$smarty->display ('index.tpl');
$smarty->assign('tGotoArray', $tGotoArray);
$smarty->display('index.tpl');
}
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
// user clicked on cancel button
if(isset($_POST['fCancel'])) {
if (isset($_POST['fCancel'])) {
header("Location: main.php");
exit(0);
}
@ -72,45 +74,43 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
# TODO: use edit.php (or create a edit_user.php)
# TODO: this will obsolete lots of the code below (parsing $goto and the error checks)
$goto = strtolower ($fGoto);
$goto = preg_replace ('/\\\r\\\n/', ',', $goto);
$goto = preg_replace ('/\r\n/', ',', $goto);
$goto = preg_replace ('/,[\s]+/i', ',', $goto);
$goto = preg_replace ('/[\s]+,/i', ',', $goto);
$goto = preg_replace ('/\,*$/', '', $goto);
$goto = strtolower($fGoto);
$goto = preg_replace('/\\\r\\\n/', ',', $goto);
$goto = preg_replace('/\r\n/', ',', $goto);
$goto = preg_replace('/,[\s]+/i', ',', $goto);
$goto = preg_replace('/[\s]+,/i', ',', $goto);
$goto = preg_replace('/\,*$/', '', $goto);
$goto = explode(",",$goto);
$goto = explode(",", $goto);
$error = 0;
$goto = array_merge(array_unique($goto));
$good_goto = array();
if($fForward_and_store != 1 && sizeof($goto) == 1 && $goto[0] == '') {
if ($fForward_and_store != 1 && sizeof($goto) == 1 && $goto[0] == '') {
flash_error($PALANG['pEdit_alias_goto_text_error1']);
$error += 1;
}
if($error === 0) {
foreach($goto as $address) {
if ($address != "") { # $goto[] may contain a "" element
# TODO - from https://sourceforge.net/tracker/?func=detail&aid=3027375&group_id=191583&atid=937964
# The not-so-good news is that some internals of edit-alias aren't too nice
# - for example, $goto[] can contain an element with empty string. I added a
# check for that in the 2.3 branch, but we should use a better solution
# (avoid empty elements in $goto) in trunk ;-)
$email_check = check_email($address);
if($email_check != '') {
$error += 1;
flash_error("$address: $email_check");
if ($error === 0) {
foreach ($goto as $address) {
if ($address != "") { # $goto[] may contain a "" element
# TODO - from https://sourceforge.net/tracker/?func=detail&aid=3027375&group_id=191583&atid=937964
# The not-so-good news is that some internals of edit-alias aren't too nice
# - for example, $goto[] can contain an element with empty string. I added a
# check for that in the 2.3 branch, but we should use a better solution
# (avoid empty elements in $goto) in trunk ;-)
$email_check = check_email($address);
if ($email_check != '') {
$error += 1;
flash_error("$address: $email_check");
} else {
$good_goto[] = $address;
}
}
else {
$good_goto[] = $address;
}
}
}
}
if ($error == 0) {
$values = array(
'goto' => $good_goto,
'goto_mailbox' => $fForward_and_store,
@ -123,26 +123,23 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
$updated = $ah->store();
if($updated) {
header ("Location: main.php");
if ($updated) {
header("Location: main.php");
exit;
}
flash_error($PALANG['pEdit_alias_result_error']);
}
else {
} else {
$tGotoArray = $goto;
}
$smarty->assign ('tGotoArray', $tGotoArray);
$smarty->assign('tGotoArray', $tGotoArray);
if ($fForward_and_store == 1) {
$smarty->assign ('forward_and_store', ' checked="checked"');
$smarty->assign ('forward_only', '');
$smarty->assign('forward_and_store', ' checked="checked"');
$smarty->assign('forward_only', '');
} else {
$smarty->assign ('forward_and_store', '');
$smarty->assign ('forward_only', ' checked="checked"');
$smarty->assign('forward_and_store', '');
$smarty->assign('forward_only', ' checked="checked"');
}
$smarty->display ('index.tpl');
$smarty->display('index.tpl');
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: index.php
* Redirects potential users to login.php
* Template File: -none-
@ -23,7 +23,7 @@
*
* -none-
*/
header ("Location: login.php");
header("Location: login.php");
exit;
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: login.php
* Used to authenticate want-to-be users.
* Template File: login.tpl
@ -19,7 +19,7 @@
*
* tUsername
*
* Form POST \ GET Variables:
* Form POST \ GET Variables:
*
* fUsername
* fPassword
@ -32,40 +32,38 @@ require_once("../common.php");
check_db_version(); # check if the database layout is up to date (and error out if not)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
$lang = safepost('lang');
$fUsername = trim(safepost('fUsername'));
$fPassword = safepost('fPassword');
$lang = safepost('lang');
$fUsername = trim(safepost('fUsername'));
$fPassword = safepost('fPassword');
if ( $lang != check_language(0) ) { # only set cookie if language selection was changed
if ($lang != check_language(0)) { # only set cookie if language selection was changed
setcookie('lang', $lang, time() + 60*60*24*30); # language cookie, lifetime 30 days
# (language preference cookie is processed even if username and/or password are invalid)
}
$h = new MailboxHandler();
if($h->login($fUsername, $fPassword)) {
}
init_session($fUsername, false);
$h = new MailboxHandler();
if ($h->login($fUsername, $fPassword)) {
init_session($fUsername, false);
header("Location: main.php");
exit;
} else {
error_log("PostfixAdmin login failed (username: $fUsername)");
flash_error($PALANG['pLogin_failed']);
}
header("Location: main.php");
exit;
} else {
error_log("PostfixAdmin login failed (username: $fUsername)");
flash_error($PALANG['pLogin_failed']);
}
}
$_SESSION['PFA_token'] = md5(uniqid(rand(), true));
$smarty->assign ('language_selector', language_selector(), false);
$smarty->assign ('smarty_template', 'login');
$smarty->assign ('logintype', 'user');
$smarty->assign ('forgotten_password_reset', Config::read('forgotten_user_password_reset'));
$smarty->display ('index.tpl');
$smarty->assign('language_selector', language_selector(), false);
$smarty->assign('smarty_template', 'login');
$smarty->assign('logintype', 'user');
$smarty->assign('forgotten_password_reset', Config::read('forgotten_user_password_reset'));
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: main.php
* 'Home page' for logged in users.
* Template File: main.php
@ -28,15 +28,12 @@ authentication_require_role('user');
$USERID_USERNAME = authentication_get_username();
$vh = new VacationHandler($USERID_USERNAME);
if($vh->check_vacation()) {
$tummVacationtext = $PALANG['pUsersMain_vacationSet'];
}
else
{
$tummVacationtext = $PALANG['pUsersMain_vacation'];
if ($vh->check_vacation()) {
$tummVacationtext = $PALANG['pUsersMain_vacationSet'];
} else {
$tummVacationtext = $PALANG['pUsersMain_vacation'];
}
$smarty->assign ('tummVacationtext', $tummVacationtext);
$smarty->assign ('smarty_template', 'users_main');
$smarty->display ('index.tpl');
$smarty->assign('tummVacationtext', $tummVacationtext);
$smarty->assign('smarty_template', 'users_main');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: password.php
* Used by users to change their mailbox (and login) password.
* Template File: password.tpl
@ -35,11 +35,12 @@ $username = authentication_get_username();
$pPassword_password_text = "";
$pPassword_password_current_text = "";
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
if(isset($_POST['fCancel'])) {
if (isset($_POST['fCancel'])) {
header("Location: main.php");
exit(0);
}
@ -51,44 +52,39 @@ if ($_SERVER['REQUEST_METHOD'] == "POST")
$error = 0;
$validpass = validate_password($fPassword);
if(count($validpass) > 0) {
if (count($validpass) > 0) {
flash_error($validpass[0]); # TODO: honor all error messages, not only the first one
$error += 1;
}
$mh = new MailboxHandler;
if(!$mh->login($username, $fPassword_current)) {
if (!$mh->login($username, $fPassword_current)) {
$error += 1;
$pPassword_password_current_text = $PALANG['pPassword_password_current_text_error'];
}
if (empty ($fPassword) or ($fPassword != $fPassword2))
{
if (empty($fPassword) or ($fPassword != $fPassword2)) {
$error += 1;
$pPassword_password_text = $PALANG['pPassword_password_text_error'];
}
if ($error == 0)
{
if ($error == 0) {
$mh->init($username); # TODO: error handling
if($mh->change_pw($fPassword, $fPassword_current) ) {
if ($mh->change_pw($fPassword, $fPassword_current)) {
flash_info(Config::Lang_f('pPassword_result_success', $username));
header("Location: main.php");
exit(0);
}
else
{
} else {
flash_error(Config::Lang_f('pPassword_result_error', $username));
}
}
}
$smarty->assign ('SESSID_USERNAME', $username);
$smarty->assign ('pPassword_password_current_text', $pPassword_password_current_text, false);
$smarty->assign ('pPassword_password_text', $pPassword_password_text, false);
$smarty->assign('SESSID_USERNAME', $username);
$smarty->assign('pPassword_password_current_text', $pPassword_password_current_text, false);
$smarty->assign('pPassword_password_text', $pPassword_password_text, false);
$smarty->assign ('smarty_template', 'password');
$smarty->display ('index.tpl');
$smarty->assign('smarty_template', 'password');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -6,7 +6,7 @@
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
@ -22,4 +22,3 @@ require_once('../common.php');
require_once('../vacation.php');
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -6,7 +6,7 @@
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
@ -14,7 +14,7 @@
* File: edit-vacation.php
*
* Allows users to update their vacation status and
* admins to update the vacation status for the their users
* admins to update the vacation status for the their users
*
* Template File: vacation.tpl
*
@ -40,29 +40,28 @@
require_once('common.php');
// only allow admins to change someone else's 'stuff'
if(authentication_has_role('admin')) {
$Admin_role = 1 ;
$fUsername = safeget('username');
list(/*NULL*/,$fDomain) = explode('@',$fUsername);
$Return_url = "list-virtual.php?domain=" . urlencode($fDomain);
# TODO: better check for valid username (check if mailbox exists)
# TODO: (should be done in VacationHandler)
if ($fDomain == '' || !check_owner(authentication_get_username(), $fDomain)) {
die("Invalid username!"); # TODO: better error message
}
}
else {
$Admin_role = 0 ;
$Return_url = "main.php";
authentication_require_role('user');
$fUsername = authentication_get_username();
if (authentication_has_role('admin')) {
$Admin_role = 1 ;
$fUsername = safeget('username');
list(/*NULL*/, $fDomain) = explode('@', $fUsername);
$Return_url = "list-virtual.php?domain=" . urlencode($fDomain);
# TODO: better check for valid username (check if mailbox exists)
# TODO: (should be done in VacationHandler)
if ($fDomain == '' || !check_owner(authentication_get_username(), $fDomain)) {
die("Invalid username!"); # TODO: better error message
}
} else {
$Admin_role = 0 ;
$Return_url = "main.php";
authentication_require_role('user');
$fUsername = authentication_get_username();
}
// is vacation support enabled in $CONF ?
if($CONF['vacation'] == 'NO') {
header ("Location: $Return_url");
exit(0);
if ($CONF['vacation'] == 'NO') {
header("Location: $Return_url");
exit(0);
}
date_default_timezone_set(@date_default_timezone_get()); # Suppress date.timezone warnings
@ -73,7 +72,7 @@ $vh = new VacationHandler($fUsername);
$choice_of_reply = Config::read('vacation_choice_of_reply');
foreach (array_keys($choice_of_reply) as $key) {
$choice_of_reply[$key] = Config::Lang($choice_of_reply[$key]);
$choice_of_reply[$key] = Config::Lang($choice_of_reply[$key]);
}
if ($_SERVER['REQUEST_METHOD'] == "GET") {
@ -85,7 +84,7 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
$tInterval_Time = '';
$details = $vh->get_details();
if($details != false) {
if ($details != false) {
$tSubject = $details['subject'];
$tBody = $details['body'];
$tInterval_Time = $details['interval_time'];
@ -93,123 +92,135 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
$tActiveUntil = $details['activeUntil'];
}
if($vh->check_vacation()) {
flash_info(sprintf($PALANG['pUsersVacation_welcome_text'],htmlentities($tUseremail)));
if ($vh->check_vacation()) {
flash_info(sprintf($PALANG['pUsersVacation_welcome_text'], htmlentities($tUseremail)));
}
//set a default, reset fields for coming back selection
if ($tSubject == '') { $tSubject = html_entity_decode($PALANG['pUsersVacation_subject_text'], ENT_QUOTES, 'UTF-8'); }
if ($tBody == '') { $tBody = html_entity_decode($PALANG['pUsersVacation_body_text'], ENT_QUOTES, 'UTF-8'); }
if ($tSubject == '') {
$tSubject = html_entity_decode($PALANG['pUsersVacation_subject_text'], ENT_QUOTES, 'UTF-8');
}
if ($tBody == '') {
$tBody = html_entity_decode($PALANG['pUsersVacation_body_text'], ENT_QUOTES, 'UTF-8');
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (safepost('token') != $_SESSION['PFA_token']) die('Invalid token!');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (safepost('token') != $_SESSION['PFA_token']) {
die('Invalid token!');
}
if(isset($_POST['fCancel'])) {
header ("Location: $Return_url");
if (isset($_POST['fCancel'])) {
header("Location: $Return_url");
exit(0);
}
$tActiveFrom = date ("Y-m-d 00:00:00", strtotime (safepost('fActiveFrom')));
$tActiveUntil = date ("Y-m-d 23:59:59", strtotime (safepost('fActiveUntil')));
$tActiveFrom = date("Y-m-d 00:00:00", strtotime(safepost('fActiveFrom')));
$tActiveUntil = date("Y-m-d 23:59:59", strtotime(safepost('fActiveUntil')));
$tSubject = safepost('fSubject');
$fSubject = $tSubject;
$tBody = safepost('fBody');
$fBody = $tBody;
$tSubject = safepost('fSubject');
$fSubject = $tSubject;
$tBody = safepost('fBody');
$fBody = $tBody;
$tInterval_Time = safepost('fInterval_Time');
$tInterval_Time = safepost('fInterval_Time');
$fChange = escape_string (safepost('fChange'));
$fBack = escape_string (safepost('fBack'));
$fChange = escape_string(safepost('fChange'));
$fBack = escape_string(safepost('fBack'));
$tUseremail = $fUsername;
$tUseremail = $fUsername;
//set a default, reset fields for coming back selection
if ($tSubject == '') { $tSubject = html_entity_decode($PALANG['pUsersVacation_subject_text'], ENT_QUOTES, 'UTF-8'); }
if ($tBody == '') { $tBody = html_entity_decode($PALANG['pUsersVacation_body_text'], ENT_QUOTES, 'UTF-8'); }
//set a default, reset fields for coming back selection
if ($tSubject == '') {
$tSubject = html_entity_decode($PALANG['pUsersVacation_subject_text'], ENT_QUOTES, 'UTF-8');
}
if ($tBody == '') {
$tBody = html_entity_decode($PALANG['pUsersVacation_body_text'], ENT_QUOTES, 'UTF-8');
}
if (isset($choice_of_reply[$tInterval_Time])) {
$fInterval_Time = $tInterval_Time;
} else {
$fInterval_Time = 0;
}
if (isset($choice_of_reply[$tInterval_Time])) {
$fInterval_Time = $tInterval_Time;
} else {
$fInterval_Time = 0;
}
// if they've set themselves change OR back, delete any record of vacation emails.
// the user is going away - set the goto alias and vacation table as necessary.
// if they've set themselves change OR back, delete any record of vacation emails.
// the user is going away - set the goto alias and vacation table as necessary.
//Set the vacation data for $fUsername
//Set the vacation data for $fUsername
if (!empty ($fChange))
{
if (!empty($fChange)) {
## check if ActiveUnitl is not back in time,
## because vacation.pl will report SMTP recipient $smtp_recipient which resolves to $email does not have an active vacation (rv: $rv, email: $email)"
## and will not send message
if ( ($tActiveUntil >= date ("Y-m-d")) and ($tActiveUntil >= $tActiveFrom) ) {
if (!$vh->set_away($fSubject, $fBody, $fInterval_Time, $tActiveFrom, $tActiveUntil)) {
$error = 1;
}
} else {
if ( $tActiveUntil < date ("Y-m-d") ) {
flash_error($PALANG['pVacation_until_before_today']);
} else {
flash_error($PALANG['pVacation_until_before_from']);
}
$error = 1;
}
}
//if change, remove old one, then perhaps set new one
if (!empty ($fBack))
{
if(!$vh->remove()) {
$error = 1;
}
}
## because vacation.pl will report SMTP recipient $smtp_recipient which resolves to $email does not have an active vacation (rv: $rv, email: $email)"
## and will not send message
if (($tActiveUntil >= date("Y-m-d")) and ($tActiveUntil >= $tActiveFrom)) {
if (!$vh->set_away($fSubject, $fBody, $fInterval_Time, $tActiveFrom, $tActiveUntil)) {
$error = 1;
}
} else {
if ($tActiveUntil < date("Y-m-d")) {
flash_error($PALANG['pVacation_until_before_today']);
} else {
flash_error($PALANG['pVacation_until_before_from']);
}
$error = 1;
}
}
//if change, remove old one, then perhaps set new one
if (!empty($fBack)) {
if (!$vh->remove()) {
$error = 1;
}
}
}
// If NO error then diplay flash message and go back to right url where we came from
if($error == 0) {
if(!empty ($fBack)) {
flash_info(sprintf($PALANG['pVacation_result_removed'],htmlentities($tUseremail)));
header ("Location: $Return_url");
exit;
}
if(!empty($fChange)) {
flash_info(sprintf($PALANG['pVacation_result_added'],htmlentities($tUseremail)));
header ("Location: $Return_url");
exit;
}
}
else {
flash_error(sprintf($PALANG['pVacation_result_error'],htmlentities($fUsername)));
if ($error == 0) {
if (!empty($fBack)) {
flash_info(sprintf($PALANG['pVacation_result_removed'], htmlentities($tUseremail)));
header("Location: $Return_url");
exit;
}
if (!empty($fChange)) {
flash_info(sprintf($PALANG['pVacation_result_added'], htmlentities($tUseremail)));
header("Location: $Return_url");
exit;
}
} else {
flash_error(sprintf($PALANG['pVacation_result_error'], htmlentities($fUsername)));
}
$today = date ("Y-m-d");
if (empty ($tActiveFrom)) $tActiveFrom = $today;
if (empty ($tActiveUntil)) $tActiveUntil = $today;
$today = date("Y-m-d");
if (empty($tActiveFrom)) {
$tActiveFrom = $today;
}
if (empty($tActiveUntil)) {
$tActiveUntil = $today;
}
if ( ! $details['active']) {
# if vacation is disabled, there's no point in displaying the date of the last vacation ;-)
# (which also means users would have to scroll in the calendar a lot)
# so let's be user-friendly and set today's date (but only if the last vacation is in the past)
if ($tActiveFrom < $today) $tActiveFrom = $today;
if ($tActiveUntil < $today) $tActiveUntil = $today;
if (! $details['active']) {
# if vacation is disabled, there's no point in displaying the date of the last vacation ;-)
# (which also means users would have to scroll in the calendar a lot)
# so let's be user-friendly and set today's date (but only if the last vacation is in the past)
if ($tActiveFrom < $today) {
$tActiveFrom = $today;
}
if ($tActiveUntil < $today) {
$tActiveUntil = $today;
}
}
$smarty->assign ('tUseremail', $tUseremail);
$smarty->assign ('tSubject', $tSubject);
$smarty->assign ('tBody', $tBody);
$smarty->assign ('tActiveFrom', date ("d.m.Y", strtotime ($tActiveFrom)));
$smarty->assign ('tActiveUntil', date ("d.m.Y", strtotime ($tActiveUntil)));
$smarty->assign ('select_options', $choice_of_reply);
$smarty->assign ('tInterval_Time', $tInterval_Time);
$smarty->assign ('smarty_template', 'vacation');
$smarty->display ('index.tpl');
$smarty->assign('tUseremail', $tUseremail);
$smarty->assign('tSubject', $tSubject);
$smarty->assign('tBody', $tBody);
$smarty->assign('tActiveFrom', date("d.m.Y", strtotime($tActiveFrom)));
$smarty->assign('tActiveUntil', date("d.m.Y", strtotime($tActiveUntil)));
$smarty->assign('select_options', $choice_of_reply);
$smarty->assign('tInterval_Time', $tInterval_Time);
$smarty->assign('smarty_template', 'vacation');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -1,16 +1,16 @@
<?php
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: viewlog.php
* Shows entries from the log table to users.
*
@ -29,65 +29,63 @@ require_once('common.php');
authentication_require_role('admin');
$SESSID_USERNAME = authentication_get_username();
if(authentication_has_role('global-admin')) {
$list_domains = list_domains ();
}
else {
$list_domains = list_domains_for_admin ($SESSID_USERNAME);
if (authentication_has_role('global-admin')) {
$list_domains = list_domains();
} else {
$list_domains = list_domains_for_admin($SESSID_USERNAME);
}
$fDomain = '';
$error = 0;
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if ((is_array ($list_domains) and sizeof ($list_domains) > 0)) $fDomain = $list_domains[0];
if ($_SERVER['REQUEST_METHOD'] == "GET") {
if ((is_array($list_domains) and sizeof($list_domains) > 0)) {
$fDomain = $list_domains[0];
}
} elseif ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset ($_POST['fDomain'])) $fDomain = escape_string ($_POST['fDomain']);
if (isset($_POST['fDomain'])) {
$fDomain = escape_string($_POST['fDomain']);
}
} else {
die('Unknown request method');
die('Unknown request method');
}
if (! (check_owner ($SESSID_USERNAME, $fDomain) || authentication_has_role('global-admin')))
{
$error = 1;
flash_error($PALANG['pViewlog_result_error']);
if (! (check_owner($SESSID_USERNAME, $fDomain) || authentication_has_role('global-admin'))) {
$error = 1;
flash_error($PALANG['pViewlog_result_error']);
}
// we need to initialize $tLog as an array!
$tLog = array();
if ($error != 1)
{
$table_log = table_by_key('log');
$page_size = isset($CONF['page_size']) ? intval($CONF['page_size']) : 35;
if ($error != 1) {
$table_log = table_by_key('log');
$page_size = isset($CONF['page_size']) ? intval($CONF['page_size']) : 35;
$query = "SELECT timestamp,username,domain,action,data FROM $table_log WHERE domain='$fDomain' ORDER BY timestamp DESC LIMIT $page_size";
if (db_pgsql()) {
$query = "SELECT extract(epoch from timestamp) as timestamp,username,domain,action,data FROM $table_log WHERE domain='$fDomain' ORDER BY timestamp DESC LIMIT $page_size";
}
$result=db_query($query);
if ($result['rows'] > 0)
{
while ($row = db_array ($result['result']))
{
if (db_pgsql()) {
$row['timestamp']=gmstrftime('%c %Z',$row['timestamp']);
}
$tLog[] = $row;
}
}
$query = "SELECT timestamp,username,domain,action,data FROM $table_log WHERE domain='$fDomain' ORDER BY timestamp DESC LIMIT $page_size";
if (db_pgsql()) {
$query = "SELECT extract(epoch from timestamp) as timestamp,username,domain,action,data FROM $table_log WHERE domain='$fDomain' ORDER BY timestamp DESC LIMIT $page_size";
}
$result=db_query($query);
if ($result['rows'] > 0) {
while ($row = db_array($result['result'])) {
if (db_pgsql()) {
$row['timestamp']=gmstrftime('%c %Z', $row['timestamp']);
}
$tLog[] = $row;
}
}
}
for ($i = 0; $i < count ($tLog); $i++)
$tLog[$i]['action'] = $PALANG ['pViewlog_action_'.$tLog [$i]['action']];
for ($i = 0; $i < count($tLog); $i++) {
$tLog[$i]['action'] = $PALANG ['pViewlog_action_'.$tLog [$i]['action']];
}
$smarty->assign ('domain_list', $list_domains);
$smarty->assign ('domain_selected', $fDomain);
$smarty->assign ('tLog', $tLog,false);
$smarty->assign ('fDomain', $fDomain);
$smarty->assign ('smarty_template', 'viewlog');
$smarty->display ('index.tpl');
$smarty->assign('domain_list', $list_domains);
$smarty->assign('domain_selected', $fDomain);
$smarty->assign('tLog', $tLog, false);
$smarty->assign('fDomain', $fDomain);
$smarty->assign('smarty_template', 'viewlog');
$smarty->display('index.tpl');
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */
?>

@ -27,12 +27,12 @@
* }
*
* Note, the requirement that your XmlRpc client provides cookies with each request.
* If it does not do this, then your authentication details will not persist across requests, and
* If it does not do this, then your authentication details will not persist across requests, and
* this XMLRPC interface will not work.
*/
require_once(dirname(__FILE__) . '/common.php');
if($CONF['xmlrpc_enabled'] == false) {
if ($CONF['xmlrpc_enabled'] == false) {
die("xmlrpc support disabled");
}
@ -45,9 +45,8 @@ $server = new Zend_XmlRpc_Server();
* @return boolean true on success, else false.
*/
function login($username, $password) {
$h = new MailboxHandler();
if($h->login($username, $password)) {
if ($h->login($username, $password)) {
session_regenerate_id();
$_SESSION['authenticated'] = true;
$_SESSION['sessid'] = array();
@ -57,10 +56,9 @@ function login($username, $password) {
return false;
}
if(!isset($_SESSION['authenticated'])) {
if (!isset($_SESSION['authenticated'])) {
$server->addFunction('login', 'login');
}
else {
} else {
$server->setClass('UserProxy', 'user');
$server->setClass('VacationProxy', 'vacation');
$server->setClass('AliasProxy', 'alias');
@ -77,15 +75,17 @@ class UserProxy {
*/
public function changePassword($old_password, $new_password) {
$uh = new MailboxHandler();
if (!$uh->init($_SESSION['sessid']['username'])) return false;
if (!$uh->init($_SESSION['sessid']['username'])) {
return false;
}
return $uh->change_pw($new_password, $old_password);
}
/**
* @param string $username
* @param string $password
* @return boolean true if successful.
*/
/**
* @param string $username
* @param string $password
* @return boolean true if successful.
*/
public function login($username, $password) {
$uh = new MailboxHandler(); # $_SESSION['sessid']['username']);
return $uh->login($username, $password);
@ -139,8 +139,6 @@ class VacationProxy {
$vh = new VacationHandler($_SESSION['sessid']['username']);
return $vh->set_away($subject, $body, $interval_time, $activeFrom, $activeUntil);
}
}
class AliasProxy {
/**

@ -127,9 +127,9 @@ class PostfixAdmin {
define('DS', DIRECTORY_SEPARATOR);
define('CORE_INCLUDE_PATH', dirname(__FILE__));
define('CORE_PATH', dirname(CORE_INCLUDE_PATH) ); # CORE_INCLUDE_PATH/../
define('CORE_PATH', dirname(CORE_INCLUDE_PATH)); # CORE_INCLUDE_PATH/../
if(!defined('POSTFIXADMIN')) { # already defined if called from setup.php
if (!defined('POSTFIXADMIN')) { # already defined if called from setup.php
define('POSTFIXADMIN', 1); # checked in included files
}
}
@ -166,14 +166,14 @@ class PostfixAdmin {
* @return boolean Success.
*/
private function __bootstrap() {
if ($this->params['webroot'] != '' ) {
define('PATH', $this->params['webroot'] );
if ($this->params['webroot'] != '') {
define('PATH', $this->params['webroot']);
} else {
define('PATH', CORE_PATH);
}
if (!file_exists(PATH)) {
$this->stderr( PATH . " don't exists");
$this->stderr(PATH . " don't exists");
return false;
}
@ -328,7 +328,7 @@ class PostfixAdmin {
}
$result = fgets($this->stdin);
if ($result === false){
if ($result === false) {
exit(1);
}
$result = trim($result);
@ -442,7 +442,7 @@ class PostfixAdmin {
$this->stdout("");
$this->stdout("Available modules:");
$modules = explode(',','admin,domain,mailbox,alias,aliasdomain,fetchmail');
$modules = explode(',', 'admin,domain,mailbox,alias,aliasdomain,fetchmail');
foreach ($modules as $module) {
$this->stdout(" $module");
}
@ -466,12 +466,11 @@ class PostfixAdmin {
$this->stdout("");
exit();
}
}
define ("POSTFIXADMIN_CLI", 1);
define("POSTFIXADMIN_CLI", 1);
$dispatcher = new PostfixAdmin($argv);

@ -7,29 +7,25 @@ class PasswordTask extends Shell {
*
* @access public
*/
function execute() {
public function execute() {
$random = false;
if (empty($this->args)) {
$this->__interactive();
}
if (!empty($this->args[0])) {
$address = $this->args[0];
if (isset($this->params['g']) && $this->params['g'] == true ) {
if (isset($this->params['g']) && $this->params['g'] == true) {
$random = true;
$password = NULL;
} elseif (isset($this->args[1]) && strlen($this->args[1]) > 8) { # TODO use validate_password()
$password = null;
} elseif (isset($this->args[1]) && strlen($this->args[1]) > 8) { # TODO use validate_password()
$password = $this->args[1];
} else {
$this->Dispatch->stderr('Missing <newpw> or -g. Falling back to interactive mode.');
$this->__interactive();
}
$this->__handle($address, $password, $random);
}
}
@ -37,12 +33,11 @@ class PasswordTask extends Shell {
* Interactive
*/
private function __interactive() {
while(true) {
while (true) {
$question = "Which address' password do you want to change?";
$address = $this->in($question);
if(filter_var($address, FILTER_VALIDATE_EMAIL)) {
if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
break;
}
$this->err("Invalid emailaddress");
@ -54,7 +49,7 @@ class PasswordTask extends Shell {
$sure = $this->in(join("\n", $question2), array('y','n'));
if ($sure == 'n' ) {
if ($sure == 'n') {
$this->out('You\'re not sure.');
$this->_stop();
}
@ -65,14 +60,13 @@ class PasswordTask extends Shell {
$random == 'y' ? $random = true : $random = false;
$password = NULL;
$password = null;
if ($random == false) {
$question = "Pleas enter the new password?";
$password = $this->in($question);
}
$this->__handle($address, $password, $random);
}
/**
@ -80,20 +74,19 @@ class PasswordTask extends Shell {
* @param string $password optional
* @param boolean $random optional - true to generate random pw.
*/
private function __handle($address, $password = NULL, $random = false) {
private function __handle($address, $password = null, $random = false) {
if ($random == true) {
$password = generate_password();
}
if ($password != NULL) {
if ($password != null) {
$handler = new MailboxHandler();
if (!$handler->init($address)) {
$this->error("Change Password",join("\n", $handler->errormsg));
$this->error("Change Password", join("\n", $handler->errormsg));
}
if ( ! $handler->change_pw($password, NULL, false) ){
$this->error("Change Password",join("\n", $handler->errormsg));
if (! $handler->change_pw($password, null, false)) {
$this->error("Change Password", join("\n", $handler->errormsg));
}
}
@ -101,7 +94,7 @@ class PasswordTask extends Shell {
$this->out("Password updated.");
$this->hr();
$this->out(sprintf('The Mail address is %20s', $address));
$this->out(sprintf('The new password is %20s',$password));
$this->out(sprintf('The new password is %20s', $password));
$this->hr();
return ;

@ -36,62 +36,62 @@ class Shell {
* @var object
* @access public
*/
var $Dispatch = null;
public $Dispatch = null;
/**
* If true, the script will ask for permission to perform actions.
*
* @var boolean
* @access public
*/
var $interactive = true;
public $interactive = true;
/**
* Contains command switches parsed from the command line.
*
* @var array
* @access public
*/
var $params = array();
public $params = array();
/**
* Contains arguments parsed from the command line.
*
* @var array
* @access public
*/
var $args = array();
public $args = array();
/**
* The file name of the shell that was invoked.
*
* @var string
* @access public
*/
var $shell = null;
public $shell = null;
/**
* The class name of the shell that was invoked.
*
* @var string
* @access public
*/
var $className = null;
public $className = null;
/**
* The command called if public methods are available.
*
* @var string
* @access public
*/
var $command = null;
public $command = null;
/**
* The name of the shell in camelized.
*
* @var string
* @access public
*/
var $name = null;
public $name = null;
/**
* Constructs this Shell instance.
*
*/
function __construct(&$dispatch) {
public function __construct(&$dispatch) {
$vars = array('params', 'args', 'shell', 'shellCommand'=> 'command');
foreach ($vars as $key => $var) {
if (is_string($key)) {
@ -117,7 +117,7 @@ class Shell {
*
* @access public
*/
function initialize() {
public function initialize() {
}
/**
* Starts up the the Shell
@ -126,9 +126,9 @@ class Shell {
*
* @access public
*/
function startup() {
public function startup() {
#CHECK!
if ( empty($this->params['q'] ) ) {
if (empty($this->params['q'])) {
$this->_welcome();
}
$CONF = Config::read('all');
@ -138,7 +138,7 @@ class Shell {
*
* @access protected
*/
function _welcome() {
public function _welcome() {
$this->out("\nWelcome to Postfixadmin-CLI v" . $this->Dispatch->version);
$this->hr();
}
@ -152,11 +152,13 @@ class Shell {
* @return Either the default value, or the user-provided input.
* @access public
*/
function in($prompt, $options = null, $default = null) {
public function in($prompt, $options = null, $default = null) {
if (!$this->interactive) {
return $default;
}
if ($prompt != '') $this->out("");
if ($prompt != '') {
$this->out("");
}
$in = $this->Dispatch->getInput($prompt, $options, $default);
if ($options && is_string($options)) {
@ -184,10 +186,10 @@ class Shell {
* @param boolean $newline If true, the outputs gets an added newline.
* @access public
*/
function out($string, $newline = true) {
public function out($string, $newline = true) {
if (is_array($string)) {
$str = '';
foreach($string as $message) {
foreach ($string as $message) {
$str .= $message ."\n";
}
$string = $str;
@ -200,10 +202,10 @@ class Shell {
* @param string $string Error text to output.
* @access public
*/
function err($string) {
public function err($string) {
if (is_array($string)) {
$str = '';
foreach($string as $message) {
foreach ($string as $message) {
$str .= $message ."\n";
}
$string = $str;
@ -216,7 +218,7 @@ class Shell {
* @param boolean $newline If true, the outputs gets an added newline.
* @access public
*/
function hr($newline = false) {
public function hr($newline = false) {
if ($newline) {
$this->out("\n");
}
@ -232,7 +234,7 @@ class Shell {
* @param string $msg Error message
* @access public
*/
function error($title, $msg) {
public function error($title, $msg) {
$out = "$title\n";
$out .= "$msg\n";
$out .= "\n";
@ -244,7 +246,7 @@ class Shell {
*
* @access public
*/
function help() {
public function help() {
if ($this->command != null) {
$this->err("Unknown {$this->name} command '$this->command'.\nFor usage, try 'postfixadmin-cli {$this->shell} help'.\n\n");
} else {
@ -258,10 +260,7 @@ class Shell {
* @return void
* @access public
*/
function _stop($status = 0) {
public function _stop($status = 0) {
exit($status);
}
}

@ -1,34 +1,32 @@
<?php
class Crypt {
/**
* @access private
*/
protected $plain = '';
/**
* @access private
*/
protected $password;
protected $size;
function __construct($plaintext) {
$this->plain = $plaintext;
}
/**
* @return true/false boolean
*/
public function crypt($algorithm) {
return true;
}
public function get() {
return $this->password;
}
}
<?php
class Crypt {
/**
* @access private
*/
protected $plain = '';
/**
* @access private
*/
protected $password;
protected $size;
public function __construct($plaintext) {
$this->plain = $plaintext;
}
/**
* @return true/false boolean
*/
public function crypt($algorithm) {
return true;
}
public function get() {
return $this->password;
}
}

@ -1,32 +1,31 @@
<?php
require_once('crypt.php');
require_once('dovecot_crypt.php');
$test = new DovecotCrypt('test');
$test->crypt('CRYPT');
echo "CRYPT:\n\n";
echo "Crypted: ".$test->get()."\n";
if ($test->verify('CRYPT', $test->get())) {
echo "Varified: true\n";
} else {
echo "Varified: false\n";
}
echo "\n";
$test2 = new DovecotCrypt('test2');
$test2->crypt('CRAM-MD5');
echo "CRAM_MD5:\n\n";
echo "Crypted: ".$test2->get()."\n";
if ($test2->verify('CRAM-MD5', $test2->get())) {
echo "Varified: true\n";
} else {
echo "Varified: false\n";
}
echo "\n";
?>
<?php
require_once('crypt.php');
require_once('dovecot_crypt.php');
$test = new DovecotCrypt('test');
$test->crypt('CRYPT');
echo "CRYPT:\n\n";
echo "Crypted: ".$test->get()."\n";
if ($test->verify('CRYPT', $test->get())) {
echo "Varified: true\n";
} else {
echo "Varified: false\n";
}
echo "\n";
$test2 = new DovecotCrypt('test2');
$test2->crypt('CRAM-MD5');
echo "CRAM_MD5:\n\n";
echo "Crypted: ".$test2->get()."\n";
if ($test2->verify('CRAM-MD5', $test2->get())) {
echo "Varified: true\n";
} else {
echo "Varified: false\n";
}
echo "\n";

@ -1,134 +1,128 @@
<?php
define('SHA1_RESULTLEN', (160/8));
define('SHA256_RESULTLEN', (256 / 8));
define('CRAM_MD5_CONTEXTLEN', 32);
define('MD5_RESULTLEN', (128/8));
define('MD4_RESULTLEN', (128/8));
define('LM_HASH_SIZE', 16);
define('NTLMSSP_HASH_SIZE', 16);
class DovecotCrypt extends Crypt {
private $salt_chars = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/**
* Array
* Crypt type and which function handles it.
* array('alogrithm' => array('encoding', 'length', 'verify', 'function'))
*/
public $password_schemes = array(
'CRYPT' => array('NONE', 0, 'crypt_verify', 'crypt_generate'),
'MD5' => array('NONE', 0, 'md5_verify', 'md5_generate'),
//'MD5-CRYPT' => array('NONE', 0, 'md5_crypt_verify', 'md5_crypt_generate'),
'SHA' => array('BASE64', SHA1_RESULTLEN, NULL, 'sha1_generate'),
'SHA1' => array('BASE64', SHA1_RESULTLEN, NULL, 'sha1_generate'),
//'SHA256' => array('BASE64', SHA256_RESULTLEN, NULL, 'sha256_generate'),
//'SMD5' => array('BASE64', 0, 'smd5_verify', 'smd5_generate'),
//'SSHA' => array('BASE64', 0, 'ssha_verify', 'ssha_generate'),
//'SSHA256' => array('BASE64', 0, 'ssha356_verify', 'ssha256_generate'),
'PLAIN' => array('NONE', 0, NULL, 'plain_generate'),
'CLEARTEXT' => array('NONE', 0, NULL, 'plain_generate'),
'CRAM-MD5' => array('HEX', CRAM_MD5_CONTEXTLEN, NULL, 'cram_md5_generate'),
//'HMAC-MD5' => array('HEX', CRAM_MD5_CONTEXTLEN, NULL, 'cram_md5_generate'),
//'DIGEST-MD5' => array('HEX', MD5_RESULTLEN, NULL, 'digest_md5_generate'),
//'PLAIN-MD4' => array('HEX', MD4_RESULTLEN, NULL, 'plain_md4_generate'),
//'PLAIN-MD5' => array('HEX', MD5_RESULTLEN, NULL, 'plain_md5_generate'),
//'LDAP-MD5' => array('BASE64', MD5_RESULTLEN, NULL, 'plain_md5_generate'),
//'LANMAN' => array('HEX', LM_HASH_SIZE, NULL, 'lm_generate'),
//'NTLM' => array('HEX', NTLMSSP_HASH_SIZE, NULL, 'ntlm_generate'),
//'OTP' => array('NONE', 0, 'otp_verify', 'otp_generate'),
//'SKEY' => array('NONE', 0, 'otp_verify', 'skey_generate'),
//'RPA' => array('HEX', MD5_RESULTLEN, NULL, 'rpa_generate'),
);
public function crypt($algorithm) {
if( !array_key_exists($algorithm, $this->password_schemes) ) {
$this->errormsg[] = "This password scheme isn't supported. Check our Wiki!";
return false;
}
$scheme = $this->password_schemes[$algorithm];
$func = '__'.$scheme[3];
$this->password = $this->$func($this->plain);
//$this->plain = '';
}
public function verify($algorithm, $password) {
if( !array_key_exists($algorithm, $this->password_schemes) ) {
$this->errormsg[] = "This password scheme isn't supported. Check our Wiki!";
return false;
}
$scheme = $this->password_schemes[$algorithm];
if($scheme[2] == NULL) {
$this->errormsg[] = "This password scheme doesn't support verification";
return false;
}
$func = '__'.$scheme[2];
return $this->$func($this->plain, $password);
}
private function __crypt_verify($plaintext, $password) {
$crypted = crypt($plaintext, $password);
return strcmp($crypted, $password) == 0;
}
private function __crypt_generate($plaintext) {
$password = crypt($plaintext);
return $password;
}
private function __md5_generate($plaintext) {
return $password;
}
private function __sha1_generate() {
}
private function __plain_generate() {
}
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/auth/password-scheme.c cram_md5_generate
#am i right that the hmac salt is the plaintext password itself?
$salt = $plaintext;
if(function_exists('hash_hmac')) { //Some providers doesn't offers hash access.
return hash_hmac('md5', $plaintext, $salt);
} else {
return custom_hmac('md5', $plaintext, $salt);
}
}
function custom_hmac($algo, $data, $key, $raw_output = false)
{
$algo = strtolower($algo);
$pack = 'H'.strlen($algo('test'));
$size = 64;
$opad = str_repeat(chr(0x5C), $size);
$ipad = str_repeat(chr(0x36), $size);
if (strlen($key) > $size) {
$key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
} else {
$key = str_pad($key, $size, chr(0x00));
}
for ($i = 0; $i < strlen($key) - 1; $i++) {
$opad[$i] = $opad[$i] ^ $key[$i];
$ipad[$i] = $ipad[$i] ^ $key[$i];
}
$output = $algo($opad.pack($pack, $algo($ipad.$data)));
return ($raw_output) ? pack($pack, $output) : $output;
}
}
<?php
define('SHA1_RESULTLEN', (160/8));
define('SHA256_RESULTLEN', (256 / 8));
define('CRAM_MD5_CONTEXTLEN', 32);
define('MD5_RESULTLEN', (128/8));
define('MD4_RESULTLEN', (128/8));
define('LM_HASH_SIZE', 16);
define('NTLMSSP_HASH_SIZE', 16);
class DovecotCrypt extends Crypt {
private $salt_chars = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/**
* Array
* Crypt type and which function handles it.
* array('alogrithm' => array('encoding', 'length', 'verify', 'function'))
*/
public $password_schemes = array(
'CRYPT' => array('NONE', 0, 'crypt_verify', 'crypt_generate'),
'MD5' => array('NONE', 0, 'md5_verify', 'md5_generate'),
//'MD5-CRYPT' => array('NONE', 0, 'md5_crypt_verify', 'md5_crypt_generate'),
'SHA' => array('BASE64', SHA1_RESULTLEN, null, 'sha1_generate'),
'SHA1' => array('BASE64', SHA1_RESULTLEN, null, 'sha1_generate'),
//'SHA256' => array('BASE64', SHA256_RESULTLEN, NULL, 'sha256_generate'),
//'SMD5' => array('BASE64', 0, 'smd5_verify', 'smd5_generate'),
//'SSHA' => array('BASE64', 0, 'ssha_verify', 'ssha_generate'),
//'SSHA256' => array('BASE64', 0, 'ssha356_verify', 'ssha256_generate'),
'PLAIN' => array('NONE', 0, null, 'plain_generate'),
'CLEARTEXT' => array('NONE', 0, null, 'plain_generate'),
'CRAM-MD5' => array('HEX', CRAM_MD5_CONTEXTLEN, null, 'cram_md5_generate'),
//'HMAC-MD5' => array('HEX', CRAM_MD5_CONTEXTLEN, NULL, 'cram_md5_generate'),
//'DIGEST-MD5' => array('HEX', MD5_RESULTLEN, NULL, 'digest_md5_generate'),
//'PLAIN-MD4' => array('HEX', MD4_RESULTLEN, NULL, 'plain_md4_generate'),
//'PLAIN-MD5' => array('HEX', MD5_RESULTLEN, NULL, 'plain_md5_generate'),
//'LDAP-MD5' => array('BASE64', MD5_RESULTLEN, NULL, 'plain_md5_generate'),
//'LANMAN' => array('HEX', LM_HASH_SIZE, NULL, 'lm_generate'),
//'NTLM' => array('HEX', NTLMSSP_HASH_SIZE, NULL, 'ntlm_generate'),
//'OTP' => array('NONE', 0, 'otp_verify', 'otp_generate'),
//'SKEY' => array('NONE', 0, 'otp_verify', 'skey_generate'),
//'RPA' => array('HEX', MD5_RESULTLEN, NULL, 'rpa_generate'),
);
public function crypt($algorithm) {
if (!array_key_exists($algorithm, $this->password_schemes)) {
$this->errormsg[] = "This password scheme isn't supported. Check our Wiki!";
return false;
}
$scheme = $this->password_schemes[$algorithm];
$func = '__'.$scheme[3];
$this->password = $this->$func($this->plain);
//$this->plain = '';
}
public function verify($algorithm, $password) {
if (!array_key_exists($algorithm, $this->password_schemes)) {
$this->errormsg[] = "This password scheme isn't supported. Check our Wiki!";
return false;
}
$scheme = $this->password_schemes[$algorithm];
if ($scheme[2] == null) {
$this->errormsg[] = "This password scheme doesn't support verification";
return false;
}
$func = '__'.$scheme[2];
return $this->$func($this->plain, $password);
}
private function __crypt_verify($plaintext, $password) {
$crypted = crypt($plaintext, $password);
return strcmp($crypted, $password) == 0;
}
private function __crypt_generate($plaintext) {
$password = crypt($plaintext);
return $password;
}
private function __md5_generate($plaintext) {
return $password;
}
private function __sha1_generate() {
}
private function __plain_generate() {
}
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/auth/password-scheme.c cram_md5_generate
#am i right that the hmac salt is the plaintext password itself?
$salt = $plaintext;
if (function_exists('hash_hmac')) { //Some providers doesn't offers hash access.
return hash_hmac('md5', $plaintext, $salt);
} else {
return custom_hmac('md5', $plaintext, $salt);
}
}
public function custom_hmac($algo, $data, $key, $raw_output = false) {
$algo = strtolower($algo);
$pack = 'H'.strlen($algo('test'));
$size = 64;
$opad = str_repeat(chr(0x5C), $size);
$ipad = str_repeat(chr(0x36), $size);
if (strlen($key) > $size) {
$key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
} else {
$key = str_pad($key, $size, chr(0x00));
}
for ($i = 0; $i < strlen($key) - 1; $i++) {
$opad[$i] = $opad[$i] ^ $key[$i];
$ipad[$i] = $ipad[$i] ^ $key[$i];
}
$output = $algo($opad.pack($pack, $algo($ipad.$data)));
return ($raw_output) ? pack($pack, $output) : $output;
}
}

@ -16,10 +16,9 @@ class PFASmarty {
// if it's not present or writeable, smarty should just not cache.
$templates_c = dirname(__FILE__) . '/templates_c';
if(is_dir($templates_c) && is_writeable($templates_c)) {
if (is_dir($templates_c) && is_writeable($templates_c)) {
$this->template->setCompileDir($templates_c);
}
else {
} else {
# unfortunately there's no sane way to just disable compiling of templates
clearstatcache(); // just incase someone just fixed it; on their next refresh it should work.
error_log("ERROR: directory $templates_c doesn't exist or isn't writeable for the webserver");
@ -31,7 +30,7 @@ class PFASmarty {
public function assign($key, $value, $sanitise = true) {
$this->template->assign("RAW_$key", $value);
if($sanitise == false) {
if ($sanitise == false) {
return $this->template->assign($key, $value);
}
$clean = $this->sanitise($value);
@ -40,29 +39,29 @@ class PFASmarty {
}
public function display($template) {
header ("Expires: Sun, 16 Mar 2003 05:00:00 GMT");
header ("Last-Modified: " . gmdate ("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-store, no-cache, must-revalidate");
header ("Cache-Control: post-check=0, pre-check=0", false);
header ("Pragma: no-cache");
header ("Content-Type: text/html; charset=UTF-8");
header("Expires: Sun, 16 Mar 2003 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-Type: text/html; charset=UTF-8");
$this->template->display($template);
unset($_SESSION['flash']); # cleanup flash messages
}
/**
* Recursive cleaning of data, using htmlentities - this assumes we only ever output to HTML and we're outputting in UTF-8 charset
* Recursive cleaning of data, using htmlentities - this assumes we only ever output to HTML and we're outputting in UTF-8 charset
*
* @param mixed $data - array or primitive type; objects not supported.
* @return mixed $data
* */
public function sanitise($data) {
if(!is_array($data)) {
if (!is_array($data)) {
return htmlentities($data, ENT_QUOTES, 'UTF-8', false);
}
if(is_array($data)) {
if (is_array($data)) {
$clean = array();
foreach($data as $key => $value) {
foreach ($data as $key => $value) {
/* as this is a nested data structure it's more likely we'll output the key too (at least in my opinion, so we'll sanitise it too */
$clean[$this->sanitise($key)] = $this->sanitise($value);
}
@ -72,27 +71,34 @@ class PFASmarty {
}
$smarty = new PFASmarty();
if (!isset($rel_path)) $rel_path = ''; # users/* sets this to '../'
if (!isset($rel_path)) {
$rel_path = '';
} # users/* sets this to '../'
$CONF['theme_css'] = $rel_path . htmlentities($CONF['theme_css']);
if (!empty($CONF['theme_custom_css'])) $CONF['theme_custom_css'] = $rel_path . htmlentities($CONF['theme_custom_css']);
if (!empty($CONF['theme_custom_css'])) {
$CONF['theme_custom_css'] = $rel_path . htmlentities($CONF['theme_custom_css']);
}
$CONF['theme_logo'] = $rel_path . htmlentities($CONF['theme_logo']);
$smarty->assign ('CONF', $CONF);
$smarty->assign ('PALANG', $PALANG);
$smarty->assign('CONF', $CONF);
$smarty->assign('PALANG', $PALANG);
$smarty->assign('url_domain', '');
//*** footer.tpl
$smarty->assign ('version', $version);
$smarty->assign('version', $version);
//*** menu.tpl
$smarty->assign ('boolconf_alias_domain', Config::bool('alias_domain'));
$smarty->assign ('authentication_has_role', array ('global_admin' => authentication_has_role ('global-admin'), 'admin' => authentication_has_role ('admin'), 'user' => authentication_has_role ('user')));
$smarty->assign('boolconf_alias_domain', Config::bool('alias_domain'));
$smarty->assign('authentication_has_role', array('global_admin' => authentication_has_role('global-admin'), 'admin' => authentication_has_role('admin'), 'user' => authentication_has_role('user')));
function eval_size ($aSize) {
if ($aSize == 0) {$ret_val = Config::Lang('pOverview_unlimited'); }
elseif ($aSize < 0) {$ret_val = Config::Lang('pOverview_disabled'); }
else {$ret_val = $aSize; }
return $ret_val;
function eval_size($aSize) {
if ($aSize == 0) {
$ret_val = Config::Lang('pOverview_unlimited');
} elseif ($aSize < 0) {
$ret_val = Config::Lang('pOverview_disabled');
} else {
$ret_val = $aSize;
}
return $ret_val;
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

@ -1,6 +1,6 @@
<?php
/**
* Test for Postfixadmin
* Test for Postfixadmin
*
* @package tests
*/
@ -8,7 +8,6 @@
require_once('RemoteTest.php');
class RemoteAliasTest extends RemoteTest {
public function __construct() {
parent::__construct();
global $CONF;
@ -29,8 +28,7 @@ class RemoteAliasTest extends RemoteTest {
try {
/* although we created an alias record, for users, this isn't returned... */
$this->assertEqual($this->alias->get(), array());
}
catch(Exception $e) {
} catch (Exception $e) {
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
}
}
@ -47,9 +45,9 @@ class RemoteAliasTest extends RemoteTest {
$this->assertFalse($this->alias->hasStoreAndForward());
}
public function testUpdateForwardandStore() {
public function testUpdateForwardandStore() {
$orig_aliases = $this->alias->get();
if(!is_array($orig_aliases)) {
if (!is_array($orig_aliases)) {
$orig_aliases = array();
}
$orig_aliases[] = 'roger@robbit.com';

@ -9,12 +9,11 @@ require_once('Zend/Http/Client.php');
require_once('Zend/Registry.php');
abstract class RemoteTest extends PHPUnit_Framework_TestCase {
protected $server_url = 'http://orange/david/postfixadmin/xmlrpc.php';
protected $username = 'roger@example.com';
protected $password = 'patchthedog';
/* xmlrpc objects... */
/* xmlrpc objects... */
protected $user;
protected $vacation;
protected $alias;
@ -28,7 +27,7 @@ abstract class RemoteTest extends PHPUnit_Framework_TestCase {
$login_object = $this->xmlrpc_client->getProxy('login');
$success = $login_object->login($this->username, $this->password);
if(!$success) {
if (!$success) {
var_dump($success);
die("Failed to login to xmlrpc interface");
}

@ -8,7 +8,6 @@
require_once('RemoteTest.php');
class RemoteUserTest extends RemoteTest {
public function __construct() {
parent::__construct();
global $CONF;
@ -30,8 +29,7 @@ class RemoteUserTest extends RemoteTest {
$this->assertTrue($this->user->login($this->username, $this->password));
$this->assertTrue($this->user->changePassword($this->password, 'foobar'));
$this->assertTrue($this->user->login($this->username, 'foobar'));
}
catch(Exception $e) {
} catch (Exception $e) {
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
}
}

@ -8,18 +8,17 @@
require_once('RemoteTest.php');
class RemoteVacationTest extends RemoteTest {
public function __construct() {
parent::__construct();
global $CONF;
// Ensure config.inc.php is vaguely correct.
if($CONF['vacation'] != 'YES' || $CONF['vacation_control'] != "YES") {
if ($CONF['vacation'] != 'YES' || $CONF['vacation_control'] != "YES") {
die("Cannot run tests; vacation not enabled - see config.inc.php");
}
if($CONF['vacation_domain'] != 'autoreply.example.com') {
if ($CONF['vacation_domain'] != 'autoreply.example.com') {
die("Cannot run tests; vacation_domain is not set to autoreply.example.com - see config.inc.php");
}
}
}
@ -36,8 +35,7 @@ class RemoteVacationTest extends RemoteTest {
public function testIsVacationSupported() {
try {
$this->assertTrue($this->vacation->isVacationSupported());
}
catch(Exception $e){
} catch (Exception $e) {
var_dump($e);
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
die("fail..");
@ -52,15 +50,14 @@ class RemoteVacationTest extends RemoteTest {
public function testGetDetails() {
$details = $this->vacation->getDetails();
$this->assertFalse($details); // empty by default (thansk to tearDown/setUp);
}
}
public function testSetAway() {
try {
$this->assertFalse($this->vacation->checkVacation());
$this->assertTrue($this->vacation->setAway('zzzz', 'aaaa'));
$this->assertTrue($this->vacation->checkVacation());
}
catch(Exception $e) {
} catch (Exception $e) {
var_dump($this->xmlrpc_client->getHttpClient()->getLastResponse()->getBody());
}
$details = $this->vacation->getDetails();
@ -77,7 +74,6 @@ class RemoteVacationTest extends RemoteTest {
$this->assertEqual($details['subject'], 'subject');
$this->assertEqual($details['body'], 'body');
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */

Loading…
Cancel
Save