postfixadmin-cli.php 12 KB

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