1: <?php
2:
3: App::uses('HttpResponse', 'Web.Lib');
4:
5: class HttpClient {
6:
7: 8: 9: 10:
11: private $agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0';
12:
13: 14: 15: 16:
17: private $referer = '';
18:
19: 20: 21: 22:
23: private $targetResponseDirectory = null;
24:
25: 26: 27: 28:
29: private static $targetCount = 0;
30:
31: 32: 33: 34:
35: private $followLocation = false;
36:
37: 38: 39: 40: 41: 42:
43: public function doPost($url, $parameters = array()) {
44: return $this->_doRequest($url, $parameters, true);
45: }
46:
47: 48: 49: 50: 51: 52:
53: public function doGet($url, $parameters = array()) {
54: return $this->_doRequest($url, $parameters, false);
55: }
56:
57: 58: 59: 60:
61: public function setFollowLocation($enabled) {
62: $this->followLocation = $enabled;
63: }
64:
65: 66: 67: 68:
69: public function setTargetResponseDirectory($path) {
70: $this->targetResponseDirectory = $path;
71: }
72:
73: 74: 75: 76: 77: 78: 79:
80: private function _doRequest($url, $parameters, $post) {
81: $curlOptions = array();
82:
83: if ($post) {
84: $curlOptions[CURLOPT_URL] = $url;
85: $curlOptions[CURLOPT_POST] = true;
86: $curlOptions[CURLOPT_POSTFIELDS] = $this->_buildParameterLine($parameters);
87: } else {
88: $curlOptions[CURLOPT_URL] = $url . '?' . $this->_buildParameterLine($parameters);
89: $curlOptions[CURLOPT_POST] = false;
90: }
91:
92: $curlOptions[CURLOPT_USERAGENT] = $this->agent;
93: $curlOptions[CURLOPT_COOKIEJAR] = $this->_getCookiesFile();
94: $curlOptions[CURLOPT_COOKIEFILE] = $this->_getCookiesFile();
95: $curlOptions[CURLOPT_FOLLOWLOCATION] = $this->followLocation;
96: $curlOptions[CURLOPT_HEADER] = true;
97: $curlOptions[CURLOPT_RETURNTRANSFER] = true;
98: $curlOptions[CURLOPT_REFERER] = $this->referer;
99:
100: $this->referer = $url;
101: $response = new HttpResponse($curlOptions);
102:
103: if ($this->targetResponseDirectory) {
104: $path = $this->targetResponseDirectory.'/'.(++self::$targetCount).'.html';
105: file_put_contents($path, $response->getBody());
106: }
107:
108: return $response;
109: }
110:
111: 112: 113: 114:
115: private function _getCookiesFile() {
116: if (empty($this->cookiesFile)) {
117: $this->cookiesFile = tempnam("/tmp", "CURLCOOKIE");
118: }
119: return $this->cookiesFile;
120: }
121:
122: 123: 124: 125: 126:
127: private function _buildParameterLine($parameters) {
128: $pairs = array();
129: foreach ($parameters as $key => $value) {
130: $pairs[] = urlencode($key) . '=' . urlencode($value);
131: }
132: return implode('&', $pairs);
133: }
134:
135: }
136:
137: ?>