Drupal investigation

QuestionHelper.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Exception\RuntimeException;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  17. use Symfony\Component\Console\Question\Question;
  18. use Symfony\Component\Console\Question\ChoiceQuestion;
  19. /**
  20. * The QuestionHelper class provides helpers to interact with the user.
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. */
  24. class QuestionHelper extends Helper
  25. {
  26. private $inputStream;
  27. private static $shell;
  28. private static $stty;
  29. /**
  30. * Asks a question to the user.
  31. *
  32. * @param InputInterface $input An InputInterface instance
  33. * @param OutputInterface $output An OutputInterface instance
  34. * @param Question $question The question to ask
  35. *
  36. * @return mixed The user answer
  37. *
  38. * @throws RuntimeException If there is no data to read in the input stream
  39. */
  40. public function ask(InputInterface $input, OutputInterface $output, Question $question)
  41. {
  42. if ($output instanceof ConsoleOutputInterface) {
  43. $output = $output->getErrorOutput();
  44. }
  45. if (!$input->isInteractive()) {
  46. return $question->getDefault();
  47. }
  48. if (!$question->getValidator()) {
  49. return $this->doAsk($output, $question);
  50. }
  51. $that = $this;
  52. $interviewer = function () use ($output, $question, $that) {
  53. return $that->doAsk($output, $question);
  54. };
  55. return $this->validateAttempts($interviewer, $output, $question);
  56. }
  57. /**
  58. * Sets the input stream to read from when interacting with the user.
  59. *
  60. * This is mainly useful for testing purpose.
  61. *
  62. * @param resource $stream The input stream
  63. *
  64. * @throws InvalidArgumentException In case the stream is not a resource
  65. */
  66. public function setInputStream($stream)
  67. {
  68. if (!is_resource($stream)) {
  69. throw new InvalidArgumentException('Input stream must be a valid resource.');
  70. }
  71. $this->inputStream = $stream;
  72. }
  73. /**
  74. * Returns the helper's input stream.
  75. *
  76. * @return resource
  77. */
  78. public function getInputStream()
  79. {
  80. return $this->inputStream;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function getName()
  86. {
  87. return 'question';
  88. }
  89. /**
  90. * Asks the question to the user.
  91. *
  92. * This method is public for PHP 5.3 compatibility, it should be private.
  93. *
  94. * @param OutputInterface $output
  95. * @param Question $question
  96. *
  97. * @return bool|mixed|null|string
  98. *
  99. * @throws \Exception
  100. * @throws \RuntimeException
  101. */
  102. public function doAsk(OutputInterface $output, Question $question)
  103. {
  104. $this->writePrompt($output, $question);
  105. $inputStream = $this->inputStream ?: STDIN;
  106. $autocomplete = $question->getAutocompleterValues();
  107. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  108. $ret = false;
  109. if ($question->isHidden()) {
  110. try {
  111. $ret = trim($this->getHiddenResponse($output, $inputStream));
  112. } catch (\RuntimeException $e) {
  113. if (!$question->isHiddenFallback()) {
  114. throw $e;
  115. }
  116. }
  117. }
  118. if (false === $ret) {
  119. $ret = fgets($inputStream, 4096);
  120. if (false === $ret) {
  121. throw new RuntimeException('Aborted');
  122. }
  123. $ret = trim($ret);
  124. }
  125. } else {
  126. $ret = trim($this->autocomplete($output, $question, $inputStream));
  127. }
  128. $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
  129. if ($normalizer = $question->getNormalizer()) {
  130. return $normalizer($ret);
  131. }
  132. return $ret;
  133. }
  134. /**
  135. * Outputs the question prompt.
  136. *
  137. * @param OutputInterface $output
  138. * @param Question $question
  139. */
  140. protected function writePrompt(OutputInterface $output, Question $question)
  141. {
  142. $message = $question->getQuestion();
  143. if ($question instanceof ChoiceQuestion) {
  144. $maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
  145. $messages = (array) $question->getQuestion();
  146. foreach ($question->getChoices() as $key => $value) {
  147. $width = $maxWidth - $this->strlen($key);
  148. $messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
  149. }
  150. $output->writeln($messages);
  151. $message = $question->getPrompt();
  152. }
  153. $output->write($message);
  154. }
  155. /**
  156. * Outputs an error message.
  157. *
  158. * @param OutputInterface $output
  159. * @param \Exception $error
  160. */
  161. protected function writeError(OutputInterface $output, \Exception $error)
  162. {
  163. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  164. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  165. } else {
  166. $message = '<error>'.$error->getMessage().'</error>';
  167. }
  168. $output->writeln($message);
  169. }
  170. /**
  171. * Autocompletes a question.
  172. *
  173. * @param OutputInterface $output
  174. * @param Question $question
  175. * @param resource $inputStream
  176. *
  177. * @return string
  178. */
  179. private function autocomplete(OutputInterface $output, Question $question, $inputStream)
  180. {
  181. $autocomplete = $question->getAutocompleterValues();
  182. $ret = '';
  183. $i = 0;
  184. $ofs = -1;
  185. $matches = $autocomplete;
  186. $numMatches = count($matches);
  187. $sttyMode = shell_exec('stty -g');
  188. // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
  189. shell_exec('stty -icanon -echo');
  190. // Add highlighted text style
  191. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  192. // Read a keypress
  193. while (!feof($inputStream)) {
  194. $c = fread($inputStream, 1);
  195. // Backspace Character
  196. if ("\177" === $c) {
  197. if (0 === $numMatches && 0 !== $i) {
  198. --$i;
  199. // Move cursor backwards
  200. $output->write("\033[1D");
  201. }
  202. if ($i === 0) {
  203. $ofs = -1;
  204. $matches = $autocomplete;
  205. $numMatches = count($matches);
  206. } else {
  207. $numMatches = 0;
  208. }
  209. // Pop the last character off the end of our string
  210. $ret = substr($ret, 0, $i);
  211. } elseif ("\033" === $c) {
  212. // Did we read an escape sequence?
  213. $c .= fread($inputStream, 2);
  214. // A = Up Arrow. B = Down Arrow
  215. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  216. if ('A' === $c[2] && -1 === $ofs) {
  217. $ofs = 0;
  218. }
  219. if (0 === $numMatches) {
  220. continue;
  221. }
  222. $ofs += ('A' === $c[2]) ? -1 : 1;
  223. $ofs = ($numMatches + $ofs) % $numMatches;
  224. }
  225. } elseif (ord($c) < 32) {
  226. if ("\t" === $c || "\n" === $c) {
  227. if ($numMatches > 0 && -1 !== $ofs) {
  228. $ret = $matches[$ofs];
  229. // Echo out remaining chars for current match
  230. $output->write(substr($ret, $i));
  231. $i = strlen($ret);
  232. }
  233. if ("\n" === $c) {
  234. $output->write($c);
  235. break;
  236. }
  237. $numMatches = 0;
  238. }
  239. continue;
  240. } else {
  241. $output->write($c);
  242. $ret .= $c;
  243. ++$i;
  244. $numMatches = 0;
  245. $ofs = 0;
  246. foreach ($autocomplete as $value) {
  247. // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
  248. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  249. $matches[$numMatches++] = $value;
  250. }
  251. }
  252. }
  253. // Erase characters from cursor to end of line
  254. $output->write("\033[K");
  255. if ($numMatches > 0 && -1 !== $ofs) {
  256. // Save cursor position
  257. $output->write("\0337");
  258. // Write highlighted text
  259. $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
  260. // Restore cursor position
  261. $output->write("\0338");
  262. }
  263. }
  264. // Reset stty so it behaves normally again
  265. shell_exec(sprintf('stty %s', $sttyMode));
  266. return $ret;
  267. }
  268. /**
  269. * Gets a hidden response from user.
  270. *
  271. * @param OutputInterface $output An Output instance
  272. * @param resource $inputStream The handler resource
  273. *
  274. * @return string The answer
  275. *
  276. * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
  277. */
  278. private function getHiddenResponse(OutputInterface $output, $inputStream)
  279. {
  280. if ('\\' === DIRECTORY_SEPARATOR) {
  281. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  282. // handle code running from a phar
  283. if ('phar:' === substr(__FILE__, 0, 5)) {
  284. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  285. copy($exe, $tmpExe);
  286. $exe = $tmpExe;
  287. }
  288. $value = rtrim(shell_exec($exe));
  289. $output->writeln('');
  290. if (isset($tmpExe)) {
  291. unlink($tmpExe);
  292. }
  293. return $value;
  294. }
  295. if ($this->hasSttyAvailable()) {
  296. $sttyMode = shell_exec('stty -g');
  297. shell_exec('stty -echo');
  298. $value = fgets($inputStream, 4096);
  299. shell_exec(sprintf('stty %s', $sttyMode));
  300. if (false === $value) {
  301. throw new RuntimeException('Aborted');
  302. }
  303. $value = trim($value);
  304. $output->writeln('');
  305. return $value;
  306. }
  307. if (false !== $shell = $this->getShell()) {
  308. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  309. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  310. $value = rtrim(shell_exec($command));
  311. $output->writeln('');
  312. return $value;
  313. }
  314. throw new RuntimeException('Unable to hide the response.');
  315. }
  316. /**
  317. * Validates an attempt.
  318. *
  319. * @param callable $interviewer A callable that will ask for a question and return the result
  320. * @param OutputInterface $output An Output instance
  321. * @param Question $question A Question instance
  322. *
  323. * @return mixed The validated response
  324. *
  325. * @throws \Exception In case the max number of attempts has been reached and no valid response has been given
  326. */
  327. private function validateAttempts($interviewer, OutputInterface $output, Question $question)
  328. {
  329. $error = null;
  330. $attempts = $question->getMaxAttempts();
  331. while (null === $attempts || $attempts--) {
  332. if (null !== $error) {
  333. $this->writeError($output, $error);
  334. }
  335. try {
  336. return call_user_func($question->getValidator(), $interviewer());
  337. } catch (RuntimeException $e) {
  338. throw $e;
  339. } catch (\Exception $error) {
  340. }
  341. }
  342. throw $error;
  343. }
  344. /**
  345. * Returns a valid unix shell.
  346. *
  347. * @return string|bool The valid shell name, false in case no valid shell is found
  348. */
  349. private function getShell()
  350. {
  351. if (null !== self::$shell) {
  352. return self::$shell;
  353. }
  354. self::$shell = false;
  355. if (file_exists('/usr/bin/env')) {
  356. // handle other OSs with bash/zsh/ksh/csh if available to hide the answer
  357. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  358. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  359. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  360. self::$shell = $sh;
  361. break;
  362. }
  363. }
  364. }
  365. return self::$shell;
  366. }
  367. /**
  368. * Returns whether Stty is available or not.
  369. *
  370. * @return bool
  371. */
  372. private function hasSttyAvailable()
  373. {
  374. if (null !== self::$stty) {
  375. return self::$stty;
  376. }
  377. exec('stty 2>&1', $output, $exitcode);
  378. return self::$stty = $exitcode === 0;
  379. }
  380. }