Client.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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\BrowserKit;
  11. use Symfony\Component\BrowserKit\Exception\BadMethodCallException;
  12. use Symfony\Component\DomCrawler\Crawler;
  13. use Symfony\Component\DomCrawler\Link;
  14. use Symfony\Component\DomCrawler\Form;
  15. use Symfony\Component\Process\PhpProcess;
  16. /**
  17. * Client simulates a browser.
  18. *
  19. * To make the actual request, you need to implement the doRequest() method.
  20. *
  21. * If you want to be able to run requests in their own process (insulated flag),
  22. * you need to also implement the getScript() method.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. */
  26. abstract class Client
  27. {
  28. protected $history;
  29. protected $cookieJar;
  30. protected $server = array();
  31. protected $internalRequest;
  32. protected $request;
  33. protected $internalResponse;
  34. protected $response;
  35. protected $crawler;
  36. protected $insulated = false;
  37. protected $redirect;
  38. protected $followRedirects = true;
  39. protected $followMetaRefresh = false;
  40. private $maxRedirects = -1;
  41. private $redirectCount = 0;
  42. private $redirects = array();
  43. private $isMainRequest = true;
  44. /**
  45. * @param array $server The server parameters (equivalent of $_SERVER)
  46. * @param History $history A History instance to store the browser history
  47. * @param CookieJar $cookieJar A CookieJar instance to store the cookies
  48. */
  49. public function __construct(array $server = array(), History $history = null, CookieJar $cookieJar = null)
  50. {
  51. $this->setServerParameters($server);
  52. $this->history = $history ?: new History();
  53. $this->cookieJar = $cookieJar ?: new CookieJar();
  54. }
  55. /**
  56. * Sets whether to automatically follow redirects or not.
  57. *
  58. * @param bool $followRedirect Whether to follow redirects
  59. */
  60. public function followRedirects($followRedirect = true)
  61. {
  62. $this->followRedirects = (bool) $followRedirect;
  63. }
  64. /**
  65. * Sets whether to automatically follow meta refresh redirects or not.
  66. */
  67. public function followMetaRefresh(bool $followMetaRefresh = true)
  68. {
  69. $this->followMetaRefresh = $followMetaRefresh;
  70. }
  71. /**
  72. * Returns whether client automatically follows redirects or not.
  73. *
  74. * @return bool
  75. */
  76. public function isFollowingRedirects()
  77. {
  78. return $this->followRedirects;
  79. }
  80. /**
  81. * Sets the maximum number of redirects that crawler can follow.
  82. *
  83. * @param int $maxRedirects
  84. */
  85. public function setMaxRedirects($maxRedirects)
  86. {
  87. $this->maxRedirects = $maxRedirects < 0 ? -1 : $maxRedirects;
  88. $this->followRedirects = -1 != $this->maxRedirects;
  89. }
  90. /**
  91. * Returns the maximum number of redirects that crawler can follow.
  92. *
  93. * @return int
  94. */
  95. public function getMaxRedirects()
  96. {
  97. return $this->maxRedirects;
  98. }
  99. /**
  100. * Sets the insulated flag.
  101. *
  102. * @param bool $insulated Whether to insulate the requests or not
  103. *
  104. * @throws \RuntimeException When Symfony Process Component is not installed
  105. */
  106. public function insulate($insulated = true)
  107. {
  108. if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) {
  109. throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.');
  110. }
  111. $this->insulated = (bool) $insulated;
  112. }
  113. /**
  114. * Sets server parameters.
  115. *
  116. * @param array $server An array of server parameters
  117. */
  118. public function setServerParameters(array $server)
  119. {
  120. $this->server = array_merge(array(
  121. 'HTTP_USER_AGENT' => 'Symfony BrowserKit',
  122. ), $server);
  123. }
  124. /**
  125. * Sets single server parameter.
  126. *
  127. * @param string $key A key of the parameter
  128. * @param string $value A value of the parameter
  129. */
  130. public function setServerParameter($key, $value)
  131. {
  132. $this->server[$key] = $value;
  133. }
  134. /**
  135. * Gets single server parameter for specified key.
  136. *
  137. * @param string $key A key of the parameter to get
  138. * @param string $default A default value when key is undefined
  139. *
  140. * @return string A value of the parameter
  141. */
  142. public function getServerParameter($key, $default = '')
  143. {
  144. return isset($this->server[$key]) ? $this->server[$key] : $default;
  145. }
  146. public function xmlHttpRequest(string $method, string $uri, array $parameters = array(), array $files = array(), array $server = array(), string $content = null, bool $changeHistory = true): Crawler
  147. {
  148. $this->setServerParameter('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  149. try {
  150. return $this->request($method, $uri, $parameters, $files, $server, $content, $changeHistory);
  151. } finally {
  152. unset($this->server['HTTP_X_REQUESTED_WITH']);
  153. }
  154. }
  155. /**
  156. * Returns the History instance.
  157. *
  158. * @return History A History instance
  159. */
  160. public function getHistory()
  161. {
  162. return $this->history;
  163. }
  164. /**
  165. * Returns the CookieJar instance.
  166. *
  167. * @return CookieJar A CookieJar instance
  168. */
  169. public function getCookieJar()
  170. {
  171. return $this->cookieJar;
  172. }
  173. /**
  174. * Returns the current Crawler instance.
  175. *
  176. * @return Crawler A Crawler instance
  177. */
  178. public function getCrawler()
  179. {
  180. if (null === $this->crawler) {
  181. @trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
  182. // throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
  183. }
  184. return $this->crawler;
  185. }
  186. /**
  187. * Returns the current BrowserKit Response instance.
  188. *
  189. * @return Response A BrowserKit Response instance
  190. */
  191. public function getInternalResponse()
  192. {
  193. if (null === $this->internalResponse) {
  194. @trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
  195. // throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
  196. }
  197. return $this->internalResponse;
  198. }
  199. /**
  200. * Returns the current origin response instance.
  201. *
  202. * The origin response is the response instance that is returned
  203. * by the code that handles requests.
  204. *
  205. * @return object A response instance
  206. *
  207. * @see doRequest()
  208. */
  209. public function getResponse()
  210. {
  211. if (null === $this->response) {
  212. @trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
  213. // throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
  214. }
  215. return $this->response;
  216. }
  217. /**
  218. * Returns the current BrowserKit Request instance.
  219. *
  220. * @return Request A BrowserKit Request instance
  221. */
  222. public function getInternalRequest()
  223. {
  224. if (null === $this->internalRequest) {
  225. @trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
  226. // throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
  227. }
  228. return $this->internalRequest;
  229. }
  230. /**
  231. * Returns the current origin Request instance.
  232. *
  233. * The origin request is the request instance that is sent
  234. * to the code that handles requests.
  235. *
  236. * @return object A Request instance
  237. *
  238. * @see doRequest()
  239. */
  240. public function getRequest()
  241. {
  242. if (null === $this->request) {
  243. @trigger_error(sprintf('Calling the "%s()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0.', __METHOD__), E_USER_DEPRECATED);
  244. // throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
  245. }
  246. return $this->request;
  247. }
  248. /**
  249. * Clicks on a given link.
  250. *
  251. * @return Crawler
  252. */
  253. public function click(Link $link)
  254. {
  255. if ($link instanceof Form) {
  256. return $this->submit($link);
  257. }
  258. return $this->request($link->getMethod(), $link->getUri());
  259. }
  260. /**
  261. * Finds link by given text and then clicks on it.
  262. *
  263. * @param string $value The link text
  264. *
  265. * @return Crawler
  266. */
  267. public function clickLink($value)
  268. {
  269. $link = $this->getCrawler()->selectLink($value)->link();
  270. return $this->click($link);
  271. }
  272. /**
  273. * Submits a form.
  274. *
  275. * @param Form $form A Form instance
  276. * @param array $values An array of form field values
  277. * @param array $serverParameters An array of server parameters
  278. *
  279. * @return Crawler
  280. */
  281. public function submit(Form $form, array $values = array()/*, array $serverParameters = array()*/)
  282. {
  283. $form->setValues($values);
  284. $serverParameters = 2 < \func_num_args() ? func_get_arg(2) : array();
  285. return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles(), $serverParameters);
  286. }
  287. /**
  288. * Finds a form by submit button text and then submits it.
  289. *
  290. * @param string $button The button text
  291. * @param array $values An array of form field values
  292. * @param string $method The method for the form
  293. *
  294. * @return Crawler
  295. */
  296. public function submitForm($button, $values, $method)
  297. {
  298. $buttonNode = $this->getCrawler()->selectButton($button);
  299. $form = $buttonNode->form($values, $method);
  300. return $this->submit($form);
  301. }
  302. /**
  303. * Calls a URI.
  304. *
  305. * @param string $method The request method
  306. * @param string $uri The URI to fetch
  307. * @param array $parameters The Request parameters
  308. * @param array $files The files
  309. * @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
  310. * @param string $content The raw body data
  311. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  312. *
  313. * @return Crawler
  314. */
  315. public function request(string $method, string $uri, array $parameters = array(), array $files = array(), array $server = array(), string $content = null, bool $changeHistory = true)
  316. {
  317. if ($this->isMainRequest) {
  318. $this->redirectCount = 0;
  319. } else {
  320. ++$this->redirectCount;
  321. }
  322. $uri = $this->getAbsoluteUri($uri);
  323. $server = array_merge($this->server, $server);
  324. if (isset($server['HTTPS'])) {
  325. $uri = preg_replace('{^'.parse_url($uri, PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
  326. }
  327. if (!$this->history->isEmpty()) {
  328. $server['HTTP_REFERER'] = $this->history->current()->getUri();
  329. }
  330. if (empty($server['HTTP_HOST'])) {
  331. $server['HTTP_HOST'] = $this->extractHost($uri);
  332. }
  333. $server['HTTPS'] = 'https' == parse_url($uri, PHP_URL_SCHEME);
  334. $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
  335. $this->request = $this->filterRequest($this->internalRequest);
  336. if (true === $changeHistory) {
  337. $this->history->add($this->internalRequest);
  338. }
  339. if ($this->insulated) {
  340. $this->response = $this->doRequestInProcess($this->request);
  341. } else {
  342. $this->response = $this->doRequest($this->request);
  343. }
  344. $this->internalResponse = $this->filterResponse($this->response);
  345. $this->cookieJar->updateFromResponse($this->internalResponse, $uri);
  346. $status = $this->internalResponse->getStatus();
  347. if ($status >= 300 && $status < 400) {
  348. $this->redirect = $this->internalResponse->getHeader('Location');
  349. } else {
  350. $this->redirect = null;
  351. }
  352. if ($this->followRedirects && $this->redirect) {
  353. $this->redirects[serialize($this->history->current())] = true;
  354. return $this->crawler = $this->followRedirect();
  355. }
  356. $this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type'));
  357. // Check for meta refresh redirect
  358. if ($this->followMetaRefresh && null !== $redirect = $this->getMetaRefreshUrl()) {
  359. $this->redirect = $redirect;
  360. $this->redirects[serialize($this->history->current())] = true;
  361. $this->crawler = $this->followRedirect();
  362. }
  363. return $this->crawler;
  364. }
  365. /**
  366. * Makes a request in another process.
  367. *
  368. * @param object $request An origin request instance
  369. *
  370. * @return object An origin response instance
  371. *
  372. * @throws \RuntimeException When processing returns exit code
  373. */
  374. protected function doRequestInProcess($request)
  375. {
  376. $deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
  377. putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
  378. $_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
  379. $process = new PhpProcess($this->getScript($request), null, null);
  380. $process->run();
  381. if (file_exists($deprecationsFile)) {
  382. $deprecations = file_get_contents($deprecationsFile);
  383. unlink($deprecationsFile);
  384. foreach ($deprecations ? unserialize($deprecations) : array() as $deprecation) {
  385. if ($deprecation[0]) {
  386. trigger_error($deprecation[1], E_USER_DEPRECATED);
  387. } else {
  388. @trigger_error($deprecation[1], E_USER_DEPRECATED);
  389. }
  390. }
  391. }
  392. if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
  393. throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
  394. }
  395. return unserialize($process->getOutput());
  396. }
  397. /**
  398. * Makes a request.
  399. *
  400. * @param object $request An origin request instance
  401. *
  402. * @return object An origin response instance
  403. */
  404. abstract protected function doRequest($request);
  405. /**
  406. * Returns the script to execute when the request must be insulated.
  407. *
  408. * @param object $request An origin request instance
  409. *
  410. * @throws \LogicException When this abstract class is not implemented
  411. */
  412. protected function getScript($request)
  413. {
  414. throw new \LogicException('To insulate requests, you need to override the getScript() method.');
  415. }
  416. /**
  417. * Filters the BrowserKit request to the origin one.
  418. *
  419. * @param Request $request The BrowserKit Request to filter
  420. *
  421. * @return object An origin request instance
  422. */
  423. protected function filterRequest(Request $request)
  424. {
  425. return $request;
  426. }
  427. /**
  428. * Filters the origin response to the BrowserKit one.
  429. *
  430. * @param object $response The origin response to filter
  431. *
  432. * @return Response An BrowserKit Response instance
  433. */
  434. protected function filterResponse($response)
  435. {
  436. return $response;
  437. }
  438. /**
  439. * Creates a crawler.
  440. *
  441. * This method returns null if the DomCrawler component is not available.
  442. *
  443. * @param string $uri A URI
  444. * @param string $content Content for the crawler to use
  445. * @param string $type Content type
  446. *
  447. * @return Crawler|null
  448. */
  449. protected function createCrawlerFromContent($uri, $content, $type)
  450. {
  451. if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
  452. return;
  453. }
  454. $crawler = new Crawler(null, $uri);
  455. $crawler->addContent($content, $type);
  456. return $crawler;
  457. }
  458. /**
  459. * Goes back in the browser history.
  460. *
  461. * @return Crawler
  462. */
  463. public function back()
  464. {
  465. do {
  466. $request = $this->history->back();
  467. } while (array_key_exists(serialize($request), $this->redirects));
  468. return $this->requestFromRequest($request, false);
  469. }
  470. /**
  471. * Goes forward in the browser history.
  472. *
  473. * @return Crawler
  474. */
  475. public function forward()
  476. {
  477. do {
  478. $request = $this->history->forward();
  479. } while (array_key_exists(serialize($request), $this->redirects));
  480. return $this->requestFromRequest($request, false);
  481. }
  482. /**
  483. * Reloads the current browser.
  484. *
  485. * @return Crawler
  486. */
  487. public function reload()
  488. {
  489. return $this->requestFromRequest($this->history->current(), false);
  490. }
  491. /**
  492. * Follow redirects?
  493. *
  494. * @return Crawler
  495. *
  496. * @throws \LogicException If request was not a redirect
  497. */
  498. public function followRedirect()
  499. {
  500. if (empty($this->redirect)) {
  501. throw new \LogicException('The request was not redirected.');
  502. }
  503. if (-1 !== $this->maxRedirects) {
  504. if ($this->redirectCount > $this->maxRedirects) {
  505. $this->redirectCount = 0;
  506. throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
  507. }
  508. }
  509. $request = $this->internalRequest;
  510. if (in_array($this->internalResponse->getStatus(), array(301, 302, 303))) {
  511. $method = 'GET';
  512. $files = array();
  513. $content = null;
  514. } else {
  515. $method = $request->getMethod();
  516. $files = $request->getFiles();
  517. $content = $request->getContent();
  518. }
  519. if ('GET' === strtoupper($method)) {
  520. // Don't forward parameters for GET request as it should reach the redirection URI
  521. $parameters = array();
  522. } else {
  523. $parameters = $request->getParameters();
  524. }
  525. $server = $request->getServer();
  526. $server = $this->updateServerFromUri($server, $this->redirect);
  527. $this->isMainRequest = false;
  528. $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
  529. $this->isMainRequest = true;
  530. return $response;
  531. }
  532. /**
  533. * @see https://dev.w3.org/html5/spec-preview/the-meta-element.html#attr-meta-http-equiv-refresh
  534. */
  535. private function getMetaRefreshUrl(): ?string
  536. {
  537. $metaRefresh = $this->getCrawler()->filter('head meta[http-equiv="refresh"]');
  538. foreach ($metaRefresh->extract(array('content')) as $content) {
  539. if (preg_match('/^\s*0\s*;\s*URL\s*=\s*(?|\'([^\']++)|"([^"]++)|([^\'"].*))/i', $content, $m)) {
  540. return str_replace("\t\r\n", '', rtrim($m[1]));
  541. }
  542. }
  543. return null;
  544. }
  545. /**
  546. * Restarts the client.
  547. *
  548. * It flushes history and all cookies.
  549. */
  550. public function restart()
  551. {
  552. $this->cookieJar->clear();
  553. $this->history->clear();
  554. }
  555. /**
  556. * Takes a URI and converts it to absolute if it is not already absolute.
  557. *
  558. * @param string $uri A URI
  559. *
  560. * @return string An absolute URI
  561. */
  562. protected function getAbsoluteUri($uri)
  563. {
  564. // already absolute?
  565. if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
  566. return $uri;
  567. }
  568. if (!$this->history->isEmpty()) {
  569. $currentUri = $this->history->current()->getUri();
  570. } else {
  571. $currentUri = sprintf('http%s://%s/',
  572. isset($this->server['HTTPS']) ? 's' : '',
  573. isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
  574. );
  575. }
  576. // protocol relative URL
  577. if (0 === strpos($uri, '//')) {
  578. return parse_url($currentUri, PHP_URL_SCHEME).':'.$uri;
  579. }
  580. // anchor or query string parameters?
  581. if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
  582. return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
  583. }
  584. if ('/' !== $uri[0]) {
  585. $path = parse_url($currentUri, PHP_URL_PATH);
  586. if ('/' !== substr($path, -1)) {
  587. $path = substr($path, 0, strrpos($path, '/') + 1);
  588. }
  589. $uri = $path.$uri;
  590. }
  591. return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
  592. }
  593. /**
  594. * Makes a request from a Request object directly.
  595. *
  596. * @param Request $request A Request instance
  597. * @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
  598. *
  599. * @return Crawler
  600. */
  601. protected function requestFromRequest(Request $request, $changeHistory = true)
  602. {
  603. return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
  604. }
  605. private function updateServerFromUri($server, $uri)
  606. {
  607. $server['HTTP_HOST'] = $this->extractHost($uri);
  608. $scheme = parse_url($uri, PHP_URL_SCHEME);
  609. $server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
  610. unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
  611. return $server;
  612. }
  613. private function extractHost($uri)
  614. {
  615. $host = parse_url($uri, PHP_URL_HOST);
  616. if ($port = parse_url($uri, PHP_URL_PORT)) {
  617. return $host.':'.$port;
  618. }
  619. return $host;
  620. }
  621. }