0
0
mirror of https://github.com/postfixadmin/postfixadmin.git synced 2024-09-20 03:36:20 +02:00

reforamt cli commands; update code to php v5 syntax; remove regexp and use filter_var for email validation; use private/protected/public

git-svn-id: https://svn.code.sf.net/p/postfixadmin/code/trunk@1840 a1433add-5e2c-0410-b055-b7f2511e0802
This commit is contained in:
David Goodwin 2016-05-20 19:55:55 +00:00
parent a00e8a811d
commit 54603b0968
3 changed files with 735 additions and 814 deletions

View File

@ -33,103 +33,97 @@
class PostfixAdmin { class PostfixAdmin {
/** /**
* Version * Version
* *
* @var string * @var string
* @access protected
*/ */
var $version ='0.2'; public $version ='0.2';
/** /**
* Standard input stream. * Standard input stream.
* *
* @var filehandle * @var filehandle
* @access public
*/ */
var $stdin; public $stdin;
/**
/**
* Standard output stream. * Standard output stream.
* *
* @var filehandle * @var filehandle
* @access public
*/ */
var $stdout; public $stdout;
/**
/**
* Standard error stream. * Standard error stream.
* *
* @var filehandle * @var filehandle
* @access public
*/ */
var $stderr; public $stderr;
/**
/**
* Contains command switches parsed from the command line. * Contains command switches parsed from the command line.
* *
* @var array * @var array
* @access public
*/ */
var $params = array(); public $params = array();
/**
/**
* Contains arguments parsed from the command line. * Contains arguments parsed from the command line.
* *
* @var array * @var array
* @access public
*/ */
var $args = array(); public $args = array();
/**
/**
* The file name of the shell that was invoked. * The file name of the shell that was invoked.
* *
* @var string * @var string
* @access public
*/ */
var $shell = null; public $shell = null;
/**
/**
* The class name of the shell that was invoked. * The class name of the shell that was invoked.
* *
* @var string * @var string
* @access public
*/ */
var $shellClass = null; public $shellClass = null;
/**
/**
* The command called if public methods are available. * The command called if public methods are available.
* *
* @var string * @var string
* @access public
*/ */
var $shellCommand = null; public $shellCommand = null;
/**
/**
* The name of the shell in camelized. * The name of the shell in camelized.
* *
* @var string * @var string
* @access public
*/ */
var $shellName = null; public $shellName = null;
/**
/**
* Constructor * Constructor
* *
* @param array $args the argv. * @param array $args the argv.
*/ */
function __construct($args = array()) { public function __construct($args = array()) {
set_time_limit(0); set_time_limit(0);
$this->__initConstants(); $this->__initConstants();
$this->parseParams($args); $this->parseParams($args);
$this->__initEnvironment(); $this->__initEnvironment();
/*$this->dispatch();
die("\n");*/
} }
/**
/**
* Defines core configuration. * Defines core configuration.
*
* @access private
*/ */
function __initConstants() { private function __initConstants() {
if (function_exists('ini_set')) {
ini_set('display_errors', '1'); ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL); ini_set('error_reporting', E_ALL);
ini_set('html_errors', false); ini_set('html_errors', false);
ini_set('implicit_flush', true); ini_set('implicit_flush', true);
ini_set('max_execution_time', 0); ini_set('max_execution_time', 0);
}
define('DS', DIRECTORY_SEPARATOR); define('DS', DIRECTORY_SEPARATOR);
define('CORE_INCLUDE_PATH', dirname(__FILE__)); define('CORE_INCLUDE_PATH', dirname(__FILE__));
@ -138,15 +132,12 @@ class PostfixAdmin {
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 define('POSTFIXADMIN', 1); # checked in included files
} }
} }
/**
/**
* Defines current working environment. * Defines current working environment.
*
* @access private
*/ */
function __initEnvironment() { private function __initEnvironment() {
$this->stdin = fopen('php://stdin', 'r'); $this->stdin = fopen('php://stdin', 'r');
$this->stdout = fopen('php://stdout', 'w'); $this->stdout = fopen('php://stdout', 'w');
$this->stderr = fopen('php://stderr', 'w'); $this->stderr = fopen('php://stderr', 'w');
@ -155,54 +146,48 @@ class PostfixAdmin {
$this->stderr(""); $this->stderr("");
$this->stderr("Unable to load."); $this->stderr("Unable to load.");
$this->stderr("\tMake sure /config.inc.php exists in " . PATH); $this->stderr("\tMake sure /config.inc.php exists in " . PATH);
exit(); exit(1);
} }
if (basename(__FILE__) != basename($this->args[0])) { if (basename(__FILE__) != basename($this->args[0])) {
$this->stderr('Warning: the dispatcher may have been loaded incorrectly, which could lead to unexpected results...'); $this->stderr('Warning: the dispatcher may have been loaded incorrectly, which could lead to unexpected results...');
if ($this->getInput('Continue anyway?', array('y', 'n'), 'y') == 'n') { if ($this->getInput('Continue anyway?', array('y', 'n'), 'y') == 'n') {
exit(); exit(1);
} }
} }
$this->shiftArgs(); $this->shiftArgs();
} }
/**
/**
* Initializes the environment and loads the Cake core. * Initializes the environment and loads the Cake core.
* *
* @return boolean Success. * @return boolean Success.
* @access private
*/ */
function __bootstrap() { private function __bootstrap() {
if ($this->params['webroot'] != '' ) { if ($this->params['webroot'] != '' ) {
define('PATH', $this->params['webroot'] ); define('PATH', $this->params['webroot'] );
} else { } else {
define('PATH', CORE_PATH); define('PATH', CORE_PATH);
} }
if (!file_exists(PATH)) { if (!file_exists(PATH)) {
$this->stderr( PATH . " don't exists"); $this->stderr( PATH . " don't exists");
return false; return false;
} }
if (!require_once(PATH . '/common.php')) { if (!require_once(PATH . '/common.php')) {
$this->stderr("Failed to load " . PATH . '/common.php'); $this->stderr("Failed to load " . PATH . '/common.php');
return false; return false;
} }
return true; return true;
} }
/** /**
* Dispatches a CLI request * Dispatches a CLI request
*
* @access public
*/ */
function dispatch() { public function dispatch() {
$CONF = Config::read('all'); $CONF = Config::read('all');
if (!isset($this->args[0])) { if (!isset($this->args[0])) {
@ -220,7 +205,7 @@ class PostfixAdmin {
$this->help(); $this->help();
return; return;
} }
# TODO: move shells/shell.php to model/ to enable autoloading # TODO: move shells/shell.php to model/ to enable autoloading
if (!class_exists('Shell')) { if (!class_exists('Shell')) {
require CORE_INCLUDE_PATH . DS . "shells" . DS . 'shell.php'; require CORE_INCLUDE_PATH . DS . "shells" . DS . 'shell.php';
} }
@ -257,7 +242,7 @@ class PostfixAdmin {
$shell->new = 1; $shell->new = 1;
} }
# TODO: add a way to Cli* to signal if the selected handler is supported (for example, not all *Handler support changing the password) # TODO: add a way to Cli* to signal if the selected handler is supported (for example, not all *Handler support changing the password)
if (strtolower(get_parent_class($shell)) == 'shell') { if (strtolower(get_parent_class($shell)) == 'shell') {
$shell->initialize(); $shell->initialize();
@ -267,7 +252,6 @@ class PostfixAdmin {
$this->shiftArgs(); $this->shiftArgs();
$shell->startup(); $shell->startup();
if (isset($this->args[0]) && $this->args[0] == 'help') { if (isset($this->args[0]) && $this->args[0] == 'help') {
if (method_exists($shell, 'help')) { if (method_exists($shell, 'help')) {
$shell->help(); $shell->help();
@ -317,16 +301,15 @@ class PostfixAdmin {
} }
} }
/** /**
* Prompts the user for input, and returns it. * Prompts the user for input, and returns it.
* *
* @param string $prompt Prompt text. * @param string $prompt Prompt text.
* @param mixed $options Array or string of options. * @param mixed $options Array or string of options.
* @param string $default Default input value. * @param string $default Default input value.
* @return Either the default value, or the user-provided input. * @return Either the default value, or the user-provided input.
* @access public
*/ */
function getInput($prompt, $options = null, $default = null) { public function getInput($prompt, $options = null, $default = null) {
if (!is_array($options)) { if (!is_array($options)) {
$print_options = ''; $print_options = '';
} else { } else {
@ -341,7 +324,7 @@ class PostfixAdmin {
$result = fgets($this->stdin); $result = fgets($this->stdin);
if ($result === false){ if ($result === false){
exit; exit(1);
} }
$result = trim($result); $result = trim($result);
@ -350,37 +333,36 @@ class PostfixAdmin {
} }
return $result; return $result;
} }
/**
/**
* Outputs to the stdout filehandle. * Outputs to the stdout filehandle.
* *
* @param string $string String to output. * @param string $string String to output.
* @param boolean $newline If true, the outputs gets an added newline. * @param boolean $newline If true, the outputs gets an added newline.
* @access public
*/ */
function stdout($string, $newline = true) { public function stdout($string, $newline = true) {
if ($newline) { if ($newline) {
fwrite($this->stdout, $string . "\n"); fwrite($this->stdout, $string . "\n");
} else { } else {
fwrite($this->stdout, $string); fwrite($this->stdout, $string);
} }
} }
/**
/**
* Outputs to the stderr filehandle. * Outputs to the stderr filehandle.
* *
* @param string $string Error text to output. * @param string $string Error text to output.
* @access public
*/ */
function stderr($string) { public function stderr($string) {
fwrite($this->stderr, 'Error: '. $string . "\n"); fwrite($this->stderr, 'Error: '. $string . "\n");
} }
/** /**
* Parses command line options * Parses command line options
* *
* @param array $params Parameters to parse * @param array $params Parameters to parse
* @access public
*/ */
function parseParams($params) { public function parseParams($params) {
$this->__parseParams($params); $this->__parseParams($params);
$defaults = array('webroot' => CORE_PATH); $defaults = array('webroot' => CORE_PATH);
@ -398,13 +380,13 @@ class PostfixAdmin {
$this->params = array_merge($this->params, $params); $this->params = array_merge($this->params, $params);
} }
/**
/**
* Helper for recursively paraing params * Helper for recursively paraing params
* *
* @return array params * @return array params
* @access private
*/ */
function __parseParams($params) { private function __parseParams($params) {
$count = count($params); $count = count($params);
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
if (isset($params[$i])) { if (isset($params[$i])) {
@ -426,17 +408,16 @@ class PostfixAdmin {
$this->args[] = $params[$i]; $this->args[] = $params[$i];
unset($params[$i]); unset($params[$i]);
} }
}
}
}
} /**
}
}
/**
* Removes first argument and shifts other arguments up * Removes first argument and shifts other arguments up
* *
* @return boolean False if there are no arguments * @return boolean False if there are no arguments
* @access public
*/ */
function shiftArgs() { public function shiftArgs() {
if (empty($this->args)) { if (empty($this->args)) {
return false; return false;
} }
@ -445,19 +426,12 @@ class PostfixAdmin {
return true; return true;
} }
function help() { /**
* prints help message and exits.
*/
public function help() {
$this->stdout("\nWelcome to Postfixadmin-CLI v" . $this->version); $this->stdout("\nWelcome to Postfixadmin-CLI v" . $this->version);
$this->stdout("---------------------------------------------------------------"); $this->stdout("---------------------------------------------------------------");
/* users shouldn't need to specify -webroot - therefore let's "hide" it ;-)
$this->stdout("Options:");
$this->stdout(" -webroot: " . $this->params['webroot']);
$this->stdout("");
$this->stdout("Changing Paths:");
$this->stdout("your webroot should be the same as your postfixadmin path");
$this->stdout("to change your path use the '-webroot' param.");
$this->stdout("Example: -webroot r/absolute/path/to/postfixadmin");
*/
$this->stdout("Usage:"); $this->stdout("Usage:");
$this->stdout(" postfixadmin-cli <module> <task> [--option value --option2 value]"); $this->stdout(" postfixadmin-cli <module> <task> [--option value --option2 value]");
$this->stdout(""); $this->stdout("");
@ -486,57 +460,9 @@ class PostfixAdmin {
$this->stdout(" print a list of available options."); $this->stdout(" print a list of available options.");
$this->stdout(""); $this->stdout("");
/*
$this->stdout("\nAvailable Commands:");
foreach ($this->commands() AS $command => $desc) {
if (is_array($desc)) {
$this->stdout($command . ":");
foreach($desc AS $command2 => $desc2) {
$this->stdout(sprintf("%-20s %s", " ".$command2 .": ", $desc2));
}
$this->stdout("");
} else {
$this->stdout(sprintf("%-20s %s", $command .": ", $desc));
}
}
$this->stdout("\nTo run a command, type 'postfixadmin-cli command [args]'");
$this->stdout("To get help on a specific command, type 'postfixadmin-cli command help'");
*/
exit(); exit();
} }
/**
* Removes first argument and shifts other arguments up
*
* @return array List of commands
* @access public
*/
/* currently unused (and outdated)
function commands() {
# TODO: this list is incomplete
return array(
'mailbox' => array(
'add'=> 'Adds a new mailbox.',
'update'=> 'Updates a mailbox.',
'delete' => 'Deletes a mailbox.',
'pw' => 'Changes the PW for a mailbox.',
),
'alias' => array(
'add' => 'Adds a new alias.',
'update' => 'Updates a alias.',
'delete' => 'Deletes a alias.',
),
);
}
*/
} }
@ -549,4 +475,3 @@ $CONF = Config::read('all');
$dispatcher->dispatch(); $dispatcher->dispatch();
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */ /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
?>

View File

@ -2,7 +2,7 @@
class PasswordTask extends Shell { class PasswordTask extends Shell {
/** /**
* Execution method always used for tasks * Execution method always used for tasks
* *
* @access public * @access public
@ -32,22 +32,20 @@ class PasswordTask extends Shell {
} }
} }
/**
* Interactive
*
* @access private
*/
function __interactive() {
while(0==0) { /**
* Interactive
*/
private function __interactive() {
while(true) {
$question = "Which address' password do you want to change?"; $question = "Which address' password do you want to change?";
$address = $this->in($question); $address = $this->in($question);
if(preg_match("/^((?:(?:(?:[a-zA-Z0-9][\.\-\+_]?)*)[a-zA-Z0-9])+)\@((?:(?:(?:[a-zA-Z0-9][\.\-_]?){0,62})[a-zA-Z0-9])+)\.([a-zA-Z0-9]{2,6})$/", $address) == 1) if(filter_var($address, FILTER_VALIDATE_EMAIL)) {
break; break;
}
$this->err("Invalid emailaddress"); $this->err("Invalid emailaddress");
} }
@ -75,16 +73,14 @@ class PasswordTask extends Shell {
$this->__handle($address, $password, $random); $this->__handle($address, $password, $random);
} }
/** /**
* Interactive * @param string $address email adress
* * @param string $password optional
* @access private * @param boolean $random optional - true to generate random pw.
*/ */
function __handle($address, $password = NULL, $random = false) { private function __handle($address, $password = NULL, $random = false) {
if ($random == true) { if ($random == true) {
$password = generate_password(); $password = generate_password();
@ -110,12 +106,13 @@ class PasswordTask extends Shell {
return ; return ;
} }
/**
/**
* Displays help contents * Displays help contents
* *
* @access public * @access public
*/ */
function help() { public function help() {
$this->out(""); $this->out("");
$this->hr(); $this->hr();
$this->out("Usage: postfixadmin-cli mailbox password <address> [<newpw>] [-g]"); $this->out("Usage: postfixadmin-cli mailbox password <address> [<newpw>] [-g]");
@ -126,5 +123,4 @@ class PasswordTask extends Shell {
$this->out(""); $this->out("");
$this->_stop(); $this->_stop();
} }
} }

View File

@ -30,56 +30,56 @@
*/ */
class Shell { class Shell {
/** /**
* An instance of the ShellDispatcher object that loaded this script * An instance of the ShellDispatcher object that loaded this script
* *
* @var object * @var object
* @access public * @access public
*/ */
var $Dispatch = null; var $Dispatch = null;
/** /**
* If true, the script will ask for permission to perform actions. * If true, the script will ask for permission to perform actions.
* *
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $interactive = true; var $interactive = true;
/** /**
* Contains command switches parsed from the command line. * Contains command switches parsed from the command line.
* *
* @var array * @var array
* @access public * @access public
*/ */
var $params = array(); var $params = array();
/** /**
* Contains arguments parsed from the command line. * Contains arguments parsed from the command line.
* *
* @var array * @var array
* @access public * @access public
*/ */
var $args = array(); var $args = array();
/** /**
* The file name of the shell that was invoked. * The file name of the shell that was invoked.
* *
* @var string * @var string
* @access public * @access public
*/ */
var $shell = null; var $shell = null;
/** /**
* The class name of the shell that was invoked. * The class name of the shell that was invoked.
* *
* @var string * @var string
* @access public * @access public
*/ */
var $className = null; var $className = null;
/** /**
* The command called if public methods are available. * The command called if public methods are available.
* *
* @var string * @var string
* @access public * @access public
*/ */
var $command = null; var $command = null;
/** /**
* The name of the shell in camelized. * The name of the shell in camelized.
* *
* @var string * @var string
@ -87,7 +87,7 @@ class Shell {
*/ */
var $name = null; var $name = null;
/** /**
* Constructs this Shell instance. * Constructs this Shell instance.
* *
*/ */
@ -110,7 +110,7 @@ class Shell {
$this->Dispatch =& $dispatch; $this->Dispatch =& $dispatch;
} }
/** /**
* Initializes the Shell * Initializes the Shell
* acts as constructor for subclasses * acts as constructor for subclasses
* allows configuration of tasks prior to shell execution * allows configuration of tasks prior to shell execution
@ -119,7 +119,7 @@ class Shell {
*/ */
function initialize() { function initialize() {
} }
/** /**
* Starts up the the Shell * Starts up the the Shell
* allows for checking and configuring prior to command or main execution * allows for checking and configuring prior to command or main execution
* can be overriden in subclasses * can be overriden in subclasses
@ -127,13 +127,13 @@ class Shell {
* @access public * @access public
*/ */
function startup() { function startup() {
#CHECK! #CHECK!
if ( empty($this->params['q'] ) ) { if ( empty($this->params['q'] ) ) {
$this->_welcome(); $this->_welcome();
} }
$CONF = Config::read('all'); $CONF = Config::read('all');
} }
/** /**
* Displays a header for the shell * Displays a header for the shell
* *
* @access protected * @access protected
@ -143,7 +143,7 @@ if ( empty($this->params['q'] ) ) {
$this->hr(); $this->hr();
} }
/** /**
* Prompts the user for input, and returns it. * Prompts the user for input, and returns it.
* *
* @param string $prompt Prompt text. * @param string $prompt Prompt text.
@ -177,7 +177,7 @@ if ( empty($this->params['q'] ) ) {
return $in; return $in;
} }
/** /**
* Outputs to the stdout filehandle. * Outputs to the stdout filehandle.
* *
* @param string $string String to output. * @param string $string String to output.
@ -194,7 +194,7 @@ if ( empty($this->params['q'] ) ) {
} }
return $this->Dispatch->stdout($string, $newline); return $this->Dispatch->stdout($string, $newline);
} }
/** /**
* Outputs to the stderr filehandle. * Outputs to the stderr filehandle.
* *
* @param string $string Error text to output. * @param string $string Error text to output.
@ -210,7 +210,7 @@ if ( empty($this->params['q'] ) ) {
} }
return $this->Dispatch->stderr($string."\n"); return $this->Dispatch->stderr($string."\n");
} }
/** /**
* Outputs a series of minus characters to the standard output, acts as a visual separator. * Outputs a series of minus characters to the standard output, acts as a visual separator.
* *
* @param boolean $newline If true, the outputs gets an added newline. * @param boolean $newline If true, the outputs gets an added newline.
@ -225,7 +225,7 @@ if ( empty($this->params['q'] ) ) {
$this->out("\n"); $this->out("\n");
} }
} }
/** /**
* Displays a formatted error message and exits the application * Displays a formatted error message and exits the application
* *
* @param string $title Title of the error message * @param string $title Title of the error message
@ -264,4 +264,4 @@ if ( empty($this->params['q'] ) ) {
} }