1<?php
2/**
3 * Copyright 2007-2016 Horde LLC (http://www.horde.org/)
4 *
5 * @author   Chuck Hagenbuch <chuck@horde.org>
6 * @license  http://www.horde.org/licenses/bsd BSD
7 * @category Horde
8 * @package  Http
9 */
10
11/**
12 * @author   Chuck Hagenbuch <chuck@horde.org>
13 * @license  http://www.horde.org/licenses/bsd BSD
14 * @category Horde
15 * @package  Http
16 */
17class Horde_Http_Response_Curl extends Horde_Http_Response_Base
18{
19    /**
20     * Info on the request obtained from curl_getinfo().
21     *
22     * @var array
23     */
24    protected $_info = array();
25
26    /**
27     * Response body.
28     *
29     * @var string
30     */
31    protected $_body;
32
33    /**
34     * Constructor.
35     *
36     * @param string $uri
37     * @param string $curlresult
38     * @param array $curlinfo
39     */
40    public function __construct($uri, $curlresult, $curlinfo)
41    {
42        $this->uri = $uri;
43        $this->_parseResult($curlresult);
44        $this->_parseInfo($curlinfo);
45    }
46
47    /**
48     * Returns the body of the HTTP response.
49     *
50     * @return string HTTP response body.
51     */
52    public function getBody()
53    {
54        return $this->_body;
55    }
56
57    /**
58     * Parses the combined header/body result from cURL.
59     *
60     * @param string $curlresult
61     */
62    protected function _parseResult($curlresult)
63    {
64        /* Curl returns multiple headers, if the last action required multiple
65         * requests, e.g. when doing Digest authentication. Only parse the
66         * headers of the latest response. */
67        preg_match_all('/(^|\r\n\r\n)(HTTP\/)/', $curlresult, $matches, PREG_OFFSET_CAPTURE);
68        $startOfHeaders = $matches[2][count($matches[2]) - 1][1];
69        $endOfHeaders = strpos($curlresult, "\r\n\r\n", $startOfHeaders);
70        $headers = substr($curlresult, $startOfHeaders, $endOfHeaders - $startOfHeaders);
71        $this->_parseHeaders($headers);
72        $this->_body = substr($curlresult, $endOfHeaders + 4);
73    }
74
75    /**
76     * Processes the results of curl_getinfo.
77     *
78     * @param array $curlinfo
79     */
80    protected function _parseInfo($curlinfo)
81    {
82        $this->uri = $curlinfo['url'];
83        $this->code = $curlinfo['http_code'];
84        $this->_info = $curlinfo;
85    }
86}
87