XdebugHandler.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. /**
  14. * @author John Stevenson <john-stevenson@blueyonder.co.uk>
  15. */
  16. class XdebugHandler
  17. {
  18. const ENV_ALLOW = 'COMPOSER_ALLOW_XDEBUG';
  19. const ENV_INI_SCAN_DIR = 'PHP_INI_SCAN_DIR';
  20. const ENV_INI_SCAN_DIR_OLD = 'COMPOSER_PHP_INI_SCAN_DIR_OLD';
  21. private $output;
  22. private $loaded;
  23. private $tmpIni;
  24. private $scanDir;
  25. /**
  26. * Constructor
  27. */
  28. public function __construct(OutputInterface $output)
  29. {
  30. $this->output = $output;
  31. $this->loaded = extension_loaded('xdebug');
  32. $tmp = sys_get_temp_dir();
  33. $this->tmpIni = $tmp.'/composer-php.ini';
  34. $this->scanDir = $tmp.'/composer-php-empty';
  35. }
  36. /**
  37. * Checks if xdebug is loaded and composer needs to be restarted
  38. *
  39. * If so, then a tmp ini is created with the xdebug ini entry commented out.
  40. * If additional inis have been loaded, these are combined into the tmp ini
  41. * and PHP_INI_SCAN_DIR is set to an empty directory. An environment
  42. * variable is set so that the new process is created only once.
  43. */
  44. public function check()
  45. {
  46. if (!$this->needsRestart()) {
  47. $originalIniScanDir = getenv(self::ENV_INI_SCAN_DIR_OLD);
  48. if ($originalIniScanDir) {
  49. putenv(self::ENV_INI_SCAN_DIR_OLD);
  50. putenv(self::ENV_INI_SCAN_DIR.'=' . $originalIniScanDir);
  51. } else {
  52. putenv(self::ENV_INI_SCAN_DIR);
  53. }
  54. return;
  55. }
  56. if ($this->prepareRestart($command)) {
  57. $this->restart($command);
  58. }
  59. }
  60. /**
  61. * Executes the restarted command
  62. *
  63. * @param string $command
  64. */
  65. protected function restart($command)
  66. {
  67. passthru($command, $exitCode);
  68. exit($exitCode);
  69. }
  70. /**
  71. * Returns true if a restart is needed
  72. *
  73. * @return bool
  74. */
  75. private function needsRestart()
  76. {
  77. if (PHP_SAPI !== 'cli' || !defined('PHP_BINARY')) {
  78. return false;
  79. }
  80. return !getenv(self::ENV_ALLOW) && $this->loaded;
  81. }
  82. /**
  83. * Returns true if everything was written for the restart
  84. *
  85. * If any of the following fails (however unlikely) we must return false to
  86. * stop potential recursion:
  87. * - tmp ini file creation
  88. * - environment variable creation
  89. * - tmp scan dir creation
  90. *
  91. * @param null|string $command The command to run, set by method
  92. *
  93. * @return bool
  94. */
  95. private function prepareRestart(&$command)
  96. {
  97. $iniFiles = array();
  98. if ($loadedIni = php_ini_loaded_file()) {
  99. $iniFiles[] = $loadedIni;
  100. }
  101. $additional = $this->getAdditionalInis($iniFiles, $replace);
  102. if ($this->writeTmpIni($iniFiles, $replace)) {
  103. $command = $this->getCommand($additional);
  104. }
  105. return !empty($command) && putenv(self::ENV_ALLOW.'=1');
  106. }
  107. /**
  108. * Writes the temporary ini file, or clears its name if no ini
  109. *
  110. * If there are no ini files, the tmp ini name is cleared so that
  111. * an empty value is passed with the -c option.
  112. *
  113. * @param array $iniFiles The php.ini locations
  114. * @param bool $replace Whether we need to modify the files
  115. *
  116. * @return bool False if the tmp ini could not be created
  117. */
  118. private function writeTmpIni(array $iniFiles, $replace)
  119. {
  120. if (empty($iniFiles)) {
  121. // Unlikely, maybe xdebug was loaded through the -d option.
  122. $this->tmpIni = '';
  123. return true;
  124. }
  125. $content = $this->getIniHeader($iniFiles);
  126. foreach ($iniFiles as $file) {
  127. $content .= $this->getIniData($file, $replace);
  128. }
  129. return @file_put_contents($this->tmpIni, $content);
  130. }
  131. /**
  132. * Returns true if additional inis were loaded
  133. *
  134. * @param array $iniFiles Populated by method
  135. * @param bool $replace Whether we need to modify the files
  136. *
  137. * @return bool
  138. */
  139. private function getAdditionalInis(array &$iniFiles, &$replace)
  140. {
  141. $replace = true;
  142. if ($scanned = php_ini_scanned_files()) {
  143. $list = explode(',', $scanned);
  144. foreach ($list as $file) {
  145. $file = trim($file);
  146. if (preg_match('/xdebug.ini$/', $file)) {
  147. // Skip the file, no need for regex replacing
  148. $replace = false;
  149. } else {
  150. $iniFiles[] = $file;
  151. }
  152. }
  153. }
  154. return !empty($scanned);
  155. }
  156. /**
  157. * Returns formatted ini file data
  158. *
  159. * @param string $iniFile The location of the ini file
  160. * @param bool $replace Whether to regex replace content
  161. *
  162. * @return string The ini data
  163. */
  164. private function getIniData($iniFile, $replace)
  165. {
  166. $data = str_repeat(PHP_EOL, 3);
  167. $data .= sprintf('; %s%s', $iniFile, PHP_EOL);
  168. $contents = file_get_contents($iniFile);
  169. if ($replace) {
  170. // Comment out xdebug config
  171. $regex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi';
  172. $data .= preg_replace($regex, ';$1', $contents);
  173. } else {
  174. $data .= $contents;
  175. }
  176. return $data;
  177. }
  178. /**
  179. * Creates the required environment and returns the restart command line
  180. *
  181. * @param bool $additional Whether additional inis were loaded
  182. *
  183. * @return string|null The command line or null on failure
  184. */
  185. private function getCommand($additional)
  186. {
  187. if ($additional) {
  188. if (!file_exists($this->scanDir) && !@mkdir($this->scanDir, 0777)) {
  189. return;
  190. }
  191. $currentIniScanDir = getenv(self::ENV_INI_SCAN_DIR);
  192. if ($currentIniScanDir) {
  193. putenv(self::ENV_INI_SCAN_DIR_OLD.'='.$currentIniScanDir);
  194. }
  195. if (!putenv(self::ENV_INI_SCAN_DIR.'='.$this->scanDir)) {
  196. return;
  197. }
  198. }
  199. $phpArgs = array(PHP_BINARY, '-c', $this->tmpIni);
  200. $params = array_merge($phpArgs, $this->getScriptArgs($_SERVER['argv']));
  201. return implode(' ', array_map(array($this, 'escape'), $params));
  202. }
  203. /**
  204. * Returns the restart script arguments, adding --ansi if required
  205. *
  206. * If we are a terminal with color support we must ensure that the --ansi
  207. * option is set, because the restarted output is piped.
  208. *
  209. * @param array $args The argv array
  210. *
  211. * @return array
  212. */
  213. private function getScriptArgs(array $args)
  214. {
  215. if (in_array('--no-ansi', $args) || in_array('--ansi', $args)) {
  216. return $args;
  217. }
  218. if ($this->output->isDecorated()) {
  219. $offset = count($args) > 1 ? 2: 1;
  220. array_splice($args, $offset, 0, '--ansi');
  221. }
  222. return $args;
  223. }
  224. /**
  225. * Escapes a string to be used as a shell argument.
  226. *
  227. * From https://github.com/johnstevenson/winbox-args
  228. * MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk>
  229. *
  230. * @param string $arg The argument to be escaped
  231. * @param bool $meta Additionally escape cmd.exe meta characters
  232. *
  233. * @return string The escaped argument
  234. */
  235. private function escape($arg, $meta = true)
  236. {
  237. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  238. return escapeshellarg($arg);
  239. }
  240. $quote = strpbrk($arg, " \t") !== false || $arg === '';
  241. $arg = preg_replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes);
  242. if ($meta) {
  243. $meta = $dquotes || preg_match('/%[^%]+%/', $arg);
  244. if (!$meta && !$quote) {
  245. $quote = strpbrk($arg, '^&|<>()') !== false;
  246. }
  247. }
  248. if ($quote) {
  249. $arg = preg_replace('/(\\\\*)$/', '$1$1', $arg);
  250. $arg = '"'.$arg.'"';
  251. }
  252. if ($meta) {
  253. $arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg);
  254. }
  255. return $arg;
  256. }
  257. /**
  258. * Returns the location of the original ini data used.
  259. *
  260. * @param array $iniFiles loaded php.ini locations
  261. *
  262. * @return string
  263. */
  264. private function getIniHeader($iniFiles)
  265. {
  266. $ini = implode(PHP_EOL.'; ', $iniFiles);
  267. $header = <<<EOD
  268. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  269. ; This file was automatically generated by Composer and can now be deleted.
  270. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  271. ; It is a modified copy of your php.ini configuration, found at:
  272. ; {$ini}
  273. ; Make any changes there because this data will not be used again.
  274. EOD;
  275. $header .= str_repeat(PHP_EOL, 50);
  276. return $header;
  277. }
  278. }