postfixadmin-cli.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. * @access protected
  39. */
  40. var $version ='0.2';
  41. /**
  42. * Standard input stream.
  43. *
  44. * @var filehandle
  45. * @access public
  46. */
  47. var $stdin;
  48. /**
  49. * Standard output stream.
  50. *
  51. * @var filehandle
  52. * @access public
  53. */
  54. var $stdout;
  55. /**
  56. * Standard error stream.
  57. *
  58. * @var filehandle
  59. * @access public
  60. */
  61. var $stderr;
  62. /**
  63. * Contains command switches parsed from the command line.
  64. *
  65. * @var array
  66. * @access public
  67. */
  68. var $params = array();
  69. /**
  70. * Contains arguments parsed from the command line.
  71. *
  72. * @var array
  73. * @access public
  74. */
  75. var $args = array();
  76. /**
  77. * The file name of the shell that was invoked.
  78. *
  79. * @var string
  80. * @access public
  81. */
  82. var $shell = null;
  83. /**
  84. * The class name of the shell that was invoked.
  85. *
  86. * @var string
  87. * @access public
  88. */
  89. var $shellClass = null;
  90. /**
  91. * The command called if public methods are available.
  92. *
  93. * @var string
  94. * @access public
  95. */
  96. var $shellCommand = null;
  97. /**
  98. * The name of the shell in camelized.
  99. *
  100. * @var string
  101. * @access public
  102. */
  103. var $shellName = null;
  104. /**
  105. * Constructor
  106. *
  107. * @param array $args the argv.
  108. */
  109. function __construct($args = array()) {
  110. set_time_limit(0);
  111. $this->__initConstants();
  112. $this->parseParams($args);
  113. $this->__initEnvironment();
  114. /*$this->dispatch();
  115. die("\n");*/
  116. }
  117. /**
  118. * Defines core configuration.
  119. *
  120. * @access private
  121. */
  122. function __initConstants() {
  123. if (function_exists('ini_set')) {
  124. ini_set('display_errors', '1');
  125. ini_set('error_reporting', E_ALL);
  126. ini_set('html_errors', false);
  127. ini_set('implicit_flush', true);
  128. ini_set('max_execution_time', 0);
  129. }
  130. define('DS', DIRECTORY_SEPARATOR);
  131. define('CORE_INCLUDE_PATH', dirname(__FILE__));
  132. define('CORE_PATH', dirname(CORE_INCLUDE_PATH) ); # CORE_INCLUDE_PATH/../
  133. if(!defined('POSTFIXADMIN')) { # already defined if called from setup.php
  134. define('POSTFIXADMIN', 1); # checked in included files
  135. }
  136. }
  137. /**
  138. * Defines current working environment.
  139. *
  140. * @access private
  141. */
  142. function __initEnvironment() {
  143. $this->stdin = fopen('php://stdin', 'r');
  144. $this->stdout = fopen('php://stdout', 'w');
  145. $this->stderr = fopen('php://stderr', 'w');
  146. if (!$this->__bootstrap()) {
  147. $this->stderr("");
  148. $this->stderr("Unable to load.");
  149. $this->stderr("\tMake sure /config.inc.php exists in " . PATH);
  150. exit();
  151. }
  152. if (basename(__FILE__) != basename($this->args[0])) {
  153. $this->stderr('Warning: the dispatcher may have been loaded incorrectly, which could lead to unexpected results...');
  154. if ($this->getInput('Continue anyway?', array('y', 'n'), 'y') == 'n') {
  155. exit();
  156. }
  157. }
  158. $this->shiftArgs();
  159. }
  160. /**
  161. * Initializes the environment and loads the Cake core.
  162. *
  163. * @return boolean Success.
  164. * @access private
  165. */
  166. function __bootstrap() {
  167. if ($this->params['webroot'] != '' ) {
  168. define('PATH', $this->params['webroot'] );
  169. } else {
  170. define('PATH', CORE_PATH);
  171. }
  172. if (!file_exists(PATH)) {
  173. $this->stderr( PATH . " don't exists");
  174. return false;
  175. }
  176. if (!require_once(PATH . '/common.php')) {
  177. $this->stderr("Failed to load " . PATH . '/common.php');
  178. return false;
  179. }
  180. return true;
  181. }
  182. /**
  183. * Dispatches a CLI request
  184. *
  185. * @access public
  186. */
  187. function dispatch() {
  188. $CONF = Config::read('all');
  189. if (!isset($this->args[0])) {
  190. $this->help();
  191. return;
  192. }
  193. $this->shell = $this->args[0];
  194. $this->shiftArgs();
  195. $this->shellName = ucfirst($this->shell);
  196. $this->shellClass = $this->shellName . 'Handler';
  197. if ($this->shell == 'help') {
  198. $this->help();
  199. return;
  200. }
  201. # TODO: move shells/shell.php to model/ to enable autoloading
  202. if (!class_exists('Shell')) {
  203. require CORE_INCLUDE_PATH . DS . "shells" . DS . 'shell.php';
  204. }
  205. $command = 'help'; # not the worst default ;-)
  206. if (isset($this->args[0])) {
  207. $command = $this->args[0];
  208. }
  209. $this->shellCommand = $command;
  210. $this->shellClass = 'Cli' . ucfirst($command);
  211. if (ucfirst($command) == 'Add' || ucfirst($command) == 'Update') {
  212. $this->shellClass = 'CliEdit';
  213. }
  214. if (!class_exists($this->shellClass)) {
  215. $this->stderr('Unknown task ' . $this->shellCommand);
  216. return;
  217. }
  218. $shell = new $this->shellClass($this);
  219. $shell->handler_to_use = ucfirst($this->shell) . 'Handler';
  220. if (!class_exists($shell->handler_to_use)) {
  221. $this->stderr('Unknown module ' . $this->shell);
  222. return;
  223. }
  224. $task = ucfirst($command);
  225. $shell->new = 0;
  226. if ($task == 'Add') {
  227. $shell->new = 1;
  228. }
  229. # TODO: add a way to Cli* to signal if the selected handler is supported (for example, not all *Handler support changing the password)
  230. if (strtolower(get_parent_class($shell)) == 'shell') {
  231. $shell->initialize();
  232. $handler = new $shell->handler_to_use;
  233. if (in_array($task, $handler->taskNames)) {
  234. $this->shiftArgs();
  235. $shell->startup();
  236. if (isset($this->args[0]) && $this->args[0] == 'help') {
  237. if (method_exists($shell, 'help')) {
  238. $shell->help();
  239. exit();
  240. } else {
  241. $this->help();
  242. }
  243. }
  244. $shell->execute();
  245. return;
  246. }
  247. }
  248. $classMethods = get_class_methods($shell);
  249. $privateMethod = $missingCommand = false;
  250. if ((in_array($command, $classMethods) || in_array(strtolower($command), $classMethods)) && strpos($command, '_', 0) === 0) {
  251. $privateMethod = true;
  252. }
  253. if (!in_array($command, $classMethods) && !in_array(strtolower($command), $classMethods)) {
  254. $missingCommand = true;
  255. }
  256. $protectedCommands = array(
  257. 'initialize','in','out','err','hr',
  258. 'createfile', 'isdir','copydir','object','tostring',
  259. 'requestaction','log','cakeerror', 'shelldispatcher',
  260. '__initconstants','__initenvironment','__construct',
  261. 'dispatch','__bootstrap','getinput','stdout','stderr','parseparams','shiftargs'
  262. );
  263. if (in_array(strtolower($command), $protectedCommands)) {
  264. $missingCommand = true;
  265. }
  266. if ($missingCommand && method_exists($shell, 'main')) {
  267. $shell->startup();
  268. $shell->main();
  269. } elseif (!$privateMethod && method_exists($shell, $command)) {
  270. $this->shiftArgs();
  271. $shell->startup();
  272. $shell->{$command}();
  273. } else {
  274. $this->stderr("Unknown {$this->shellName} command '$command'.\nFor usage, try 'postfixadmin-cli {$this->shell} help'.\n\n");
  275. }
  276. }
  277. /**
  278. * Prompts the user for input, and returns it.
  279. *
  280. * @param string $prompt Prompt text.
  281. * @param mixed $options Array or string of options.
  282. * @param string $default Default input value.
  283. * @return Either the default value, or the user-provided input.
  284. * @access public
  285. */
  286. function getInput($prompt, $options = null, $default = null) {
  287. if (!is_array($options)) {
  288. $print_options = '';
  289. } else {
  290. $print_options = '(' . implode('/', $options) . ')';
  291. }
  292. if ($default == null) {
  293. $this->stdout($prompt . " $print_options \n" . '> ', false);
  294. } else {
  295. $this->stdout($prompt . " $print_options \n" . "[$default] > ", false);
  296. }
  297. $result = fgets($this->stdin);
  298. if ($result === false){
  299. exit;
  300. }
  301. $result = trim($result);
  302. if ($default != null && empty($result)) {
  303. return $default;
  304. }
  305. return $result;
  306. }
  307. /**
  308. * Outputs to the stdout filehandle.
  309. *
  310. * @param string $string String to output.
  311. * @param boolean $newline If true, the outputs gets an added newline.
  312. * @access public
  313. */
  314. function stdout($string, $newline = true) {
  315. if ($newline) {
  316. fwrite($this->stdout, $string . "\n");
  317. } else {
  318. fwrite($this->stdout, $string);
  319. }
  320. }
  321. /**
  322. * Outputs to the stderr filehandle.
  323. *
  324. * @param string $string Error text to output.
  325. * @access public
  326. */
  327. function stderr($string) {
  328. fwrite($this->stderr, 'Error: '. $string . "\n");
  329. }
  330. /**
  331. * Parses command line options
  332. *
  333. * @param array $params Parameters to parse
  334. * @access public
  335. */
  336. function parseParams($params) {
  337. $this->__parseParams($params);
  338. $defaults = array('webroot' => CORE_PATH);
  339. $params = array_merge($defaults, array_intersect_key($this->params, $defaults));
  340. $isWin = array_filter(array_map('strpos', $params, array('\\')));
  341. $params = str_replace('\\', '/', $params);
  342. if (!empty($matches[0]) || !empty($isWin)) {
  343. $params = str_replace('/', '\\', $params);
  344. }
  345. $this->params = array_merge($this->params, $params);
  346. }
  347. /**
  348. * Helper for recursively paraing params
  349. *
  350. * @return array params
  351. * @access private
  352. */
  353. function __parseParams($params) {
  354. $count = count($params);
  355. for ($i = 0; $i < $count; $i++) {
  356. if (isset($params[$i])) {
  357. if ($params[$i] != '' && $params[$i]{0} === '-') {
  358. $key = substr($params[$i], 1);
  359. $this->params[$key] = true;
  360. unset($params[$i]);
  361. if (isset($params[++$i])) {
  362. if ($params[$i]{0} !== '-') {
  363. $this->params[$key] = str_replace('"', '', $params[$i]);
  364. unset($params[$i]);
  365. } else {
  366. $i--;
  367. $this->__parseParams($params);
  368. }
  369. }
  370. } else {
  371. $this->args[] = $params[$i];
  372. unset($params[$i]);
  373. }
  374. }
  375. }
  376. }
  377. /**
  378. * Removes first argument and shifts other arguments up
  379. *
  380. * @return boolean False if there are no arguments
  381. * @access public
  382. */
  383. function shiftArgs() {
  384. if (empty($this->args)) {
  385. return false;
  386. }
  387. unset($this->args[0]);
  388. $this->args = array_values($this->args);
  389. return true;
  390. }
  391. function help() {
  392. $this->stdout("\nWelcome to Postfixadmin-CLI v" . $this->version);
  393. $this->stdout("---------------------------------------------------------------");
  394. /* users shouldn't need to specify -webroot - therefore let's "hide" it ;-)
  395. $this->stdout("Options:");
  396. $this->stdout(" -webroot: " . $this->params['webroot']);
  397. $this->stdout("");
  398. $this->stdout("Changing Paths:");
  399. $this->stdout("your webroot should be the same as your postfixadmin path");
  400. $this->stdout("to change your path use the '-webroot' param.");
  401. $this->stdout("Example: -webroot r/absolute/path/to/postfixadmin");
  402. */
  403. $this->stdout("Usage:");
  404. $this->stdout(" postfixadmin-cli <module> <task> [--option value --option2 value]");
  405. $this->stdout("");
  406. $this->stdout("Available modules:");
  407. $modules = explode(',','admin,domain,mailbox,alias,aliasdomain,fetchmail');
  408. foreach ($modules as $module) {
  409. $this->stdout(" $module");
  410. }
  411. $this->stdout("");
  412. $this->stdout("Most modules support the following tasks:");
  413. $this->stdout(" view View an item");
  414. $this->stdout(" add Add an item");
  415. $this->stdout(" update Update an item");
  416. $this->stdout(" delete Delete an item");
  417. $this->stdout(" scheme Print database scheme (useful for developers only)");
  418. $this->stdout(" help Print help output");
  419. $this->stdout("");
  420. $this->stdout("");
  421. $this->stdout("For module-specific help, see:");
  422. $this->stdout("");
  423. $this->stdout(" postfixadmin-cli <module> help");
  424. $this->stdout(" print a detailed list of available commands");
  425. $this->stdout("");
  426. $this->stdout(" postfixadmin-cli <module> <task> help");
  427. $this->stdout(" print a list of available options.");
  428. $this->stdout("");
  429. /*
  430. $this->stdout("\nAvailable Commands:");
  431. foreach ($this->commands() AS $command => $desc) {
  432. if (is_array($desc)) {
  433. $this->stdout($command . ":");
  434. foreach($desc AS $command2 => $desc2) {
  435. $this->stdout(sprintf("%-20s %s", " ".$command2 .": ", $desc2));
  436. }
  437. $this->stdout("");
  438. } else {
  439. $this->stdout(sprintf("%-20s %s", $command .": ", $desc));
  440. }
  441. }
  442. $this->stdout("\nTo run a command, type 'postfixadmin-cli command [args]'");
  443. $this->stdout("To get help on a specific command, type 'postfixadmin-cli command help'");
  444. */
  445. exit();
  446. }
  447. /**
  448. * Removes first argument and shifts other arguments up
  449. *
  450. * @return array List of commands
  451. * @access public
  452. */
  453. /* currently unused (and outdated)
  454. function commands() {
  455. # TODO: this list is incomplete
  456. return array(
  457. 'mailbox' => array(
  458. 'add'=> 'Adds a new mailbox.',
  459. 'update'=> 'Updates a mailbox.',
  460. 'delete' => 'Deletes a mailbox.',
  461. 'pw' => 'Changes the PW for a mailbox.',
  462. ),
  463. 'alias' => array(
  464. 'add' => 'Adds a new alias.',
  465. 'update' => 'Updates a alias.',
  466. 'delete' => 'Deletes a alias.',
  467. ),
  468. );
  469. }
  470. */
  471. }
  472. define ("POSTFIXADMIN_CLI", 1);
  473. $dispatcher = new PostfixAdmin($argv);
  474. $CONF = Config::read('all');
  475. $dispatcher->dispatch();
  476. /* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
  477. ?>