PostfixAdmin - web based virtual user administration interface for Postfix mail servers https://postfixadmin.github.io/postfixadmin/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

419 lines
12 KiB

8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
6 years ago
8 years ago
6 years ago
  1. #!/usr/bin/php
  2. <?php
  3. /**
  4. * Command-line code generation utility to automate administrator tasks.
  5. *
  6. * Shell dispatcher class
  7. *
  8. * PHP versions 4 and 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework <http://www.cakephp.org/>
  11. * Copyright 2005-2008, Cake Software Foundation, Inc.
  12. * 1785 E. Sahara Avenue, Suite 490-204
  13. * Las Vegas, Nevada 89104
  14. * Modified for PostfixAdmin by Valkum 2011
  15. * Modified for PostfixAdmin by Christian Boltz 2011-2013
  16. *
  17. * Copyright 2010
  18. *
  19. * Licensed under The MIT License
  20. * Redistributions of files must retain the above copyright notice.
  21. *
  22. * @filesource
  23. * @copyright Copyright 2005-2008, Cake Software Foundation, Inc.
  24. * @link http://postfixadmin.sourceforge.net/ Postfixadmin on Sourceforge
  25. * @package postfixadmin
  26. * @subpackage -
  27. * @since -
  28. * @version $Revision$
  29. * @modifiedby $LastChangedBy$
  30. * @lastmodified $Date$
  31. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  32. */
  33. class PostfixAdmin
  34. {
  35. /**
  36. * Version
  37. *
  38. * @var string
  39. */
  40. public $version = '0.3';
  41. /**
  42. * Standard input stream.
  43. *
  44. * @var resource
  45. */
  46. public $stdin;
  47. /**
  48. * Standard output stream.
  49. *
  50. * @var resource
  51. */
  52. public $stdout;
  53. /**
  54. * Standard error stream.
  55. *
  56. * @var resource
  57. */
  58. public $stderr;
  59. /**
  60. * Contains command switches parsed from the command line.
  61. *
  62. * @var array
  63. */
  64. public $params = array();
  65. /**
  66. * Contains arguments parsed from the command line.
  67. *
  68. * @var array
  69. */
  70. public $args = array();
  71. /**
  72. * The file name of the shell that was invoked.
  73. *
  74. * @var string
  75. */
  76. public $shell;
  77. /**
  78. * The class name of the shell that was invoked.
  79. *
  80. * @var string
  81. */
  82. public $shellClass;
  83. /**
  84. * The command called if public methods are available.
  85. *
  86. * @var string
  87. */
  88. public $shellCommand;
  89. /**
  90. * The name of the shell in camelized.
  91. *
  92. * @var string
  93. */
  94. public $shellName;
  95. /**
  96. * Constructor
  97. *
  98. * @param array $args the argv.
  99. */
  100. public function __construct($args = array())
  101. {
  102. set_time_limit(0);
  103. $this->__initConstants();
  104. $this->parseParams($args);
  105. $this->__initEnvironment();
  106. }
  107. /**
  108. * Defines core configuration.
  109. */
  110. private function __initConstants()
  111. {
  112. ini_set('display_errors', '1');
  113. $error_reporting_orig = error_reporting();
  114. error_reporting($error_reporting_orig | E_ERROR | E_WARNING | E_PARSE);
  115. ini_set('html_errors', "0");
  116. ini_set('implicit_flush', "1");
  117. ini_set('max_execution_time', "0");
  118. }
  119. /**
  120. * Defines current working environment.
  121. */
  122. private function __initEnvironment()
  123. {
  124. $this->stdin = fopen('php://stdin', 'r');
  125. $this->stdout = fopen('php://stdout', 'w');
  126. $this->stderr = fopen('php://stderr', 'w');
  127. if (basename(__FILE__) != basename($this->args[0])) {
  128. $this->stderr('Warning: the dispatcher may have been loaded incorrectly, which could lead to unexpected results...');
  129. if ($this->getInput('Continue anyway?', array('y', 'n'), 'y') == 'n') {
  130. exit(1);
  131. }
  132. }
  133. $this->shiftArgs();
  134. }
  135. /**
  136. * postfixadmin-cli admin view admin@example.com
  137. * - Create AdminHandler.
  138. * - and then a CliView object (Shell class)
  139. * - call CliView->view() ... which under the covers uses AdminHandler*
  140. */
  141. public function dispatch()
  142. {
  143. check_db_version(); # ensure the database layout is up to date
  144. if (!isset($this->args[0])) {
  145. $this->help();
  146. return 1;
  147. }
  148. $this->shell = $this->args[0];
  149. $this->shiftArgs();
  150. $this->shellName = ucfirst($this->shell);
  151. $this->shellClass = $this->shellName . 'Handler';
  152. if ($this->shell == 'help') {
  153. $this->help();
  154. return 1;
  155. }
  156. $command = $this->args[0];
  157. $this->shellCommand = $command;
  158. $this->shellClass = 'Cli' . ucfirst($command);
  159. if (ucfirst($command) == 'Add' || ucfirst($command) == 'Update') {
  160. $this->shellClass = 'CliEdit';
  161. }
  162. if (!class_exists($this->shellClass)) {
  163. $this->stderr('Unknown task ' . $this->shellCommand);
  164. return 1;
  165. }
  166. $shell = new $this->shellClass($this);
  167. $shell->handler_to_use = ucfirst($this->shell) . 'Handler';
  168. if (!class_exists($shell->handler_to_use)) {
  169. $this->stderr('Unknown module ' . $this->shell);
  170. return 1;
  171. }
  172. $task = ucfirst($command);
  173. $shell->new = 0;
  174. if ($task == 'Add') {
  175. $shell->new = 1;
  176. }
  177. # TODO: add a way to Cli* to signal if the selected handler is supported (for example, not all *Handler support changing the password)
  178. if (strtolower(get_parent_class($shell)) == 'shell') {
  179. $handler = new $shell->handler_to_use();
  180. if (in_array($task, $handler->taskNames)) {
  181. $this->shiftArgs();
  182. $shell->startup();
  183. if (isset($this->args[0]) && $this->args[0] == 'help') {
  184. if (method_exists($shell, 'help')) {
  185. $shell->help();
  186. return 1;
  187. } else {
  188. $this->help();
  189. return 1;
  190. }
  191. }
  192. return $shell->execute();
  193. }
  194. }
  195. $classMethods = get_class_methods($shell);
  196. $privateMethod = $missingCommand = false;
  197. if ((in_array($command, $classMethods) || in_array(strtolower($command), $classMethods)) && strpos($command, '_', 0) === 0) {
  198. $privateMethod = true;
  199. }
  200. if (!in_array($command, $classMethods) && !in_array(strtolower($command), $classMethods)) {
  201. $missingCommand = true;
  202. }
  203. $protectedCommands = array(
  204. 'in', 'out', 'err', 'hr', 'log',
  205. '__construct', 'dispatch', 'stdout', 'stderr'
  206. );
  207. if (in_array(strtolower($command), $protectedCommands)) {
  208. $missingCommand = true;
  209. }
  210. if ($missingCommand && method_exists($shell, 'main')) {
  211. $shell->startup();
  212. return $shell->main();
  213. } elseif (!$privateMethod && method_exists($shell, $command)) {
  214. $this->shiftArgs();
  215. $shell->startup();
  216. return $shell->{$command}();
  217. } else {
  218. $this->stderr("Unknown {$this->shellName} command '$command'.\nFor usage, try 'postfixadmin-cli {$this->shell} help'.\n\n");
  219. return 1;
  220. }
  221. }
  222. /**
  223. * Prompts the user for input, and returns it.
  224. *
  225. * @param string $prompt Prompt text.
  226. * @param mixed $options Array or string of options.
  227. * @param string $default Default input value.
  228. * @return string Either the default value, or the user-provided input.
  229. */
  230. public function getInput($prompt, $options = null, $default = null)
  231. {
  232. if (!is_array($options)) {
  233. $print_options = '';
  234. } else {
  235. $print_options = '(' . implode('/', $options) . ')';
  236. }
  237. if ($default == null) {
  238. $this->stdout($prompt . " $print_options \n" . '> ', false);
  239. } else {
  240. $this->stdout($prompt . " $print_options \n" . "[$default] > ", false);
  241. }
  242. $result = fgets($this->stdin);
  243. if ($result === false) {
  244. exit(1);
  245. }
  246. $result = trim($result);
  247. if ($default != null && empty($result)) {
  248. return $default;
  249. }
  250. return $result;
  251. }
  252. /**
  253. * Outputs to the stdout filehandle.
  254. *
  255. * @param string $string String to output.
  256. * @param boolean $newline If true, the outputs gets an added newline.
  257. */
  258. public function stdout($string, $newline = true)
  259. {
  260. if ($newline) {
  261. fwrite($this->stdout, $string . "\n");
  262. } else {
  263. fwrite($this->stdout, $string);
  264. }
  265. }
  266. /**
  267. * Outputs to the stderr filehandle.
  268. *
  269. * @param string $string Error text to output.
  270. */
  271. public function stderr($string)
  272. {
  273. fwrite($this->stderr, 'Error: '. $string . "\n");
  274. }
  275. /**
  276. * Parses command line options
  277. *
  278. * @param array $params Parameters to parse
  279. */
  280. public function parseParams($params)
  281. {
  282. $count = count($params);
  283. for ($i = 0; $i < $count; $i++) {
  284. if ($params[$i] != '' && $params[$i][0] === '-' && $params[$i] != '-1') {
  285. $key = substr($params[$i], 1);
  286. if (isset($params[$i + 1])) {
  287. # TODO: ideally we should know if a parameter can / must have a value instead of whitelisting known valid values starting with '-' (probably only bool doesn't need a value)
  288. if ($params[$i + 1][0] === '-' && $params[$i + 1] != '-1') {
  289. $this->params[$key] = true;
  290. } else {
  291. $this->params[$key] = $params[$i + 1];
  292. $i++;
  293. }
  294. }
  295. } else {
  296. $this->args[] = $params[$i];
  297. }
  298. }
  299. }
  300. /**
  301. * Removes first argument and shifts other arguments up
  302. *
  303. * @return boolean False if there are no arguments
  304. */
  305. public function shiftArgs()
  306. {
  307. if (empty($this->args)) {
  308. return false;
  309. }
  310. unset($this->args[0]);
  311. $this->args = array_values($this->args);
  312. return true;
  313. }
  314. /**
  315. * prints help message and exits.
  316. */
  317. public function help()
  318. {
  319. $this->stdout("\nWelcome to Postfixadmin-CLI v" . $this->version);
  320. $this->stdout("---------------------------------------------------------------");
  321. $this->stdout("Usage:");
  322. $this->stdout(" postfixadmin-cli <module> <task> [--option value --option2 value]");
  323. $this->stdout("");
  324. $this->stdout("Available modules:");
  325. $modules = explode(',', 'admin,domain,mailbox,alias,aliasdomain,fetchmail');
  326. foreach ($modules as $module) {
  327. $this->stdout(" $module");
  328. }
  329. $this->stdout("");
  330. $this->stdout("Most modules support the following tasks:");
  331. $this->stdout(" view View an item");
  332. $this->stdout(" add Add an item");
  333. $this->stdout(" update Update an item");
  334. $this->stdout(" delete Delete an item");
  335. $this->stdout(" scheme Print database scheme (useful for developers only)");
  336. $this->stdout(" help Print help output");
  337. $this->stdout("");
  338. $this->stdout("");
  339. $this->stdout("For module-specific help, see:");
  340. $this->stdout("");
  341. $this->stdout(" postfixadmin-cli <module> help");
  342. $this->stdout(" print a detailed list of available commands");
  343. $this->stdout("");
  344. $this->stdout(" postfixadmin-cli <module> <task> help");
  345. $this->stdout(" print a list of available options.");
  346. $this->stdout("");
  347. exit();
  348. }
  349. }
  350. define("POSTFIXADMIN_CLI", 1);
  351. require_once(dirname(__FILE__) . '/../common.php');
  352. $dispatcher = new PostfixAdmin($argv);
  353. try {
  354. $retval = $dispatcher->dispatch();
  355. } catch (Exception $e) {
  356. $dispatcher->stderr("Execution Exception: " . $e->getMessage());
  357. $retval = 1;
  358. }
  359. exit($retval ?? 0);
  360. /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */