My favorites | Sign in
Project Logo
                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<?php

/**
*
* Example Usage:
*
* $http = new CurlHttpRequest("GET", "http://www.example.com/");
* echo($http->send());
*
* $http = new CurlHttpRequest();
* $http->open("GET", "http://www.example.com/");
* $http->send();
* echo($http->responseText);
*
* Differences from WinHttpRequest and XmlHttpRequest:
* - Does NOT throw exceptions, uses trigger_error() and return variables.
*
* TODO: Option to catch CURLOPT_VERBOSE output?
*/
class CurlHttpRequest
{
const REGEXP_STATUS = '/^[^\s]*\s*([0-9]{3})([^\r\n]*)/i';

private $url;
private $head;
private $body;
private $_http;
private $_verb;
private $_reqhead;
private $_tmphead;

// high-level helpers, make accessible to extensions (such as GData)
protected $_thappy;
protected $_name;
protected $_sesvar;

// XMLHttpRequest/WinHttpRequest aliases
public $responseText;
public $status;
public $statusText;

function __construct($verb = false, $url = false, $sesvar = false)
{
$this->_reqhead = array();
$this->_tmphead = array();
$this->_sesvar = $sesvar; // $_SESSION var to unset on 401 errors
$this->_http = $this->open($verb, $url);
}

function __destruct()
{
$this->close();
}

/**
* Name; useful for errors when trigger happy mode is enabled.
*/
function setName($name)
{
$this->_name = $name;
}

/**
* Constructs HTTP request to a URL.
*
* @param string $verb HTTP method of requesting URL.
* @param string $url URL to request.
* @param boolean $async Asynchronous?
* @return resource cURL resource.
*/
function open($verb = false, $url = false, $async = false)
{
if ($async) {
return !trigger_error("Async HttpRequest not complete",
E_USER_ERROR);
}

// reset transient vars
$this->head = $this->body = '';
$this->status = false;
$this->statusText = false;
$this->responseText = false;

if ($this->_http) {
$ch = $this->_http;
} else {
$ch = $this->_http = curl_init();
$this->_verb = "GET";
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
array($this, 'writeResponseHeaders'));
curl_setopt($ch, CURLOPT_WRITEFUNCTION,
array($this, 'writeResponseBody'));
}

// HTTP verb (method)
if (false !== $verb) {
$this->_verb = strtoupper($verb);

switch ($this->_verb) {
case "POST": curl_setopt($ch, CURLOPT_POST, TRUE); break;
case "GET": curl_setopt($ch, CURLOPT_HTTPGET, TRUE); break;
case "HEAD": curl_setopt($ch, CURLOPT_NOBODY, TRUE); break;
default:
return !trigger_error("Unsupported HTTP verb \"$verb\" (" .
gettype($verb) . ")", E_USER_ERROR);
}
}

// HTTP URL
if (false !== $url) {
curl_setopt($ch, CURLOPT_URL, ($this->url = $url));
}

// success, return cURL handle for caller-customization (if desired)
return $ch;
}

/**
* Sends HTTP request and processes response.
*
* @param mixed $data Data to send.
* @param mixed $file File to send output to, false == buffer.
* @param array $opt Special options array.
* @return mixed False on failure or body on success (200-299).
*/
function send($data = false, $file = false, $opt = array())
{
$time_start = microtime(true);

//echo("open\n");
if (false === ($ch = $this->open()))
return false;

// configure request headers
//echo("head\n");
if (!CurlHttpRequest::CfgHead($ch, $this->_reqhead, $this->_tmphead)) {
return false;
}

// configure POST payload or query string parameters
//echo("data\n");
if (!CurlHttpRequest::CfgData($ch, $this->url, $this->_verb, $data)) {
return false;
}

// sending to file?
$fn = $this->start($ch, $file);
$ok = curl_exec($ch);
$time_end = microtime(true);
$this->finish($ch, $file, $fn);
if (!$ok) {
$time = round($time_end - $time_start, 2);
return !trigger_error("cURL failed after {$time} seconds ({$this->url})",
E_USER_WARNING);
}

//echo("stat\n");
if (!CurlHttpRequest::GetStatus($this->head, $this->status,
$this->statusText)) {
return false;
}

// automatically unset $_SESSION variable on 401 error
if (401 == $this->status && $this->_sesvar) {
unset($_SESSION[$this->_sesvar]);
}

// trigger happy output on all but 200 (causes false return on error)
if (200 != $this->status) {

if (!isset($opt['muffle']) ||
!in_array($this->status, $opt['muffle'])) {

if (isset($opt['epfx']))
$epfx = $opt['epfx'];
else
$epfx = get_class($this);

// generate message
$msg = "{$epfx} {$this->_verb}";
if ($this->_name) {
$msg .= " ({$this->_name})";
}
$msg .= ": {$this->status} {$this->statusText}";

// use NOTICE on 2XX errors, WARNING for everything else
if ($this->status >= 200 && $this->status <= 299) {
$type = E_USER_NOTICE;
} else {
$type = E_USER_WARNING;
$msg = "{$msg}; {$this->head} (" . $this->getUrl() .
") ... {$this->body}";
}

// bam
trigger_error($msg, $type);
}

// return false on error response
if ($this->status < 200 || $this->status > 299)
return false;
}

return $this->responseText;
}

function setRequestHeader($name, $value, $temporary = false)
{
// TODO: correct casing based on name? Studly caps (Pascal)?
$name = strtolower($name);
$this->_reqhead[$name] = $value;
if ($temporary) {
$this->_tmphead[]= $name;
}
return $this->_http;
}


function setReferer($url)
{
return $this->setRequestHeader('Referer', $url);
}

/**
* Set timeouts
*/
function setTimeout($totalSec, $connSec = false)
{
if (false === ($ch = $this->open())) {
return false;
}
$ok = curl_setopt($ch, CURLOPT_TIMEOUT, $totalSec);
if (false !== $connSec)
$ok |= curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connSec);
return $ok;
}

function setFollow($amount)
{
if (false === ($ch = $this->open())) {
return false;
}
$ok = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$ok |= curl_setopt($ch, CURLOPT_MAXREDIRS, $amount);
return $ok;
}

/**
* Sets a user/password pair to be used with this connection.
*
* Security note: Remains until unset (e.g. regardless of host).
*/
function setUserPass($uid, $pwd = false)
{
if (false === ($ch = $this->open())) {
return false;
}
$up = $pwd ? "{$uid}:{$pwd}" : $uid;
$ok = curl_setopt($ch, CURLOPT_USERPWD, $up);
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, $up ? true : false);
return $ok;
}

function setAuthSub($token)
{
return $this->setRequestHeader('Authorization',
"AuthSub token=\"{$token}\"");
}

function start($ch, &$file)
{
$fn = false;
if (false !== $file) {
if (!is_resource($file)) {
// store for chmod() later
$fn = $file;
$file = SaveStart($fn);
}

curl_setopt($ch, CURLOPT_FILE, $file);
}

return $fn;
}

function finish($ch, $file, $fn)
{
if ($file) {
curl_setopt($ch, CURLOPT_WRITEFUNCTION,
array($this, 'writeResponseBody'));
$this->responseText = '';
} else {
$this->responseText = $this->body;
}

if (false !== $fn) {
SaveClose($file, $fn);
}
}

function close()
{
if ($this->_http) {
curl_close($this->_http);
$this->_http = false;
}
}

function writeResponseBody($ch, $data)
{
$this->body .= $data;
return strlen($data);
}

function writeResponseHeaders($ch, $data)
{
$this->head .= $data;

// multiple headers? happens during POST and initial 100 status
if (false !== ($i = strpos($this->head, "\r\n\r\n"))) {
// only keep the most recent headers (chop previous)
if ($i + 4 < strlen($this->head)) {
$this->head = substr($this->head, $i + 4);
}
}

return strlen($data);
}

function getAllResponseHeaders()
{
return $this->head;
}

function getResponseHeader($name)
{
$re = '/\n' . $name . ':([^\r\n]+)/i';
if (!preg_match($re, $this->head, $m)) {
return false;
}
return trim($m[1]);
}

function getContentType($attr = false, $defval = false)
{
$ct = curl_getinfo($this->_http, CURLINFO_CONTENT_TYPE);
if (false === $attr)
return $ct;

if (';' === $attr) {
$i = strpos($ct, ';');
if (false === $i)
return $ct;
return trim(substr($ct, 0, $i));
}

// \b == word boundary
$re = '/\b' . $attr . '=([^;]+)/i';
if (!preg_match($re, $ct, $m))
return $defval;
return str_replace('"', '', strtolower(trim($m[1])));
}

/**
* Get configured URL.
*
* @return string URL requests are to be sent to.
*/
function getUrl()
{
return $this->url;
}

/**
* Get last effective URL.
*
* @return string Last URL to be requested.
*/
function getLastUrl()
{
return curl_getinfo($this->_http, CURLINFO_EFFECTIVE_URL);
}

/**
* Parse HTTP status and status text.
*
* @param string $headers Response headers including HTTP status line.
* @param integer $status HTTP status code to set.
* @param string $statusText HTTP status message.
* @return boolean True on success, false on failure.
*/
static function GetStatus($headers, &$status, &$statusText)
{
// parse first line of headers for status code and message
// (NOTE: HTTP version is completely ignored)
if (!preg_match(CurlHttpRequest::REGEXP_STATUS, $headers, $m)) {
return !trigger_error("Invalid or corrupt HTTP headers",
E_USER_WARNING);
}

$status = intval($m[1]); // curl_getinfo($ch);
$statusText = trim($m[2]);
return true;
}

/**
* Configure request headers based on dictionary of them.
*
* @param resource $ch cURL resource handle.
* @param array $dic Dictionary of header names and values.
* @param array $tmplist Optional array of headers to set once.
* @return boolean True on success, false on failure.
*/
static function CfgHead($ch, &$dic, &$tmplist = array())
{
// set request headers based on our permanent dictionary
$headers = array();
foreach ($dic as $name => $value) {
if (false !== $value && '' != $value) {
$headers[]= "$name: $value";
}
}

if (count($tmplist) > 0) {
foreach ($tmplist as $name) {
if (array_key_exists($name, $dic)) {
unset($dic[$name]);
}
}
$tmplist = array();
}

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

return true;
}

/**
* Configure request data to send.
*
* @param resource $ch cURL resource handle.
* @param string $url URL data is being sent to.
* @param string $verb Method of sending data (POST, GET, ...)
* @param mixed $data Data to send or false for none.
* @return boolean True on success, false on failure.
*/
static function CfgData($ch, $url, $verb, $data)
{
if (!$url) {
return !trigger_error("No URL specified", E_USER_WARNING);
}
curl_setopt($ch, CURLOPT_URL, $url);

// set options for posting data
if (false !== $data) {
switch ($verb) {
case "POST":
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;

case "GET":
// parse data parameters
if (is_string($data)) {
$s = urlencode($data);
} else {
$s = http_build_query($data);
}

// set query string
$i = strpos($url, '?');
if (false === $i) {
$url = "{$url}?$s";
} else {
$url = substr($url, 0, 1 + $i) . $s;
}

// set URL with query string
curl_setopt($ch, CURLOPT_URL, $url);
break;

default:
return !trigger_error(
"Unimplemented data verb ({$verb})",
E_USER_ERROR);

} // switch (verb)

} // if (data to send)

return true;
}
}

?>
Show details Hide details

Change log

r140 by weenie on Oct 16, 2009   Diff
Replaced Zend HTTP client with
CurlHttpRequest
Go to: 
Project members, sign in to write a code review

Older revisions

r139 by weenie on Oct 16, 2009   Diff
Delicious class and authentication for
HTTP
r136 by weenie on Oct 15, 2009   Diff
Removed trigger happy mode; broke
send() into multiple static functions;
added send to file
r129 by weenie on Oct 10, 2009   Diff
Removed Blog class in favor of new
GData class which handles Blogger AND
Sites
All revisions of this file

File info

Size: 11362 bytes, 494 lines
Hosted by Google Code