GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — develop (#1782)
by
unknown
10:54
created
libs/PEAR.1.9.5/HTTP/Request2/Response.php 3 patches
Switch Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -435,11 +435,11 @@
 block discarded – undo
435 435
 
436 436
             try {
437 437
                 switch (strtolower($this->getHeader('content-encoding'))) {
438
-                case 'gzip':
439
-                    $decoded = self::decodeGzip($this->body);
440
-                    break;
441
-                case 'deflate':
442
-                    $decoded = self::decodeDeflate($this->body);
438
+                	case 'gzip':
439
+                    	$decoded = self::decodeGzip($this->body);
440
+                    	break;
441
+                	case 'deflate':
442
+                    	$decoded = self::decodeDeflate($this->body);
443 443
                 }
444 444
             } catch (Exception $e) {
445 445
             }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -8 removed lines patch added patch discarded remove patch
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
         // the request
143 143
         300 => 'Multiple Choices',
144 144
         301 => 'Moved Permanently',
145
-        302 => 'Found',  // 1.1
145
+        302 => 'Found', // 1.1
146 146
         303 => 'See Other',
147 147
         304 => 'Not Modified',
148 148
         305 => 'Use Proxy',
@@ -220,8 +220,8 @@  discard block
 block discarded – undo
220 220
         $this->version      = $m[1];
221 221
         $this->code         = intval($m[2]);
222 222
         $this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);
223
-        $this->bodyEncoded  = (bool)$bodyEncoded;
224
-        $this->effectiveUrl = (string)$effectiveUrl;
223
+        $this->bodyEncoded  = (bool) $bodyEncoded;
224
+        $this->effectiveUrl = (string) $effectiveUrl;
225 225
     }
226 226
 
227 227
     /**
@@ -241,9 +241,8 @@  discard block
 block discarded – undo
241 241
         if ('' == $headerLine) {
242 242
             // empty string signals the end of headers, process the received ones
243 243
             if (!empty($this->headers['set-cookie'])) {
244
-                $cookies = is_array($this->headers['set-cookie'])?
245
-                           $this->headers['set-cookie']:
246
-                           array($this->headers['set-cookie']);
244
+                $cookies = is_array($this->headers['set-cookie']) ?
245
+                           $this->headers['set-cookie'] : array($this->headers['set-cookie']);
247 246
                 foreach ($cookies as $cookieString) {
248 247
                     $this->parseCookie($cookieString);
249 248
                 }
@@ -400,7 +399,7 @@  discard block
 block discarded – undo
400 399
             return $this->headers;
401 400
         } else {
402 401
             $headerName = strtolower($headerName);
403
-            return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
402
+            return isset($this->headers[$headerName]) ? $this->headers[$headerName] : null;
404 403
         }
405 404
     }
406 405
 
@@ -625,7 +624,7 @@  discard block
 block discarded – undo
625 624
         // We should check for presence of zlib header and use gzuncompress() or
626 625
         // gzinflate() as needed. See bug #15305
627 626
         $header = unpack('n', substr($data, 0, 2));
628
-        return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
627
+        return (0 == $header[1] % 31) ? gzuncompress($data) : gzinflate($data);
629 628
     }
630 629
 }
631 630
 ?>
632 631
\ No newline at end of file
Please login to merge, or discard this patch.
Indentation   +591 added lines, -591 removed lines patch added patch discarded remove patch
@@ -1,22 +1,22 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Class representing a HTTP response
4
- *
5
- * PHP version 5
6
- *
7
- * LICENSE
8
- *
9
- * This source file is subject to BSD 3-Clause License that is bundled
10
- * with this package in the file LICENSE and available at the URL
11
- * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
12
- *
13
- * @category  HTTP
14
- * @package   HTTP_Request2
15
- * @author    Alexey Borzov <[email protected]>
16
- * @copyright 2008-2014 Alexey Borzov <[email protected]>
17
- * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
18
- * @link      http://pear.php.net/package/HTTP_Request2
19
- */
3
+	 * Class representing a HTTP response
4
+	 *
5
+	 * PHP version 5
6
+	 *
7
+	 * LICENSE
8
+	 *
9
+	 * This source file is subject to BSD 3-Clause License that is bundled
10
+	 * with this package in the file LICENSE and available at the URL
11
+	 * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
12
+	 *
13
+	 * @category  HTTP
14
+	 * @package   HTTP_Request2
15
+	 * @author    Alexey Borzov <[email protected]>
16
+	 * @copyright 2008-2014 Alexey Borzov <[email protected]>
17
+	 * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
18
+	 * @link      http://pear.php.net/package/HTTP_Request2
19
+	 */
20 20
 
21 21
 /**
22 22
  * Exception class for HTTP_Request2 package
@@ -53,579 +53,579 @@  discard block
 block discarded – undo
53 53
  */
54 54
 class HTTP_Request2_Response
55 55
 {
56
-    /**
57
-     * HTTP protocol version (e.g. 1.0, 1.1)
58
-     * @var  string
59
-     */
60
-    protected $version;
61
-
62
-    /**
63
-     * Status code
64
-     * @var  integer
65
-     * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
66
-     */
67
-    protected $code;
68
-
69
-    /**
70
-     * Reason phrase
71
-     * @var  string
72
-     * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
73
-     */
74
-    protected $reasonPhrase;
75
-
76
-    /**
77
-     * Effective URL (may be different from original request URL in case of redirects)
78
-     * @var  string
79
-     */
80
-    protected $effectiveUrl;
81
-
82
-    /**
83
-     * Associative array of response headers
84
-     * @var  array
85
-     */
86
-    protected $headers = array();
87
-
88
-    /**
89
-     * Cookies set in the response
90
-     * @var  array
91
-     */
92
-    protected $cookies = array();
93
-
94
-    /**
95
-     * Name of last header processed by parseHederLine()
96
-     *
97
-     * Used to handle the headers that span multiple lines
98
-     *
99
-     * @var  string
100
-     */
101
-    protected $lastHeader = null;
102
-
103
-    /**
104
-     * Response body
105
-     * @var  string
106
-     */
107
-    protected $body = '';
108
-
109
-    /**
110
-     * Whether the body is still encoded by Content-Encoding
111
-     *
112
-     * cURL provides the decoded body to the callback; if we are reading from
113
-     * socket the body is still gzipped / deflated
114
-     *
115
-     * @var  bool
116
-     */
117
-    protected $bodyEncoded;
118
-
119
-    /**
120
-     * Associative array of HTTP status code / reason phrase.
121
-     *
122
-     * @var  array
123
-     * @link http://tools.ietf.org/html/rfc2616#section-10
124
-     */
125
-    protected static $phrases = array(
126
-
127
-        // 1xx: Informational - Request received, continuing process
128
-        100 => 'Continue',
129
-        101 => 'Switching Protocols',
130
-
131
-        // 2xx: Success - The action was successfully received, understood and
132
-        // accepted
133
-        200 => 'OK',
134
-        201 => 'Created',
135
-        202 => 'Accepted',
136
-        203 => 'Non-Authoritative Information',
137
-        204 => 'No Content',
138
-        205 => 'Reset Content',
139
-        206 => 'Partial Content',
140
-
141
-        // 3xx: Redirection - Further action must be taken in order to complete
142
-        // the request
143
-        300 => 'Multiple Choices',
144
-        301 => 'Moved Permanently',
145
-        302 => 'Found',  // 1.1
146
-        303 => 'See Other',
147
-        304 => 'Not Modified',
148
-        305 => 'Use Proxy',
149
-        307 => 'Temporary Redirect',
150
-
151
-        // 4xx: Client Error - The request contains bad syntax or cannot be
152
-        // fulfilled
153
-        400 => 'Bad Request',
154
-        401 => 'Unauthorized',
155
-        402 => 'Payment Required',
156
-        403 => 'Forbidden',
157
-        404 => 'Not Found',
158
-        405 => 'Method Not Allowed',
159
-        406 => 'Not Acceptable',
160
-        407 => 'Proxy Authentication Required',
161
-        408 => 'Request Timeout',
162
-        409 => 'Conflict',
163
-        410 => 'Gone',
164
-        411 => 'Length Required',
165
-        412 => 'Precondition Failed',
166
-        413 => 'Request Entity Too Large',
167
-        414 => 'Request-URI Too Long',
168
-        415 => 'Unsupported Media Type',
169
-        416 => 'Requested Range Not Satisfiable',
170
-        417 => 'Expectation Failed',
171
-
172
-        // 5xx: Server Error - The server failed to fulfill an apparently
173
-        // valid request
174
-        500 => 'Internal Server Error',
175
-        501 => 'Not Implemented',
176
-        502 => 'Bad Gateway',
177
-        503 => 'Service Unavailable',
178
-        504 => 'Gateway Timeout',
179
-        505 => 'HTTP Version Not Supported',
180
-        509 => 'Bandwidth Limit Exceeded',
181
-
182
-    );
183
-
184
-    /**
185
-     * Returns the default reason phrase for the given code or all reason phrases
186
-     *
187
-     * @param int $code Response code
188
-     *
189
-     * @return string|array|null Default reason phrase for $code if $code is given
190
-     *                           (null if no phrase is available), array of all
191
-     *                           reason phrases if $code is null
192
-     * @link   http://pear.php.net/bugs/18716
193
-     */
194
-    public static function getDefaultReasonPhrase($code = null)
195
-    {
196
-        if (null === $code) {
197
-            return self::$phrases;
198
-        } else {
199
-            return isset(self::$phrases[$code]) ? self::$phrases[$code] : null;
200
-        }
201
-    }
202
-
203
-    /**
204
-     * Constructor, parses the response status line
205
-     *
206
-     * @param string $statusLine   Response status line (e.g. "HTTP/1.1 200 OK")
207
-     * @param bool   $bodyEncoded  Whether body is still encoded by Content-Encoding
208
-     * @param string $effectiveUrl Effective URL of the response
209
-     *
210
-     * @throws   HTTP_Request2_MessageException if status line is invalid according to spec
211
-     */
212
-    public function __construct($statusLine, $bodyEncoded = true, $effectiveUrl = null)
213
-    {
214
-        if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {
215
-            throw new HTTP_Request2_MessageException(
216
-                "Malformed response: {$statusLine}",
217
-                HTTP_Request2_Exception::MALFORMED_RESPONSE
218
-            );
219
-        }
220
-        $this->version      = $m[1];
221
-        $this->code         = intval($m[2]);
222
-        $this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);
223
-        $this->bodyEncoded  = (bool)$bodyEncoded;
224
-        $this->effectiveUrl = (string)$effectiveUrl;
225
-    }
226
-
227
-    /**
228
-     * Parses the line from HTTP response filling $headers array
229
-     *
230
-     * The method should be called after reading the line from socket or receiving
231
-     * it into cURL callback. Passing an empty string here indicates the end of
232
-     * response headers and triggers additional processing, so be sure to pass an
233
-     * empty string in the end.
234
-     *
235
-     * @param string $headerLine Line from HTTP response
236
-     */
237
-    public function parseHeaderLine($headerLine)
238
-    {
239
-        $headerLine = trim($headerLine, "\r\n");
240
-
241
-        if ('' == $headerLine) {
242
-            // empty string signals the end of headers, process the received ones
243
-            if (!empty($this->headers['set-cookie'])) {
244
-                $cookies = is_array($this->headers['set-cookie'])?
245
-                           $this->headers['set-cookie']:
246
-                           array($this->headers['set-cookie']);
247
-                foreach ($cookies as $cookieString) {
248
-                    $this->parseCookie($cookieString);
249
-                }
250
-                unset($this->headers['set-cookie']);
251
-            }
252
-            foreach (array_keys($this->headers) as $k) {
253
-                if (is_array($this->headers[$k])) {
254
-                    $this->headers[$k] = implode(', ', $this->headers[$k]);
255
-                }
256
-            }
257
-
258
-        } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {
259
-            // string of the form header-name: header value
260
-            $name  = strtolower($m[1]);
261
-            $value = trim($m[2]);
262
-            if (empty($this->headers[$name])) {
263
-                $this->headers[$name] = $value;
264
-            } else {
265
-                if (!is_array($this->headers[$name])) {
266
-                    $this->headers[$name] = array($this->headers[$name]);
267
-                }
268
-                $this->headers[$name][] = $value;
269
-            }
270
-            $this->lastHeader = $name;
271
-
272
-        } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {
273
-            // continuation of a previous header
274
-            if (!is_array($this->headers[$this->lastHeader])) {
275
-                $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);
276
-            } else {
277
-                $key = count($this->headers[$this->lastHeader]) - 1;
278
-                $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);
279
-            }
280
-        }
281
-    }
282
-
283
-    /**
284
-     * Parses a Set-Cookie header to fill $cookies array
285
-     *
286
-     * @param string $cookieString value of Set-Cookie header
287
-     *
288
-     * @link     http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
289
-     */
290
-    protected function parseCookie($cookieString)
291
-    {
292
-        $cookie = array(
293
-            'expires' => null,
294
-            'domain'  => null,
295
-            'path'    => null,
296
-            'secure'  => false
297
-        );
298
-
299
-        if (!strpos($cookieString, ';')) {
300
-            // Only a name=value pair
301
-            $pos = strpos($cookieString, '=');
302
-            $cookie['name']  = trim(substr($cookieString, 0, $pos));
303
-            $cookie['value'] = trim(substr($cookieString, $pos + 1));
304
-
305
-        } else {
306
-            // Some optional parameters are supplied
307
-            $elements = explode(';', $cookieString);
308
-            $pos = strpos($elements[0], '=');
309
-            $cookie['name']  = trim(substr($elements[0], 0, $pos));
310
-            $cookie['value'] = trim(substr($elements[0], $pos + 1));
311
-
312
-            for ($i = 1; $i < count($elements); $i++) {
313
-                if (false === strpos($elements[$i], '=')) {
314
-                    $elName  = trim($elements[$i]);
315
-                    $elValue = null;
316
-                } else {
317
-                    list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
318
-                }
319
-                $elName = strtolower($elName);
320
-                if ('secure' == $elName) {
321
-                    $cookie['secure'] = true;
322
-                } elseif ('expires' == $elName) {
323
-                    $cookie['expires'] = str_replace('"', '', $elValue);
324
-                } elseif ('path' == $elName || 'domain' == $elName) {
325
-                    $cookie[$elName] = urldecode($elValue);
326
-                } else {
327
-                    $cookie[$elName] = $elValue;
328
-                }
329
-            }
330
-        }
331
-        $this->cookies[] = $cookie;
332
-    }
333
-
334
-    /**
335
-     * Appends a string to the response body
336
-     *
337
-     * @param string $bodyChunk part of response body
338
-     */
339
-    public function appendBody($bodyChunk)
340
-    {
341
-        $this->body .= $bodyChunk;
342
-    }
343
-
344
-    /**
345
-     * Returns the effective URL of the response
346
-     *
347
-     * This may be different from the request URL if redirects were followed.
348
-     *
349
-     * @return string
350
-     * @link   http://pear.php.net/bugs/bug.php?id=18412
351
-     */
352
-    public function getEffectiveUrl()
353
-    {
354
-        return $this->effectiveUrl;
355
-    }
356
-
357
-    /**
358
-     * Returns the status code
359
-     *
360
-     * @return   integer
361
-     */
362
-    public function getStatus()
363
-    {
364
-        return $this->code;
365
-    }
366
-
367
-    /**
368
-     * Returns the reason phrase
369
-     *
370
-     * @return   string
371
-     */
372
-    public function getReasonPhrase()
373
-    {
374
-        return $this->reasonPhrase;
375
-    }
376
-
377
-    /**
378
-     * Whether response is a redirect that can be automatically handled by HTTP_Request2
379
-     *
380
-     * @return   bool
381
-     */
382
-    public function isRedirect()
383
-    {
384
-        return in_array($this->code, array(300, 301, 302, 303, 307))
385
-               && isset($this->headers['location']);
386
-    }
387
-
388
-    /**
389
-     * Returns either the named header or all response headers
390
-     *
391
-     * @param string $headerName Name of header to return
392
-     *
393
-     * @return   string|array    Value of $headerName header (null if header is
394
-     *                           not present), array of all response headers if
395
-     *                           $headerName is null
396
-     */
397
-    public function getHeader($headerName = null)
398
-    {
399
-        if (null === $headerName) {
400
-            return $this->headers;
401
-        } else {
402
-            $headerName = strtolower($headerName);
403
-            return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
404
-        }
405
-    }
406
-
407
-    /**
408
-     * Returns cookies set in response
409
-     *
410
-     * @return   array
411
-     */
412
-    public function getCookies()
413
-    {
414
-        return $this->cookies;
415
-    }
416
-
417
-    /**
418
-     * Returns the body of the response
419
-     *
420
-     * @return   string
421
-     * @throws   HTTP_Request2_Exception if body cannot be decoded
422
-     */
423
-    public function getBody()
424
-    {
425
-        if (0 == strlen($this->body) || !$this->bodyEncoded
426
-            || !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))
427
-        ) {
428
-            return $this->body;
429
-
430
-        } else {
431
-            if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
432
-                $oldEncoding = mb_internal_encoding();
433
-                mb_internal_encoding('8bit');
434
-            }
435
-
436
-            try {
437
-                switch (strtolower($this->getHeader('content-encoding'))) {
438
-                case 'gzip':
439
-                    $decoded = self::decodeGzip($this->body);
440
-                    break;
441
-                case 'deflate':
442
-                    $decoded = self::decodeDeflate($this->body);
443
-                }
444
-            } catch (Exception $e) {
445
-            }
446
-
447
-            if (!empty($oldEncoding)) {
448
-                mb_internal_encoding($oldEncoding);
449
-            }
450
-            if (!empty($e)) {
451
-                throw $e;
452
-            }
453
-            return $decoded;
454
-        }
455
-    }
456
-
457
-    /**
458
-     * Get the HTTP version of the response
459
-     *
460
-     * @return   string
461
-     */
462
-    public function getVersion()
463
-    {
464
-        return $this->version;
465
-    }
466
-
467
-    /**
468
-     * Decodes the message-body encoded by gzip
469
-     *
470
-     * The real decoding work is done by gzinflate() built-in function, this
471
-     * method only parses the header and checks data for compliance with
472
-     * RFC 1952
473
-     *
474
-     * @param string $data gzip-encoded data
475
-     *
476
-     * @return   string  decoded data
477
-     * @throws   HTTP_Request2_LogicException
478
-     * @throws   HTTP_Request2_MessageException
479
-     * @link     http://tools.ietf.org/html/rfc1952
480
-     */
481
-    public static function decodeGzip($data)
482
-    {
483
-        $length = strlen($data);
484
-        // If it doesn't look like gzip-encoded data, don't bother
485
-        if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
486
-            return $data;
487
-        }
488
-        if (!function_exists('gzinflate')) {
489
-            throw new HTTP_Request2_LogicException(
490
-                'Unable to decode body: gzip extension not available',
491
-                HTTP_Request2_Exception::MISCONFIGURATION
492
-            );
493
-        }
494
-        $method = ord(substr($data, 2, 1));
495
-        if (8 != $method) {
496
-            throw new HTTP_Request2_MessageException(
497
-                'Error parsing gzip header: unknown compression method',
498
-                HTTP_Request2_Exception::DECODE_ERROR
499
-            );
500
-        }
501
-        $flags = ord(substr($data, 3, 1));
502
-        if ($flags & 224) {
503
-            throw new HTTP_Request2_MessageException(
504
-                'Error parsing gzip header: reserved bits are set',
505
-                HTTP_Request2_Exception::DECODE_ERROR
506
-            );
507
-        }
508
-
509
-        // header is 10 bytes minimum. may be longer, though.
510
-        $headerLength = 10;
511
-        // extra fields, need to skip 'em
512
-        if ($flags & 4) {
513
-            if ($length - $headerLength - 2 < 8) {
514
-                throw new HTTP_Request2_MessageException(
515
-                    'Error parsing gzip header: data too short',
516
-                    HTTP_Request2_Exception::DECODE_ERROR
517
-                );
518
-            }
519
-            $extraLength = unpack('v', substr($data, 10, 2));
520
-            if ($length - $headerLength - 2 - $extraLength[1] < 8) {
521
-                throw new HTTP_Request2_MessageException(
522
-                    'Error parsing gzip header: data too short',
523
-                    HTTP_Request2_Exception::DECODE_ERROR
524
-                );
525
-            }
526
-            $headerLength += $extraLength[1] + 2;
527
-        }
528
-        // file name, need to skip that
529
-        if ($flags & 8) {
530
-            if ($length - $headerLength - 1 < 8) {
531
-                throw new HTTP_Request2_MessageException(
532
-                    'Error parsing gzip header: data too short',
533
-                    HTTP_Request2_Exception::DECODE_ERROR
534
-                );
535
-            }
536
-            $filenameLength = strpos(substr($data, $headerLength), chr(0));
537
-            if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
538
-                throw new HTTP_Request2_MessageException(
539
-                    'Error parsing gzip header: data too short',
540
-                    HTTP_Request2_Exception::DECODE_ERROR
541
-                );
542
-            }
543
-            $headerLength += $filenameLength + 1;
544
-        }
545
-        // comment, need to skip that also
546
-        if ($flags & 16) {
547
-            if ($length - $headerLength - 1 < 8) {
548
-                throw new HTTP_Request2_MessageException(
549
-                    'Error parsing gzip header: data too short',
550
-                    HTTP_Request2_Exception::DECODE_ERROR
551
-                );
552
-            }
553
-            $commentLength = strpos(substr($data, $headerLength), chr(0));
554
-            if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
555
-                throw new HTTP_Request2_MessageException(
556
-                    'Error parsing gzip header: data too short',
557
-                    HTTP_Request2_Exception::DECODE_ERROR
558
-                );
559
-            }
560
-            $headerLength += $commentLength + 1;
561
-        }
562
-        // have a CRC for header. let's check
563
-        if ($flags & 2) {
564
-            if ($length - $headerLength - 2 < 8) {
565
-                throw new HTTP_Request2_MessageException(
566
-                    'Error parsing gzip header: data too short',
567
-                    HTTP_Request2_Exception::DECODE_ERROR
568
-                );
569
-            }
570
-            $crcReal   = 0xffff & crc32(substr($data, 0, $headerLength));
571
-            $crcStored = unpack('v', substr($data, $headerLength, 2));
572
-            if ($crcReal != $crcStored[1]) {
573
-                throw new HTTP_Request2_MessageException(
574
-                    'Header CRC check failed',
575
-                    HTTP_Request2_Exception::DECODE_ERROR
576
-                );
577
-            }
578
-            $headerLength += 2;
579
-        }
580
-        // unpacked data CRC and size at the end of encoded data
581
-        $tmp = unpack('V2', substr($data, -8));
582
-        $dataCrc  = $tmp[1];
583
-        $dataSize = $tmp[2];
584
-
585
-        // finally, call the gzinflate() function
586
-        // don't pass $dataSize to gzinflate, see bugs #13135, #14370
587
-        $unpacked = gzinflate(substr($data, $headerLength, -8));
588
-        if (false === $unpacked) {
589
-            throw new HTTP_Request2_MessageException(
590
-                'gzinflate() call failed',
591
-                HTTP_Request2_Exception::DECODE_ERROR
592
-            );
593
-        } elseif ($dataSize != strlen($unpacked)) {
594
-            throw new HTTP_Request2_MessageException(
595
-                'Data size check failed',
596
-                HTTP_Request2_Exception::DECODE_ERROR
597
-            );
598
-        } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
599
-            throw new HTTP_Request2_Exception(
600
-                'Data CRC check failed',
601
-                HTTP_Request2_Exception::DECODE_ERROR
602
-            );
603
-        }
604
-        return $unpacked;
605
-    }
606
-
607
-    /**
608
-     * Decodes the message-body encoded by deflate
609
-     *
610
-     * @param string $data deflate-encoded data
611
-     *
612
-     * @return   string  decoded data
613
-     * @throws   HTTP_Request2_LogicException
614
-     */
615
-    public static function decodeDeflate($data)
616
-    {
617
-        if (!function_exists('gzuncompress')) {
618
-            throw new HTTP_Request2_LogicException(
619
-                'Unable to decode body: gzip extension not available',
620
-                HTTP_Request2_Exception::MISCONFIGURATION
621
-            );
622
-        }
623
-        // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
624
-        // while many applications send raw deflate stream from RFC 1951.
625
-        // We should check for presence of zlib header and use gzuncompress() or
626
-        // gzinflate() as needed. See bug #15305
627
-        $header = unpack('n', substr($data, 0, 2));
628
-        return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
629
-    }
56
+	/**
57
+	 * HTTP protocol version (e.g. 1.0, 1.1)
58
+	 * @var  string
59
+	 */
60
+	protected $version;
61
+
62
+	/**
63
+	 * Status code
64
+	 * @var  integer
65
+	 * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
66
+	 */
67
+	protected $code;
68
+
69
+	/**
70
+	 * Reason phrase
71
+	 * @var  string
72
+	 * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
73
+	 */
74
+	protected $reasonPhrase;
75
+
76
+	/**
77
+	 * Effective URL (may be different from original request URL in case of redirects)
78
+	 * @var  string
79
+	 */
80
+	protected $effectiveUrl;
81
+
82
+	/**
83
+	 * Associative array of response headers
84
+	 * @var  array
85
+	 */
86
+	protected $headers = array();
87
+
88
+	/**
89
+	 * Cookies set in the response
90
+	 * @var  array
91
+	 */
92
+	protected $cookies = array();
93
+
94
+	/**
95
+	 * Name of last header processed by parseHederLine()
96
+	 *
97
+	 * Used to handle the headers that span multiple lines
98
+	 *
99
+	 * @var  string
100
+	 */
101
+	protected $lastHeader = null;
102
+
103
+	/**
104
+	 * Response body
105
+	 * @var  string
106
+	 */
107
+	protected $body = '';
108
+
109
+	/**
110
+	 * Whether the body is still encoded by Content-Encoding
111
+	 *
112
+	 * cURL provides the decoded body to the callback; if we are reading from
113
+	 * socket the body is still gzipped / deflated
114
+	 *
115
+	 * @var  bool
116
+	 */
117
+	protected $bodyEncoded;
118
+
119
+	/**
120
+	 * Associative array of HTTP status code / reason phrase.
121
+	 *
122
+	 * @var  array
123
+	 * @link http://tools.ietf.org/html/rfc2616#section-10
124
+	 */
125
+	protected static $phrases = array(
126
+
127
+		// 1xx: Informational - Request received, continuing process
128
+		100 => 'Continue',
129
+		101 => 'Switching Protocols',
130
+
131
+		// 2xx: Success - The action was successfully received, understood and
132
+		// accepted
133
+		200 => 'OK',
134
+		201 => 'Created',
135
+		202 => 'Accepted',
136
+		203 => 'Non-Authoritative Information',
137
+		204 => 'No Content',
138
+		205 => 'Reset Content',
139
+		206 => 'Partial Content',
140
+
141
+		// 3xx: Redirection - Further action must be taken in order to complete
142
+		// the request
143
+		300 => 'Multiple Choices',
144
+		301 => 'Moved Permanently',
145
+		302 => 'Found',  // 1.1
146
+		303 => 'See Other',
147
+		304 => 'Not Modified',
148
+		305 => 'Use Proxy',
149
+		307 => 'Temporary Redirect',
150
+
151
+		// 4xx: Client Error - The request contains bad syntax or cannot be
152
+		// fulfilled
153
+		400 => 'Bad Request',
154
+		401 => 'Unauthorized',
155
+		402 => 'Payment Required',
156
+		403 => 'Forbidden',
157
+		404 => 'Not Found',
158
+		405 => 'Method Not Allowed',
159
+		406 => 'Not Acceptable',
160
+		407 => 'Proxy Authentication Required',
161
+		408 => 'Request Timeout',
162
+		409 => 'Conflict',
163
+		410 => 'Gone',
164
+		411 => 'Length Required',
165
+		412 => 'Precondition Failed',
166
+		413 => 'Request Entity Too Large',
167
+		414 => 'Request-URI Too Long',
168
+		415 => 'Unsupported Media Type',
169
+		416 => 'Requested Range Not Satisfiable',
170
+		417 => 'Expectation Failed',
171
+
172
+		// 5xx: Server Error - The server failed to fulfill an apparently
173
+		// valid request
174
+		500 => 'Internal Server Error',
175
+		501 => 'Not Implemented',
176
+		502 => 'Bad Gateway',
177
+		503 => 'Service Unavailable',
178
+		504 => 'Gateway Timeout',
179
+		505 => 'HTTP Version Not Supported',
180
+		509 => 'Bandwidth Limit Exceeded',
181
+
182
+	);
183
+
184
+	/**
185
+	 * Returns the default reason phrase for the given code or all reason phrases
186
+	 *
187
+	 * @param int $code Response code
188
+	 *
189
+	 * @return string|array|null Default reason phrase for $code if $code is given
190
+	 *                           (null if no phrase is available), array of all
191
+	 *                           reason phrases if $code is null
192
+	 * @link   http://pear.php.net/bugs/18716
193
+	 */
194
+	public static function getDefaultReasonPhrase($code = null)
195
+	{
196
+		if (null === $code) {
197
+			return self::$phrases;
198
+		} else {
199
+			return isset(self::$phrases[$code]) ? self::$phrases[$code] : null;
200
+		}
201
+	}
202
+
203
+	/**
204
+	 * Constructor, parses the response status line
205
+	 *
206
+	 * @param string $statusLine   Response status line (e.g. "HTTP/1.1 200 OK")
207
+	 * @param bool   $bodyEncoded  Whether body is still encoded by Content-Encoding
208
+	 * @param string $effectiveUrl Effective URL of the response
209
+	 *
210
+	 * @throws   HTTP_Request2_MessageException if status line is invalid according to spec
211
+	 */
212
+	public function __construct($statusLine, $bodyEncoded = true, $effectiveUrl = null)
213
+	{
214
+		if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {
215
+			throw new HTTP_Request2_MessageException(
216
+				"Malformed response: {$statusLine}",
217
+				HTTP_Request2_Exception::MALFORMED_RESPONSE
218
+			);
219
+		}
220
+		$this->version      = $m[1];
221
+		$this->code         = intval($m[2]);
222
+		$this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);
223
+		$this->bodyEncoded  = (bool)$bodyEncoded;
224
+		$this->effectiveUrl = (string)$effectiveUrl;
225
+	}
226
+
227
+	/**
228
+	 * Parses the line from HTTP response filling $headers array
229
+	 *
230
+	 * The method should be called after reading the line from socket or receiving
231
+	 * it into cURL callback. Passing an empty string here indicates the end of
232
+	 * response headers and triggers additional processing, so be sure to pass an
233
+	 * empty string in the end.
234
+	 *
235
+	 * @param string $headerLine Line from HTTP response
236
+	 */
237
+	public function parseHeaderLine($headerLine)
238
+	{
239
+		$headerLine = trim($headerLine, "\r\n");
240
+
241
+		if ('' == $headerLine) {
242
+			// empty string signals the end of headers, process the received ones
243
+			if (!empty($this->headers['set-cookie'])) {
244
+				$cookies = is_array($this->headers['set-cookie'])?
245
+						   $this->headers['set-cookie']:
246
+						   array($this->headers['set-cookie']);
247
+				foreach ($cookies as $cookieString) {
248
+					$this->parseCookie($cookieString);
249
+				}
250
+				unset($this->headers['set-cookie']);
251
+			}
252
+			foreach (array_keys($this->headers) as $k) {
253
+				if (is_array($this->headers[$k])) {
254
+					$this->headers[$k] = implode(', ', $this->headers[$k]);
255
+				}
256
+			}
257
+
258
+		} elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {
259
+			// string of the form header-name: header value
260
+			$name  = strtolower($m[1]);
261
+			$value = trim($m[2]);
262
+			if (empty($this->headers[$name])) {
263
+				$this->headers[$name] = $value;
264
+			} else {
265
+				if (!is_array($this->headers[$name])) {
266
+					$this->headers[$name] = array($this->headers[$name]);
267
+				}
268
+				$this->headers[$name][] = $value;
269
+			}
270
+			$this->lastHeader = $name;
271
+
272
+		} elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {
273
+			// continuation of a previous header
274
+			if (!is_array($this->headers[$this->lastHeader])) {
275
+				$this->headers[$this->lastHeader] .= ' ' . trim($m[1]);
276
+			} else {
277
+				$key = count($this->headers[$this->lastHeader]) - 1;
278
+				$this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);
279
+			}
280
+		}
281
+	}
282
+
283
+	/**
284
+	 * Parses a Set-Cookie header to fill $cookies array
285
+	 *
286
+	 * @param string $cookieString value of Set-Cookie header
287
+	 *
288
+	 * @link     http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
289
+	 */
290
+	protected function parseCookie($cookieString)
291
+	{
292
+		$cookie = array(
293
+			'expires' => null,
294
+			'domain'  => null,
295
+			'path'    => null,
296
+			'secure'  => false
297
+		);
298
+
299
+		if (!strpos($cookieString, ';')) {
300
+			// Only a name=value pair
301
+			$pos = strpos($cookieString, '=');
302
+			$cookie['name']  = trim(substr($cookieString, 0, $pos));
303
+			$cookie['value'] = trim(substr($cookieString, $pos + 1));
304
+
305
+		} else {
306
+			// Some optional parameters are supplied
307
+			$elements = explode(';', $cookieString);
308
+			$pos = strpos($elements[0], '=');
309
+			$cookie['name']  = trim(substr($elements[0], 0, $pos));
310
+			$cookie['value'] = trim(substr($elements[0], $pos + 1));
311
+
312
+			for ($i = 1; $i < count($elements); $i++) {
313
+				if (false === strpos($elements[$i], '=')) {
314
+					$elName  = trim($elements[$i]);
315
+					$elValue = null;
316
+				} else {
317
+					list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
318
+				}
319
+				$elName = strtolower($elName);
320
+				if ('secure' == $elName) {
321
+					$cookie['secure'] = true;
322
+				} elseif ('expires' == $elName) {
323
+					$cookie['expires'] = str_replace('"', '', $elValue);
324
+				} elseif ('path' == $elName || 'domain' == $elName) {
325
+					$cookie[$elName] = urldecode($elValue);
326
+				} else {
327
+					$cookie[$elName] = $elValue;
328
+				}
329
+			}
330
+		}
331
+		$this->cookies[] = $cookie;
332
+	}
333
+
334
+	/**
335
+	 * Appends a string to the response body
336
+	 *
337
+	 * @param string $bodyChunk part of response body
338
+	 */
339
+	public function appendBody($bodyChunk)
340
+	{
341
+		$this->body .= $bodyChunk;
342
+	}
343
+
344
+	/**
345
+	 * Returns the effective URL of the response
346
+	 *
347
+	 * This may be different from the request URL if redirects were followed.
348
+	 *
349
+	 * @return string
350
+	 * @link   http://pear.php.net/bugs/bug.php?id=18412
351
+	 */
352
+	public function getEffectiveUrl()
353
+	{
354
+		return $this->effectiveUrl;
355
+	}
356
+
357
+	/**
358
+	 * Returns the status code
359
+	 *
360
+	 * @return   integer
361
+	 */
362
+	public function getStatus()
363
+	{
364
+		return $this->code;
365
+	}
366
+
367
+	/**
368
+	 * Returns the reason phrase
369
+	 *
370
+	 * @return   string
371
+	 */
372
+	public function getReasonPhrase()
373
+	{
374
+		return $this->reasonPhrase;
375
+	}
376
+
377
+	/**
378
+	 * Whether response is a redirect that can be automatically handled by HTTP_Request2
379
+	 *
380
+	 * @return   bool
381
+	 */
382
+	public function isRedirect()
383
+	{
384
+		return in_array($this->code, array(300, 301, 302, 303, 307))
385
+			   && isset($this->headers['location']);
386
+	}
387
+
388
+	/**
389
+	 * Returns either the named header or all response headers
390
+	 *
391
+	 * @param string $headerName Name of header to return
392
+	 *
393
+	 * @return   string|array    Value of $headerName header (null if header is
394
+	 *                           not present), array of all response headers if
395
+	 *                           $headerName is null
396
+	 */
397
+	public function getHeader($headerName = null)
398
+	{
399
+		if (null === $headerName) {
400
+			return $this->headers;
401
+		} else {
402
+			$headerName = strtolower($headerName);
403
+			return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
404
+		}
405
+	}
406
+
407
+	/**
408
+	 * Returns cookies set in response
409
+	 *
410
+	 * @return   array
411
+	 */
412
+	public function getCookies()
413
+	{
414
+		return $this->cookies;
415
+	}
416
+
417
+	/**
418
+	 * Returns the body of the response
419
+	 *
420
+	 * @return   string
421
+	 * @throws   HTTP_Request2_Exception if body cannot be decoded
422
+	 */
423
+	public function getBody()
424
+	{
425
+		if (0 == strlen($this->body) || !$this->bodyEncoded
426
+			|| !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))
427
+		) {
428
+			return $this->body;
429
+
430
+		} else {
431
+			if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
432
+				$oldEncoding = mb_internal_encoding();
433
+				mb_internal_encoding('8bit');
434
+			}
435
+
436
+			try {
437
+				switch (strtolower($this->getHeader('content-encoding'))) {
438
+				case 'gzip':
439
+					$decoded = self::decodeGzip($this->body);
440
+					break;
441
+				case 'deflate':
442
+					$decoded = self::decodeDeflate($this->body);
443
+				}
444
+			} catch (Exception $e) {
445
+			}
446
+
447
+			if (!empty($oldEncoding)) {
448
+				mb_internal_encoding($oldEncoding);
449
+			}
450
+			if (!empty($e)) {
451
+				throw $e;
452
+			}
453
+			return $decoded;
454
+		}
455
+	}
456
+
457
+	/**
458
+	 * Get the HTTP version of the response
459
+	 *
460
+	 * @return   string
461
+	 */
462
+	public function getVersion()
463
+	{
464
+		return $this->version;
465
+	}
466
+
467
+	/**
468
+	 * Decodes the message-body encoded by gzip
469
+	 *
470
+	 * The real decoding work is done by gzinflate() built-in function, this
471
+	 * method only parses the header and checks data for compliance with
472
+	 * RFC 1952
473
+	 *
474
+	 * @param string $data gzip-encoded data
475
+	 *
476
+	 * @return   string  decoded data
477
+	 * @throws   HTTP_Request2_LogicException
478
+	 * @throws   HTTP_Request2_MessageException
479
+	 * @link     http://tools.ietf.org/html/rfc1952
480
+	 */
481
+	public static function decodeGzip($data)
482
+	{
483
+		$length = strlen($data);
484
+		// If it doesn't look like gzip-encoded data, don't bother
485
+		if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
486
+			return $data;
487
+		}
488
+		if (!function_exists('gzinflate')) {
489
+			throw new HTTP_Request2_LogicException(
490
+				'Unable to decode body: gzip extension not available',
491
+				HTTP_Request2_Exception::MISCONFIGURATION
492
+			);
493
+		}
494
+		$method = ord(substr($data, 2, 1));
495
+		if (8 != $method) {
496
+			throw new HTTP_Request2_MessageException(
497
+				'Error parsing gzip header: unknown compression method',
498
+				HTTP_Request2_Exception::DECODE_ERROR
499
+			);
500
+		}
501
+		$flags = ord(substr($data, 3, 1));
502
+		if ($flags & 224) {
503
+			throw new HTTP_Request2_MessageException(
504
+				'Error parsing gzip header: reserved bits are set',
505
+				HTTP_Request2_Exception::DECODE_ERROR
506
+			);
507
+		}
508
+
509
+		// header is 10 bytes minimum. may be longer, though.
510
+		$headerLength = 10;
511
+		// extra fields, need to skip 'em
512
+		if ($flags & 4) {
513
+			if ($length - $headerLength - 2 < 8) {
514
+				throw new HTTP_Request2_MessageException(
515
+					'Error parsing gzip header: data too short',
516
+					HTTP_Request2_Exception::DECODE_ERROR
517
+				);
518
+			}
519
+			$extraLength = unpack('v', substr($data, 10, 2));
520
+			if ($length - $headerLength - 2 - $extraLength[1] < 8) {
521
+				throw new HTTP_Request2_MessageException(
522
+					'Error parsing gzip header: data too short',
523
+					HTTP_Request2_Exception::DECODE_ERROR
524
+				);
525
+			}
526
+			$headerLength += $extraLength[1] + 2;
527
+		}
528
+		// file name, need to skip that
529
+		if ($flags & 8) {
530
+			if ($length - $headerLength - 1 < 8) {
531
+				throw new HTTP_Request2_MessageException(
532
+					'Error parsing gzip header: data too short',
533
+					HTTP_Request2_Exception::DECODE_ERROR
534
+				);
535
+			}
536
+			$filenameLength = strpos(substr($data, $headerLength), chr(0));
537
+			if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
538
+				throw new HTTP_Request2_MessageException(
539
+					'Error parsing gzip header: data too short',
540
+					HTTP_Request2_Exception::DECODE_ERROR
541
+				);
542
+			}
543
+			$headerLength += $filenameLength + 1;
544
+		}
545
+		// comment, need to skip that also
546
+		if ($flags & 16) {
547
+			if ($length - $headerLength - 1 < 8) {
548
+				throw new HTTP_Request2_MessageException(
549
+					'Error parsing gzip header: data too short',
550
+					HTTP_Request2_Exception::DECODE_ERROR
551
+				);
552
+			}
553
+			$commentLength = strpos(substr($data, $headerLength), chr(0));
554
+			if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
555
+				throw new HTTP_Request2_MessageException(
556
+					'Error parsing gzip header: data too short',
557
+					HTTP_Request2_Exception::DECODE_ERROR
558
+				);
559
+			}
560
+			$headerLength += $commentLength + 1;
561
+		}
562
+		// have a CRC for header. let's check
563
+		if ($flags & 2) {
564
+			if ($length - $headerLength - 2 < 8) {
565
+				throw new HTTP_Request2_MessageException(
566
+					'Error parsing gzip header: data too short',
567
+					HTTP_Request2_Exception::DECODE_ERROR
568
+				);
569
+			}
570
+			$crcReal   = 0xffff & crc32(substr($data, 0, $headerLength));
571
+			$crcStored = unpack('v', substr($data, $headerLength, 2));
572
+			if ($crcReal != $crcStored[1]) {
573
+				throw new HTTP_Request2_MessageException(
574
+					'Header CRC check failed',
575
+					HTTP_Request2_Exception::DECODE_ERROR
576
+				);
577
+			}
578
+			$headerLength += 2;
579
+		}
580
+		// unpacked data CRC and size at the end of encoded data
581
+		$tmp = unpack('V2', substr($data, -8));
582
+		$dataCrc  = $tmp[1];
583
+		$dataSize = $tmp[2];
584
+
585
+		// finally, call the gzinflate() function
586
+		// don't pass $dataSize to gzinflate, see bugs #13135, #14370
587
+		$unpacked = gzinflate(substr($data, $headerLength, -8));
588
+		if (false === $unpacked) {
589
+			throw new HTTP_Request2_MessageException(
590
+				'gzinflate() call failed',
591
+				HTTP_Request2_Exception::DECODE_ERROR
592
+			);
593
+		} elseif ($dataSize != strlen($unpacked)) {
594
+			throw new HTTP_Request2_MessageException(
595
+				'Data size check failed',
596
+				HTTP_Request2_Exception::DECODE_ERROR
597
+			);
598
+		} elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
599
+			throw new HTTP_Request2_Exception(
600
+				'Data CRC check failed',
601
+				HTTP_Request2_Exception::DECODE_ERROR
602
+			);
603
+		}
604
+		return $unpacked;
605
+	}
606
+
607
+	/**
608
+	 * Decodes the message-body encoded by deflate
609
+	 *
610
+	 * @param string $data deflate-encoded data
611
+	 *
612
+	 * @return   string  decoded data
613
+	 * @throws   HTTP_Request2_LogicException
614
+	 */
615
+	public static function decodeDeflate($data)
616
+	{
617
+		if (!function_exists('gzuncompress')) {
618
+			throw new HTTP_Request2_LogicException(
619
+				'Unable to decode body: gzip extension not available',
620
+				HTTP_Request2_Exception::MISCONFIGURATION
621
+			);
622
+		}
623
+		// RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
624
+		// while many applications send raw deflate stream from RFC 1951.
625
+		// We should check for presence of zlib header and use gzuncompress() or
626
+		// gzinflate() as needed. See bug #15305
627
+		$header = unpack('n', substr($data, 0, 2));
628
+		return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
629
+	}
630 630
 }
631 631
 ?>
632 632
\ No newline at end of file
Please login to merge, or discard this patch.
libs/PEAR.1.9.5/HTTP/Request2/SOCKS5.php 3 patches
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -1,22 +1,22 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * SOCKS5 proxy connection class
4
- *
5
- * PHP version 5
6
- *
7
- * LICENSE
8
- *
9
- * This source file is subject to BSD 3-Clause License that is bundled
10
- * with this package in the file LICENSE and available at the URL
11
- * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
12
- *
13
- * @category  HTTP
14
- * @package   HTTP_Request2
15
- * @author    Alexey Borzov <[email protected]>
16
- * @copyright 2008-2014 Alexey Borzov <[email protected]>
17
- * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
18
- * @link      http://pear.php.net/package/HTTP_Request2
19
- */
3
+	 * SOCKS5 proxy connection class
4
+	 *
5
+	 * PHP version 5
6
+	 *
7
+	 * LICENSE
8
+	 *
9
+	 * This source file is subject to BSD 3-Clause License that is bundled
10
+	 * with this package in the file LICENSE and available at the URL
11
+	 * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
12
+	 *
13
+	 * @category  HTTP
14
+	 * @package   HTTP_Request2
15
+	 * @author    Alexey Borzov <[email protected]>
16
+	 * @copyright 2008-2014 Alexey Borzov <[email protected]>
17
+	 * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
18
+	 * @link      http://pear.php.net/package/HTTP_Request2
19
+	 */
20 20
 
21 21
 /** Socket wrapper class used by Socket Adapter */
22 22
 require_once 'HTTP/Request2/SocketWrapper.php';
@@ -35,101 +35,101 @@  discard block
 block discarded – undo
35 35
  */
36 36
 class HTTP_Request2_SOCKS5 extends HTTP_Request2_SocketWrapper
37 37
 {
38
-    /**
39
-     * Constructor, tries to connect and authenticate to a SOCKS5 proxy
40
-     *
41
-     * @param string $address        Proxy address, e.g. 'tcp://localhost:1080'
42
-     * @param int    $timeout        Connection timeout (seconds)
43
-     * @param array  $contextOptions Stream context options
44
-     * @param string $username       Proxy user name
45
-     * @param string $password       Proxy password
46
-     *
47
-     * @throws HTTP_Request2_LogicException
48
-     * @throws HTTP_Request2_ConnectionException
49
-     * @throws HTTP_Request2_MessageException
50
-     */
51
-    public function __construct(
52
-        $address, $timeout = 10, array $contextOptions = array(),
53
-        $username = null, $password = null
54
-    ) {
55
-        parent::__construct($address, $timeout, $contextOptions);
38
+	/**
39
+	 * Constructor, tries to connect and authenticate to a SOCKS5 proxy
40
+	 *
41
+	 * @param string $address        Proxy address, e.g. 'tcp://localhost:1080'
42
+	 * @param int    $timeout        Connection timeout (seconds)
43
+	 * @param array  $contextOptions Stream context options
44
+	 * @param string $username       Proxy user name
45
+	 * @param string $password       Proxy password
46
+	 *
47
+	 * @throws HTTP_Request2_LogicException
48
+	 * @throws HTTP_Request2_ConnectionException
49
+	 * @throws HTTP_Request2_MessageException
50
+	 */
51
+	public function __construct(
52
+		$address, $timeout = 10, array $contextOptions = array(),
53
+		$username = null, $password = null
54
+	) {
55
+		parent::__construct($address, $timeout, $contextOptions);
56 56
 
57
-        if (strlen($username)) {
58
-            $request = pack('C4', 5, 2, 0, 2);
59
-        } else {
60
-            $request = pack('C3', 5, 1, 0);
61
-        }
62
-        $this->write($request);
63
-        $response = unpack('Cversion/Cmethod', $this->read(3));
64
-        if (5 != $response['version']) {
65
-            throw new HTTP_Request2_MessageException(
66
-                'Invalid version received from SOCKS5 proxy: ' . $response['version'],
67
-                HTTP_Request2_Exception::MALFORMED_RESPONSE
68
-            );
69
-        }
70
-        switch ($response['method']) {
71
-        case 2:
72
-            $this->performAuthentication($username, $password);
73
-        case 0:
74
-            break;
75
-        default:
76
-            throw new HTTP_Request2_ConnectionException(
77
-                "Connection rejected by proxy due to unsupported auth method"
78
-            );
79
-        }
80
-    }
57
+		if (strlen($username)) {
58
+			$request = pack('C4', 5, 2, 0, 2);
59
+		} else {
60
+			$request = pack('C3', 5, 1, 0);
61
+		}
62
+		$this->write($request);
63
+		$response = unpack('Cversion/Cmethod', $this->read(3));
64
+		if (5 != $response['version']) {
65
+			throw new HTTP_Request2_MessageException(
66
+				'Invalid version received from SOCKS5 proxy: ' . $response['version'],
67
+				HTTP_Request2_Exception::MALFORMED_RESPONSE
68
+			);
69
+		}
70
+		switch ($response['method']) {
71
+		case 2:
72
+			$this->performAuthentication($username, $password);
73
+		case 0:
74
+			break;
75
+		default:
76
+			throw new HTTP_Request2_ConnectionException(
77
+				"Connection rejected by proxy due to unsupported auth method"
78
+			);
79
+		}
80
+	}
81 81
 
82
-    /**
83
-     * Performs username/password authentication for SOCKS5
84
-     *
85
-     * @param string $username Proxy user name
86
-     * @param string $password Proxy password
87
-     *
88
-     * @throws HTTP_Request2_ConnectionException
89
-     * @throws HTTP_Request2_MessageException
90
-     * @link http://tools.ietf.org/html/rfc1929
91
-     */
92
-    protected function performAuthentication($username, $password)
93
-    {
94
-        $request  = pack('C2', 1, strlen($username)) . $username
95
-                    . pack('C', strlen($password)) . $password;
82
+	/**
83
+	 * Performs username/password authentication for SOCKS5
84
+	 *
85
+	 * @param string $username Proxy user name
86
+	 * @param string $password Proxy password
87
+	 *
88
+	 * @throws HTTP_Request2_ConnectionException
89
+	 * @throws HTTP_Request2_MessageException
90
+	 * @link http://tools.ietf.org/html/rfc1929
91
+	 */
92
+	protected function performAuthentication($username, $password)
93
+	{
94
+		$request  = pack('C2', 1, strlen($username)) . $username
95
+					. pack('C', strlen($password)) . $password;
96 96
 
97
-        $this->write($request);
98
-        $response = unpack('Cvn/Cstatus', $this->read(3));
99
-        if (1 != $response['vn'] || 0 != $response['status']) {
100
-            throw new HTTP_Request2_ConnectionException(
101
-                'Connection rejected by proxy due to invalid username and/or password'
102
-            );
103
-        }
104
-    }
97
+		$this->write($request);
98
+		$response = unpack('Cvn/Cstatus', $this->read(3));
99
+		if (1 != $response['vn'] || 0 != $response['status']) {
100
+			throw new HTTP_Request2_ConnectionException(
101
+				'Connection rejected by proxy due to invalid username and/or password'
102
+			);
103
+		}
104
+	}
105 105
 
106
-    /**
107
-     * Connects to a remote host via proxy
108
-     *
109
-     * @param string $remoteHost Remote host
110
-     * @param int    $remotePort Remote port
111
-     *
112
-     * @throws HTTP_Request2_ConnectionException
113
-     * @throws HTTP_Request2_MessageException
114
-     */
115
-    public function connect($remoteHost, $remotePort)
116
-    {
117
-        $request = pack('C5', 0x05, 0x01, 0x00, 0x03, strlen($remoteHost))
118
-                   . $remoteHost . pack('n', $remotePort);
106
+	/**
107
+	 * Connects to a remote host via proxy
108
+	 *
109
+	 * @param string $remoteHost Remote host
110
+	 * @param int    $remotePort Remote port
111
+	 *
112
+	 * @throws HTTP_Request2_ConnectionException
113
+	 * @throws HTTP_Request2_MessageException
114
+	 */
115
+	public function connect($remoteHost, $remotePort)
116
+	{
117
+		$request = pack('C5', 0x05, 0x01, 0x00, 0x03, strlen($remoteHost))
118
+				   . $remoteHost . pack('n', $remotePort);
119 119
 
120
-        $this->write($request);
121
-        $response = unpack('Cversion/Creply/Creserved', $this->read(1024));
122
-        if (5 != $response['version'] || 0 != $response['reserved']) {
123
-            throw new HTTP_Request2_MessageException(
124
-                'Invalid response received from SOCKS5 proxy',
125
-                HTTP_Request2_Exception::MALFORMED_RESPONSE
126
-            );
127
-        } elseif (0 != $response['reply']) {
128
-            throw new HTTP_Request2_ConnectionException(
129
-                "Unable to connect to {$remoteHost}:{$remotePort} through SOCKS5 proxy",
130
-                0, $response['reply']
131
-            );
132
-        }
133
-    }
120
+		$this->write($request);
121
+		$response = unpack('Cversion/Creply/Creserved', $this->read(1024));
122
+		if (5 != $response['version'] || 0 != $response['reserved']) {
123
+			throw new HTTP_Request2_MessageException(
124
+				'Invalid response received from SOCKS5 proxy',
125
+				HTTP_Request2_Exception::MALFORMED_RESPONSE
126
+			);
127
+		} elseif (0 != $response['reply']) {
128
+			throw new HTTP_Request2_ConnectionException(
129
+				"Unable to connect to {$remoteHost}:{$remotePort} through SOCKS5 proxy",
130
+				0, $response['reply']
131
+			);
132
+		}
133
+	}
134 134
 }
135 135
 ?>
136 136
\ No newline at end of file
Please login to merge, or discard this patch.
Switch Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -68,14 +68,14 @@
 block discarded – undo
68 68
             );
69 69
         }
70 70
         switch ($response['method']) {
71
-        case 2:
72
-            $this->performAuthentication($username, $password);
73
-        case 0:
74
-            break;
75
-        default:
76
-            throw new HTTP_Request2_ConnectionException(
77
-                "Connection rejected by proxy due to unsupported auth method"
78
-            );
71
+        	case 2:
72
+            	$this->performAuthentication($username, $password);
73
+        	case 0:
74
+            	break;
75
+        	default:
76
+            	throw new HTTP_Request2_ConnectionException(
77
+                	"Connection rejected by proxy due to unsupported auth method"
78
+            	);
79 79
         }
80 80
     }
81 81
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@
 block discarded – undo
91 91
      */
92 92
     protected function performAuthentication($username, $password)
93 93
     {
94
-        $request  = pack('C2', 1, strlen($username)) . $username
94
+        $request = pack('C2', 1, strlen($username)) . $username
95 95
                     . pack('C', strlen($password)) . $password;
96 96
 
97 97
         $this->write($request);
Please login to merge, or discard this patch.
libs/PEAR.1.9.5/HTTP/Request2/SocketWrapper.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -170,7 +170,7 @@
 block discarded – undo
170 170
                 // reset socket timeout if we don't have request timeout specified,
171 171
                 // prevents further calls failing with a bogus Exception
172 172
                 if (!$this->deadline) {
173
-                    $default = (int)@ini_get('default_socket_timeout');
173
+                    $default = (int) @ini_get('default_socket_timeout');
174 174
                     stream_set_timeout($this->socket, $default > 0 ? $default : PHP_INT_MAX);
175 175
                 }
176 176
                 if ($info['timed_out']) {
Please login to merge, or discard this patch.
Indentation   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -38,260 +38,260 @@
 block discarded – undo
38 38
  */
39 39
 class HTTP_Request2_SocketWrapper
40 40
 {
41
-    /**
42
-     * PHP warning messages raised during stream_socket_client() call
43
-     * @var array
44
-     */
45
-    protected $connectionWarnings = array();
41
+	/**
42
+	 * PHP warning messages raised during stream_socket_client() call
43
+	 * @var array
44
+	 */
45
+	protected $connectionWarnings = array();
46 46
 
47
-    /**
48
-     * Connected socket
49
-     * @var resource
50
-     */
51
-    protected $socket;
47
+	/**
48
+	 * Connected socket
49
+	 * @var resource
50
+	 */
51
+	protected $socket;
52 52
 
53
-    /**
54
-     * Sum of start time and global timeout, exception will be thrown if request continues past this time
55
-     * @var  integer
56
-     */
57
-    protected $deadline;
53
+	/**
54
+	 * Sum of start time and global timeout, exception will be thrown if request continues past this time
55
+	 * @var  integer
56
+	 */
57
+	protected $deadline;
58 58
 
59
-    /**
60
-     * Global timeout value, mostly for exception messages
61
-     * @var integer
62
-     */
63
-    protected $timeout;
59
+	/**
60
+	 * Global timeout value, mostly for exception messages
61
+	 * @var integer
62
+	 */
63
+	protected $timeout;
64 64
 
65
-    /**
66
-     * Class constructor, tries to establish connection
67
-     *
68
-     * @param string $address        Address for stream_socket_client() call,
69
-     *                               e.g. 'tcp://localhost:80'
70
-     * @param int    $timeout        Connection timeout (seconds)
71
-     * @param array  $contextOptions Context options
72
-     *
73
-     * @throws HTTP_Request2_LogicException
74
-     * @throws HTTP_Request2_ConnectionException
75
-     */
76
-    public function __construct($address, $timeout, array $contextOptions = array())
77
-    {
78
-        if (!empty($contextOptions)
79
-            && !isset($contextOptions['socket']) && !isset($contextOptions['ssl'])
80
-        ) {
81
-            // Backwards compatibility with 2.1.0 and 2.1.1 releases
82
-            $contextOptions = array('ssl' => $contextOptions);
83
-        }
84
-        $context = stream_context_create();
85
-        foreach ($contextOptions as $wrapper => $options) {
86
-            foreach ($options as $name => $value) {
87
-                if (!stream_context_set_option($context, $wrapper, $name, $value)) {
88
-                    throw new HTTP_Request2_LogicException(
89
-                        "Error setting '{$wrapper}' wrapper context option '{$name}'"
90
-                    );
91
-                }
92
-            }
93
-        }
94
-        set_error_handler(array($this, 'connectionWarningsHandler'));
95
-        $this->socket = stream_socket_client(
96
-            $address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context
97
-        );
98
-        restore_error_handler();
99
-        // if we fail to bind to a specified local address (see request #19515),
100
-        // connection still succeeds, albeit with a warning. Throw an Exception
101
-        // with the warning text in this case as that connection is unlikely
102
-        // to be what user wants and as Curl throws an error in similar case.
103
-        if ($this->connectionWarnings) {
104
-            if ($this->socket) {
105
-                fclose($this->socket);
106
-            }
107
-            $error = $errstr ? $errstr : implode("\n", $this->connectionWarnings);
108
-            throw new HTTP_Request2_ConnectionException(
109
-                "Unable to connect to {$address}. Error: {$error}", 0, $errno
110
-            );
111
-        }
112
-    }
65
+	/**
66
+	 * Class constructor, tries to establish connection
67
+	 *
68
+	 * @param string $address        Address for stream_socket_client() call,
69
+	 *                               e.g. 'tcp://localhost:80'
70
+	 * @param int    $timeout        Connection timeout (seconds)
71
+	 * @param array  $contextOptions Context options
72
+	 *
73
+	 * @throws HTTP_Request2_LogicException
74
+	 * @throws HTTP_Request2_ConnectionException
75
+	 */
76
+	public function __construct($address, $timeout, array $contextOptions = array())
77
+	{
78
+		if (!empty($contextOptions)
79
+			&& !isset($contextOptions['socket']) && !isset($contextOptions['ssl'])
80
+		) {
81
+			// Backwards compatibility with 2.1.0 and 2.1.1 releases
82
+			$contextOptions = array('ssl' => $contextOptions);
83
+		}
84
+		$context = stream_context_create();
85
+		foreach ($contextOptions as $wrapper => $options) {
86
+			foreach ($options as $name => $value) {
87
+				if (!stream_context_set_option($context, $wrapper, $name, $value)) {
88
+					throw new HTTP_Request2_LogicException(
89
+						"Error setting '{$wrapper}' wrapper context option '{$name}'"
90
+					);
91
+				}
92
+			}
93
+		}
94
+		set_error_handler(array($this, 'connectionWarningsHandler'));
95
+		$this->socket = stream_socket_client(
96
+			$address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context
97
+		);
98
+		restore_error_handler();
99
+		// if we fail to bind to a specified local address (see request #19515),
100
+		// connection still succeeds, albeit with a warning. Throw an Exception
101
+		// with the warning text in this case as that connection is unlikely
102
+		// to be what user wants and as Curl throws an error in similar case.
103
+		if ($this->connectionWarnings) {
104
+			if ($this->socket) {
105
+				fclose($this->socket);
106
+			}
107
+			$error = $errstr ? $errstr : implode("\n", $this->connectionWarnings);
108
+			throw new HTTP_Request2_ConnectionException(
109
+				"Unable to connect to {$address}. Error: {$error}", 0, $errno
110
+			);
111
+		}
112
+	}
113 113
 
114
-    /**
115
-     * Destructor, disconnects socket
116
-     */
117
-    public function __destruct()
118
-    {
119
-        fclose($this->socket);
120
-    }
114
+	/**
115
+	 * Destructor, disconnects socket
116
+	 */
117
+	public function __destruct()
118
+	{
119
+		fclose($this->socket);
120
+	}
121 121
 
122
-    /**
123
-     * Wrapper around fread(), handles global request timeout
124
-     *
125
-     * @param int $length Reads up to this number of bytes
126
-     *
127
-     * @return   string Data read from socket
128
-     * @throws   HTTP_Request2_MessageException     In case of timeout
129
-     */
130
-    public function read($length)
131
-    {
132
-        if ($this->deadline) {
133
-            stream_set_timeout($this->socket, max($this->deadline - time(), 1));
134
-        }
135
-        $data = fread($this->socket, $length);
136
-        $this->checkTimeout();
137
-        return $data;
138
-    }
122
+	/**
123
+	 * Wrapper around fread(), handles global request timeout
124
+	 *
125
+	 * @param int $length Reads up to this number of bytes
126
+	 *
127
+	 * @return   string Data read from socket
128
+	 * @throws   HTTP_Request2_MessageException     In case of timeout
129
+	 */
130
+	public function read($length)
131
+	{
132
+		if ($this->deadline) {
133
+			stream_set_timeout($this->socket, max($this->deadline - time(), 1));
134
+		}
135
+		$data = fread($this->socket, $length);
136
+		$this->checkTimeout();
137
+		return $data;
138
+	}
139 139
 
140
-    /**
141
-     * Reads until either the end of the socket or a newline, whichever comes first
142
-     *
143
-     * Strips the trailing newline from the returned data, handles global
144
-     * request timeout. Method idea borrowed from Net_Socket PEAR package.
145
-     *
146
-     * @param int $bufferSize   buffer size to use for reading
147
-     * @param int $localTimeout timeout value to use just for this call
148
-     *                          (used when waiting for "100 Continue" response)
149
-     *
150
-     * @return   string Available data up to the newline (not including newline)
151
-     * @throws   HTTP_Request2_MessageException     In case of timeout
152
-     */
153
-    public function readLine($bufferSize, $localTimeout = null)
154
-    {
155
-        $line = '';
156
-        while (!feof($this->socket)) {
157
-            if (null !== $localTimeout) {
158
-                stream_set_timeout($this->socket, $localTimeout);
159
-            } elseif ($this->deadline) {
160
-                stream_set_timeout($this->socket, max($this->deadline - time(), 1));
161
-            }
140
+	/**
141
+	 * Reads until either the end of the socket or a newline, whichever comes first
142
+	 *
143
+	 * Strips the trailing newline from the returned data, handles global
144
+	 * request timeout. Method idea borrowed from Net_Socket PEAR package.
145
+	 *
146
+	 * @param int $bufferSize   buffer size to use for reading
147
+	 * @param int $localTimeout timeout value to use just for this call
148
+	 *                          (used when waiting for "100 Continue" response)
149
+	 *
150
+	 * @return   string Available data up to the newline (not including newline)
151
+	 * @throws   HTTP_Request2_MessageException     In case of timeout
152
+	 */
153
+	public function readLine($bufferSize, $localTimeout = null)
154
+	{
155
+		$line = '';
156
+		while (!feof($this->socket)) {
157
+			if (null !== $localTimeout) {
158
+				stream_set_timeout($this->socket, $localTimeout);
159
+			} elseif ($this->deadline) {
160
+				stream_set_timeout($this->socket, max($this->deadline - time(), 1));
161
+			}
162 162
 
163
-            $line .= @fgets($this->socket, $bufferSize);
163
+			$line .= @fgets($this->socket, $bufferSize);
164 164
 
165
-            if (null === $localTimeout) {
166
-                $this->checkTimeout();
165
+			if (null === $localTimeout) {
166
+				$this->checkTimeout();
167 167
 
168
-            } else {
169
-                $info = stream_get_meta_data($this->socket);
170
-                // reset socket timeout if we don't have request timeout specified,
171
-                // prevents further calls failing with a bogus Exception
172
-                if (!$this->deadline) {
173
-                    $default = (int)@ini_get('default_socket_timeout');
174
-                    stream_set_timeout($this->socket, $default > 0 ? $default : PHP_INT_MAX);
175
-                }
176
-                if ($info['timed_out']) {
177
-                    throw new HTTP_Request2_MessageException(
178
-                        "readLine() call timed out", HTTP_Request2_Exception::TIMEOUT
179
-                    );
180
-                }
181
-            }
182
-            if (substr($line, -1) == "\n") {
183
-                return rtrim($line, "\r\n");
184
-            }
185
-        }
186
-        return $line;
187
-    }
168
+			} else {
169
+				$info = stream_get_meta_data($this->socket);
170
+				// reset socket timeout if we don't have request timeout specified,
171
+				// prevents further calls failing with a bogus Exception
172
+				if (!$this->deadline) {
173
+					$default = (int)@ini_get('default_socket_timeout');
174
+					stream_set_timeout($this->socket, $default > 0 ? $default : PHP_INT_MAX);
175
+				}
176
+				if ($info['timed_out']) {
177
+					throw new HTTP_Request2_MessageException(
178
+						"readLine() call timed out", HTTP_Request2_Exception::TIMEOUT
179
+					);
180
+				}
181
+			}
182
+			if (substr($line, -1) == "\n") {
183
+				return rtrim($line, "\r\n");
184
+			}
185
+		}
186
+		return $line;
187
+	}
188 188
 
189
-    /**
190
-     * Wrapper around fwrite(), handles global request timeout
191
-     *
192
-     * @param string $data String to be written
193
-     *
194
-     * @return int
195
-     * @throws HTTP_Request2_MessageException
196
-     */
197
-    public function write($data)
198
-    {
199
-        if ($this->deadline) {
200
-            stream_set_timeout($this->socket, max($this->deadline - time(), 1));
201
-        }
202
-        $written = fwrite($this->socket, $data);
203
-        $this->checkTimeout();
204
-        // http://www.php.net/manual/en/function.fwrite.php#96951
205
-        if ($written < strlen($data)) {
206
-            throw new HTTP_Request2_MessageException('Error writing request');
207
-        }
208
-        return $written;
209
-    }
189
+	/**
190
+	 * Wrapper around fwrite(), handles global request timeout
191
+	 *
192
+	 * @param string $data String to be written
193
+	 *
194
+	 * @return int
195
+	 * @throws HTTP_Request2_MessageException
196
+	 */
197
+	public function write($data)
198
+	{
199
+		if ($this->deadline) {
200
+			stream_set_timeout($this->socket, max($this->deadline - time(), 1));
201
+		}
202
+		$written = fwrite($this->socket, $data);
203
+		$this->checkTimeout();
204
+		// http://www.php.net/manual/en/function.fwrite.php#96951
205
+		if ($written < strlen($data)) {
206
+			throw new HTTP_Request2_MessageException('Error writing request');
207
+		}
208
+		return $written;
209
+	}
210 210
 
211
-    /**
212
-     * Tests for end-of-file on a socket
213
-     *
214
-     * @return bool
215
-     */
216
-    public function eof()
217
-    {
218
-        return feof($this->socket);
219
-    }
211
+	/**
212
+	 * Tests for end-of-file on a socket
213
+	 *
214
+	 * @return bool
215
+	 */
216
+	public function eof()
217
+	{
218
+		return feof($this->socket);
219
+	}
220 220
 
221
-    /**
222
-     * Sets request deadline
223
-     *
224
-     * @param int $deadline Exception will be thrown if request continues
225
-     *                      past this time
226
-     * @param int $timeout  Original request timeout value, to use in
227
-     *                      Exception message
228
-     */
229
-    public function setDeadline($deadline, $timeout)
230
-    {
231
-        $this->deadline = $deadline;
232
-        $this->timeout  = $timeout;
233
-    }
221
+	/**
222
+	 * Sets request deadline
223
+	 *
224
+	 * @param int $deadline Exception will be thrown if request continues
225
+	 *                      past this time
226
+	 * @param int $timeout  Original request timeout value, to use in
227
+	 *                      Exception message
228
+	 */
229
+	public function setDeadline($deadline, $timeout)
230
+	{
231
+		$this->deadline = $deadline;
232
+		$this->timeout  = $timeout;
233
+	}
234 234
 
235
-    /**
236
-     * Turns on encryption on a socket
237
-     *
238
-     * @throws HTTP_Request2_ConnectionException
239
-     */
240
-    public function enableCrypto()
241
-    {
242
-        $modes = array(
243
-            STREAM_CRYPTO_METHOD_TLS_CLIENT,
244
-            STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
245
-            STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
246
-            STREAM_CRYPTO_METHOD_SSLv2_CLIENT
247
-        );
235
+	/**
236
+	 * Turns on encryption on a socket
237
+	 *
238
+	 * @throws HTTP_Request2_ConnectionException
239
+	 */
240
+	public function enableCrypto()
241
+	{
242
+		$modes = array(
243
+			STREAM_CRYPTO_METHOD_TLS_CLIENT,
244
+			STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
245
+			STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
246
+			STREAM_CRYPTO_METHOD_SSLv2_CLIENT
247
+		);
248 248
 
249
-        foreach ($modes as $mode) {
250
-            if (stream_socket_enable_crypto($this->socket, true, $mode)) {
251
-                return;
252
-            }
253
-        }
254
-        throw new HTTP_Request2_ConnectionException(
255
-            'Failed to enable secure connection when connecting through proxy'
256
-        );
257
-    }
249
+		foreach ($modes as $mode) {
250
+			if (stream_socket_enable_crypto($this->socket, true, $mode)) {
251
+				return;
252
+			}
253
+		}
254
+		throw new HTTP_Request2_ConnectionException(
255
+			'Failed to enable secure connection when connecting through proxy'
256
+		);
257
+	}
258 258
 
259
-    /**
260
-     * Throws an Exception if stream timed out
261
-     *
262
-     * @throws HTTP_Request2_MessageException
263
-     */
264
-    protected function checkTimeout()
265
-    {
266
-        $info = stream_get_meta_data($this->socket);
267
-        if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
268
-            $reason = $this->deadline
269
-                ? "after {$this->timeout} second(s)"
270
-                : 'due to default_socket_timeout php.ini setting';
271
-            throw new HTTP_Request2_MessageException(
272
-                "Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT
273
-            );
274
-        }
275
-    }
259
+	/**
260
+	 * Throws an Exception if stream timed out
261
+	 *
262
+	 * @throws HTTP_Request2_MessageException
263
+	 */
264
+	protected function checkTimeout()
265
+	{
266
+		$info = stream_get_meta_data($this->socket);
267
+		if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
268
+			$reason = $this->deadline
269
+				? "after {$this->timeout} second(s)"
270
+				: 'due to default_socket_timeout php.ini setting';
271
+			throw new HTTP_Request2_MessageException(
272
+				"Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT
273
+			);
274
+		}
275
+	}
276 276
 
277
-    /**
278
-     * Error handler to use during stream_socket_client() call
279
-     *
280
-     * One stream_socket_client() call may produce *multiple* PHP warnings
281
-     * (especially OpenSSL-related), we keep them in an array to later use for
282
-     * the message of HTTP_Request2_ConnectionException
283
-     *
284
-     * @param int    $errno  error level
285
-     * @param string $errstr error message
286
-     *
287
-     * @return bool
288
-     */
289
-    protected function connectionWarningsHandler($errno, $errstr)
290
-    {
291
-        if ($errno & E_WARNING) {
292
-            array_unshift($this->connectionWarnings, $errstr);
293
-        }
294
-        return true;
295
-    }
277
+	/**
278
+	 * Error handler to use during stream_socket_client() call
279
+	 *
280
+	 * One stream_socket_client() call may produce *multiple* PHP warnings
281
+	 * (especially OpenSSL-related), we keep them in an array to later use for
282
+	 * the message of HTTP_Request2_ConnectionException
283
+	 *
284
+	 * @param int    $errno  error level
285
+	 * @param string $errstr error message
286
+	 *
287
+	 * @return bool
288
+	 */
289
+	protected function connectionWarningsHandler($errno, $errstr)
290
+	{
291
+		if ($errno & E_WARNING) {
292
+			array_unshift($this->connectionWarnings, $errstr);
293
+		}
294
+		return true;
295
+	}
296 296
 }
297 297
 ?>
Please login to merge, or discard this patch.
libs/PEAR.1.9.5/PEAR.php 2 patches
Indentation   +963 added lines, -963 removed lines patch added patch discarded remove patch
@@ -1,23 +1,23 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * PEAR, the PHP Extension and Application Repository
4
- *
5
- * PEAR class and PEAR_Error class
6
- *
7
- * PHP versions 4 and 5
8
- *
9
- * @category   pear
10
- * @package    PEAR
11
- * @author     Sterling Hughes <[email protected]>
12
- * @author     Stig Bakken <[email protected]>
13
- * @author     Tomas V.V.Cox <[email protected]>
14
- * @author     Greg Beaver <[email protected]>
15
- * @copyright  1997-2010 The Authors
16
- * @license    http://opensource.org/licenses/bsd-license.php New BSD License
17
- * @version    CVS: $Id$
18
- * @link       http://pear.php.net/package/PEAR
19
- * @since      File available since Release 0.1
20
- */
3
+	 * PEAR, the PHP Extension and Application Repository
4
+	 *
5
+	 * PEAR class and PEAR_Error class
6
+	 *
7
+	 * PHP versions 4 and 5
8
+	 *
9
+	 * @category   pear
10
+	 * @package    PEAR
11
+	 * @author     Sterling Hughes <[email protected]>
12
+	 * @author     Stig Bakken <[email protected]>
13
+	 * @author     Tomas V.V.Cox <[email protected]>
14
+	 * @author     Greg Beaver <[email protected]>
15
+	 * @copyright  1997-2010 The Authors
16
+	 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
17
+	 * @version    CVS: $Id$
18
+	 * @link       http://pear.php.net/package/PEAR
19
+	 * @since      File available since Release 0.1
20
+	 */
21 21
 
22 22
 /**#@+
23 23
  * ERROR constants
@@ -34,16 +34,16 @@  discard block
 block discarded – undo
34 34
 define('PEAR_ERROR_EXCEPTION', 32);
35 35
 /**#@-*/
36 36
 define('PEAR_ZE2', (function_exists('version_compare') &&
37
-                    version_compare(zend_version(), "2-dev", "ge")));
37
+					version_compare(zend_version(), "2-dev", "ge")));
38 38
 
39 39
 if (substr(PHP_OS, 0, 3) == 'WIN') {
40
-    define('OS_WINDOWS', true);
41
-    define('OS_UNIX',    false);
42
-    define('PEAR_OS',    'Windows');
40
+	define('OS_WINDOWS', true);
41
+	define('OS_UNIX',    false);
42
+	define('PEAR_OS',    'Windows');
43 43
 } else {
44
-    define('OS_WINDOWS', false);
45
-    define('OS_UNIX',    true);
46
-    define('PEAR_OS',    'Unix'); // blatant assumption
44
+	define('OS_WINDOWS', false);
45
+	define('OS_UNIX',    true);
46
+	define('PEAR_OS',    'Unix'); // blatant assumption
47 47
 }
48 48
 
49 49
 $GLOBALS['_PEAR_default_error_mode']     = PEAR_ERROR_RETURN;
@@ -86,694 +86,694 @@  discard block
 block discarded – undo
86 86
  */
87 87
 class PEAR
88 88
 {
89
-    /**
90
-     * Whether to enable internal debug messages.
91
-     *
92
-     * @var     bool
93
-     * @access  private
94
-     */
95
-    var $_debug = false;
96
-
97
-    /**
98
-     * Default error mode for this object.
99
-     *
100
-     * @var     int
101
-     * @access  private
102
-     */
103
-    var $_default_error_mode = null;
104
-
105
-    /**
106
-     * Default error options used for this object when error mode
107
-     * is PEAR_ERROR_TRIGGER.
108
-     *
109
-     * @var     int
110
-     * @access  private
111
-     */
112
-    var $_default_error_options = null;
113
-
114
-    /**
115
-     * Default error handler (callback) for this object, if error mode is
116
-     * PEAR_ERROR_CALLBACK.
117
-     *
118
-     * @var     string
119
-     * @access  private
120
-     */
121
-    var $_default_error_handler = '';
122
-
123
-    /**
124
-     * Which class to use for error objects.
125
-     *
126
-     * @var     string
127
-     * @access  private
128
-     */
129
-    var $_error_class = 'PEAR_Error';
130
-
131
-    /**
132
-     * An array of expected errors.
133
-     *
134
-     * @var     array
135
-     * @access  private
136
-     */
137
-    var $_expected_errors = array();
138
-
139
-    /**
140
-     * Constructor.  Registers this object in
141
-     * $_PEAR_destructor_object_list for destructor emulation if a
142
-     * destructor object exists.
143
-     *
144
-     * @param string $error_class  (optional) which class to use for
145
-     *        error objects, defaults to PEAR_Error.
146
-     * @access public
147
-     * @return void
148
-     */
149
-    function PEAR($error_class = null)
150
-    {
151
-        $classname = strtolower(get_class($this));
152
-        if ($this->_debug) {
153
-            print "PEAR constructor called, class=$classname\n";
154
-        }
155
-
156
-        if ($error_class !== null) {
157
-            $this->_error_class = $error_class;
158
-        }
159
-
160
-        while ($classname && strcasecmp($classname, "pear")) {
161
-            $destructor = "_$classname";
162
-            if (method_exists($this, $destructor)) {
163
-                global $_PEAR_destructor_object_list;
164
-                $_PEAR_destructor_object_list[] = &$this;
165
-                if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
166
-                    register_shutdown_function("_PEAR_call_destructors");
167
-                    $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
168
-                }
169
-                break;
170
-            } else {
171
-                $classname = get_parent_class($classname);
172
-            }
173
-        }
174
-    }
175
-
176
-    /**
177
-     * Destructor (the emulated type of...).  Does nothing right now,
178
-     * but is included for forward compatibility, so subclass
179
-     * destructors should always call it.
180
-     *
181
-     * See the note in the class desciption about output from
182
-     * destructors.
183
-     *
184
-     * @access public
185
-     * @return void
186
-     */
187
-    function _PEAR() {
188
-        if ($this->_debug) {
189
-            printf("PEAR destructor called, class=%s\n", strtolower(get_class($this)));
190
-        }
191
-    }
192
-
193
-    /**
194
-    * If you have a class that's mostly/entirely static, and you need static
195
-    * properties, you can use this method to simulate them. Eg. in your method(s)
196
-    * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
197
-    * You MUST use a reference, or they will not persist!
198
-    *
199
-    * @access public
200
-    * @param  string $class  The calling classname, to prevent clashes
201
-    * @param  string $var    The variable to retrieve.
202
-    * @return mixed   A reference to the variable. If not set it will be
203
-    *                 auto initialised to NULL.
204
-    */
205
-    function &getStaticProperty($class, $var)
206
-    {
207
-        static $properties;
208
-        if (!isset($properties[$class])) {
209
-            $properties[$class] = array();
210
-        }
211
-
212
-        if (!array_key_exists($var, $properties[$class])) {
213
-            $properties[$class][$var] = null;
214
-        }
215
-
216
-        return $properties[$class][$var];
217
-    }
218
-
219
-    /**
220
-    * Use this function to register a shutdown method for static
221
-    * classes.
222
-    *
223
-    * @access public
224
-    * @param  mixed $func  The function name (or array of class/method) to call
225
-    * @param  mixed $args  The arguments to pass to the function
226
-    * @return void
227
-    */
228
-    function registerShutdownFunc($func, $args = array())
229
-    {
230
-        // if we are called statically, there is a potential
231
-        // that no shutdown func is registered.  Bug #6445
232
-        if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
233
-            register_shutdown_function("_PEAR_call_destructors");
234
-            $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
235
-        }
236
-        $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
237
-    }
238
-
239
-    /**
240
-     * Tell whether a value is a PEAR error.
241
-     *
242
-     * @param   mixed $data   the value to test
243
-     * @param   int   $code   if $data is an error object, return true
244
-     *                        only if $code is a string and
245
-     *                        $obj->getMessage() == $code or
246
-     *                        $code is an integer and $obj->getCode() == $code
247
-     * @access  public
248
-     * @return  bool    true if parameter is an error
249
-     */
250
-    function isError($data, $code = null)
251
-    {
252
-        if (!is_a($data, 'PEAR_Error')) {
253
-            return false;
254
-        }
255
-
256
-        if (is_null($code)) {
257
-            return true;
258
-        } elseif (is_string($code)) {
259
-            return $data->getMessage() == $code;
260
-        }
261
-
262
-        return $data->getCode() == $code;
263
-    }
264
-
265
-    /**
266
-     * Sets how errors generated by this object should be handled.
267
-     * Can be invoked both in objects and statically.  If called
268
-     * statically, setErrorHandling sets the default behaviour for all
269
-     * PEAR objects.  If called in an object, setErrorHandling sets
270
-     * the default behaviour for that object.
271
-     *
272
-     * @param int $mode
273
-     *        One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
274
-     *        PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
275
-     *        PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
276
-     *
277
-     * @param mixed $options
278
-     *        When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
279
-     *        of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
280
-     *
281
-     *        When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
282
-     *        to be the callback function or method.  A callback
283
-     *        function is a string with the name of the function, a
284
-     *        callback method is an array of two elements: the element
285
-     *        at index 0 is the object, and the element at index 1 is
286
-     *        the name of the method to call in the object.
287
-     *
288
-     *        When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
289
-     *        a printf format string used when printing the error
290
-     *        message.
291
-     *
292
-     * @access public
293
-     * @return void
294
-     * @see PEAR_ERROR_RETURN
295
-     * @see PEAR_ERROR_PRINT
296
-     * @see PEAR_ERROR_TRIGGER
297
-     * @see PEAR_ERROR_DIE
298
-     * @see PEAR_ERROR_CALLBACK
299
-     * @see PEAR_ERROR_EXCEPTION
300
-     *
301
-     * @since PHP 4.0.5
302
-     */
303
-    function setErrorHandling($mode = null, $options = null)
304
-    {
305
-        if (isset($this) && is_a($this, 'PEAR')) {
306
-            $setmode     = &$this->_default_error_mode;
307
-            $setoptions  = &$this->_default_error_options;
308
-        } else {
309
-            $setmode     = &$GLOBALS['_PEAR_default_error_mode'];
310
-            $setoptions  = &$GLOBALS['_PEAR_default_error_options'];
311
-        }
312
-
313
-        switch ($mode) {
314
-            case PEAR_ERROR_EXCEPTION:
315
-            case PEAR_ERROR_RETURN:
316
-            case PEAR_ERROR_PRINT:
317
-            case PEAR_ERROR_TRIGGER:
318
-            case PEAR_ERROR_DIE:
319
-            case null:
320
-                $setmode = $mode;
321
-                $setoptions = $options;
322
-                break;
323
-
324
-            case PEAR_ERROR_CALLBACK:
325
-                $setmode = $mode;
326
-                // class/object method callback
327
-                if (is_callable($options)) {
328
-                    $setoptions = $options;
329
-                } else {
330
-                    trigger_error("invalid error callback", E_USER_WARNING);
331
-                }
332
-                break;
333
-
334
-            default:
335
-                trigger_error("invalid error mode", E_USER_WARNING);
336
-                break;
337
-        }
338
-    }
339
-
340
-    /**
341
-     * This method is used to tell which errors you expect to get.
342
-     * Expected errors are always returned with error mode
343
-     * PEAR_ERROR_RETURN.  Expected error codes are stored in a stack,
344
-     * and this method pushes a new element onto it.  The list of
345
-     * expected errors are in effect until they are popped off the
346
-     * stack with the popExpect() method.
347
-     *
348
-     * Note that this method can not be called statically
349
-     *
350
-     * @param mixed $code a single error code or an array of error codes to expect
351
-     *
352
-     * @return int     the new depth of the "expected errors" stack
353
-     * @access public
354
-     */
355
-    function expectError($code = '*')
356
-    {
357
-        if (is_array($code)) {
358
-            array_push($this->_expected_errors, $code);
359
-        } else {
360
-            array_push($this->_expected_errors, array($code));
361
-        }
362
-        return count($this->_expected_errors);
363
-    }
364
-
365
-    /**
366
-     * This method pops one element off the expected error codes
367
-     * stack.
368
-     *
369
-     * @return array   the list of error codes that were popped
370
-     */
371
-    function popExpect()
372
-    {
373
-        return array_pop($this->_expected_errors);
374
-    }
375
-
376
-    /**
377
-     * This method checks unsets an error code if available
378
-     *
379
-     * @param mixed error code
380
-     * @return bool true if the error code was unset, false otherwise
381
-     * @access private
382
-     * @since PHP 4.3.0
383
-     */
384
-    function _checkDelExpect($error_code)
385
-    {
386
-        $deleted = false;
387
-        foreach ($this->_expected_errors as $key => $error_array) {
388
-            if (in_array($error_code, $error_array)) {
389
-                unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
390
-                $deleted = true;
391
-            }
392
-
393
-            // clean up empty arrays
394
-            if (0 == count($this->_expected_errors[$key])) {
395
-                unset($this->_expected_errors[$key]);
396
-            }
397
-        }
398
-
399
-        return $deleted;
400
-    }
401
-
402
-    /**
403
-     * This method deletes all occurences of the specified element from
404
-     * the expected error codes stack.
405
-     *
406
-     * @param  mixed $error_code error code that should be deleted
407
-     * @return mixed list of error codes that were deleted or error
408
-     * @access public
409
-     * @since PHP 4.3.0
410
-     */
411
-    function delExpect($error_code)
412
-    {
413
-        $deleted = false;
414
-        if ((is_array($error_code) && (0 != count($error_code)))) {
415
-            // $error_code is a non-empty array here; we walk through it trying
416
-            // to unset all values
417
-            foreach ($error_code as $key => $error) {
418
-                $deleted =  $this->_checkDelExpect($error) ? true : false;
419
-            }
420
-
421
-            return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
422
-        } elseif (!empty($error_code)) {
423
-            // $error_code comes alone, trying to unset it
424
-            if ($this->_checkDelExpect($error_code)) {
425
-                return true;
426
-            }
427
-
428
-            return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
429
-        }
430
-
431
-        // $error_code is empty
432
-        return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
433
-    }
434
-
435
-    /**
436
-     * This method is a wrapper that returns an instance of the
437
-     * configured error class with this object's default error
438
-     * handling applied.  If the $mode and $options parameters are not
439
-     * specified, the object's defaults are used.
440
-     *
441
-     * @param mixed $message a text error message or a PEAR error object
442
-     *
443
-     * @param int $code      a numeric error code (it is up to your class
444
-     *                  to define these if you want to use codes)
445
-     *
446
-     * @param int $mode      One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
447
-     *                  PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
448
-     *                  PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION.
449
-     *
450
-     * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter
451
-     *                  specifies the PHP-internal error level (one of
452
-     *                  E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
453
-     *                  If $mode is PEAR_ERROR_CALLBACK, this
454
-     *                  parameter specifies the callback function or
455
-     *                  method.  In other error modes this parameter
456
-     *                  is ignored.
457
-     *
458
-     * @param string $userinfo If you need to pass along for example debug
459
-     *                  information, this parameter is meant for that.
460
-     *
461
-     * @param string $error_class The returned error object will be
462
-     *                  instantiated from this class, if specified.
463
-     *
464
-     * @param bool $skipmsg If true, raiseError will only pass error codes,
465
-     *                  the error message parameter will be dropped.
466
-     *
467
-     * @access public
468
-     * @return object   a PEAR error object
469
-     * @see PEAR::setErrorHandling
470
-     * @since PHP 4.0.5
471
-     */
472
-    function &raiseError($message = null,
473
-                         $code = null,
474
-                         $mode = null,
475
-                         $options = null,
476
-                         $userinfo = null,
477
-                         $error_class = null,
478
-                         $skipmsg = false)
479
-    {
480
-        // The error is yet a PEAR error object
481
-        if (is_object($message)) {
482
-            $code        = $message->getCode();
483
-            $userinfo    = $message->getUserInfo();
484
-            $error_class = $message->getType();
485
-            $message->error_message_prefix = '';
486
-            $message     = $message->getMessage();
487
-        }
488
-
489
-        if (
490
-            isset($this) &&
491
-            isset($this->_expected_errors) &&
492
-            count($this->_expected_errors) > 0 &&
493
-            count($exp = end($this->_expected_errors))
494
-        ) {
495
-            if ($exp[0] == "*" ||
496
-                (is_int(reset($exp)) && in_array($code, $exp)) ||
497
-                (is_string(reset($exp)) && in_array($message, $exp))
498
-            ) {
499
-                $mode = PEAR_ERROR_RETURN;
500
-            }
501
-        }
502
-
503
-        // No mode given, try global ones
504
-        if ($mode === null) {
505
-            // Class error handler
506
-            if (isset($this) && isset($this->_default_error_mode)) {
507
-                $mode    = $this->_default_error_mode;
508
-                $options = $this->_default_error_options;
509
-            // Global error handler
510
-            } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {
511
-                $mode    = $GLOBALS['_PEAR_default_error_mode'];
512
-                $options = $GLOBALS['_PEAR_default_error_options'];
513
-            }
514
-        }
515
-
516
-        if ($error_class !== null) {
517
-            $ec = $error_class;
518
-        } elseif (isset($this) && isset($this->_error_class)) {
519
-            $ec = $this->_error_class;
520
-        } else {
521
-            $ec = 'PEAR_Error';
522
-        }
523
-
524
-        if (intval(PHP_VERSION) < 5) {
525
-            // little non-eval hack to fix bug #12147
526
-            include 'PEAR/FixPHP5PEARWarnings.php';
527
-            return $a;
528
-        }
529
-
530
-        if ($skipmsg) {
531
-            $a = new $ec($code, $mode, $options, $userinfo);
532
-        } else {
533
-            $a = new $ec($message, $code, $mode, $options, $userinfo);
534
-        }
535
-
536
-        return $a;
537
-    }
538
-
539
-    /**
540
-     * Simpler form of raiseError with fewer options.  In most cases
541
-     * message, code and userinfo are enough.
542
-     *
543
-     * @param mixed $message a text error message or a PEAR error object
544
-     *
545
-     * @param int $code      a numeric error code (it is up to your class
546
-     *                  to define these if you want to use codes)
547
-     *
548
-     * @param string $userinfo If you need to pass along for example debug
549
-     *                  information, this parameter is meant for that.
550
-     *
551
-     * @access public
552
-     * @return object   a PEAR error object
553
-     * @see PEAR::raiseError
554
-     */
555
-    function &throwError($message = null, $code = null, $userinfo = null)
556
-    {
557
-        if (isset($this) && is_a($this, 'PEAR')) {
558
-            $a = &$this->raiseError($message, $code, null, null, $userinfo);
559
-            return $a;
560
-        }
561
-
562
-        $a = &PEAR::raiseError($message, $code, null, null, $userinfo);
563
-        return $a;
564
-    }
565
-
566
-    function staticPushErrorHandling($mode, $options = null)
567
-    {
568
-        $stack       = &$GLOBALS['_PEAR_error_handler_stack'];
569
-        $def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
570
-        $def_options = &$GLOBALS['_PEAR_default_error_options'];
571
-        $stack[] = array($def_mode, $def_options);
572
-        switch ($mode) {
573
-            case PEAR_ERROR_EXCEPTION:
574
-            case PEAR_ERROR_RETURN:
575
-            case PEAR_ERROR_PRINT:
576
-            case PEAR_ERROR_TRIGGER:
577
-            case PEAR_ERROR_DIE:
578
-            case null:
579
-                $def_mode = $mode;
580
-                $def_options = $options;
581
-                break;
582
-
583
-            case PEAR_ERROR_CALLBACK:
584
-                $def_mode = $mode;
585
-                // class/object method callback
586
-                if (is_callable($options)) {
587
-                    $def_options = $options;
588
-                } else {
589
-                    trigger_error("invalid error callback", E_USER_WARNING);
590
-                }
591
-                break;
592
-
593
-            default:
594
-                trigger_error("invalid error mode", E_USER_WARNING);
595
-                break;
596
-        }
597
-        $stack[] = array($mode, $options);
598
-        return true;
599
-    }
600
-
601
-    function staticPopErrorHandling()
602
-    {
603
-        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
604
-        $setmode     = &$GLOBALS['_PEAR_default_error_mode'];
605
-        $setoptions  = &$GLOBALS['_PEAR_default_error_options'];
606
-        array_pop($stack);
607
-        list($mode, $options) = $stack[sizeof($stack) - 1];
608
-        array_pop($stack);
609
-        switch ($mode) {
610
-            case PEAR_ERROR_EXCEPTION:
611
-            case PEAR_ERROR_RETURN:
612
-            case PEAR_ERROR_PRINT:
613
-            case PEAR_ERROR_TRIGGER:
614
-            case PEAR_ERROR_DIE:
615
-            case null:
616
-                $setmode = $mode;
617
-                $setoptions = $options;
618
-                break;
619
-
620
-            case PEAR_ERROR_CALLBACK:
621
-                $setmode = $mode;
622
-                // class/object method callback
623
-                if (is_callable($options)) {
624
-                    $setoptions = $options;
625
-                } else {
626
-                    trigger_error("invalid error callback", E_USER_WARNING);
627
-                }
628
-                break;
629
-
630
-            default:
631
-                trigger_error("invalid error mode", E_USER_WARNING);
632
-                break;
633
-        }
634
-        return true;
635
-    }
636
-
637
-    /**
638
-     * Push a new error handler on top of the error handler options stack. With this
639
-     * you can easily override the actual error handler for some code and restore
640
-     * it later with popErrorHandling.
641
-     *
642
-     * @param mixed $mode (same as setErrorHandling)
643
-     * @param mixed $options (same as setErrorHandling)
644
-     *
645
-     * @return bool Always true
646
-     *
647
-     * @see PEAR::setErrorHandling
648
-     */
649
-    function pushErrorHandling($mode, $options = null)
650
-    {
651
-        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
652
-        if (isset($this) && is_a($this, 'PEAR')) {
653
-            $def_mode    = &$this->_default_error_mode;
654
-            $def_options = &$this->_default_error_options;
655
-        } else {
656
-            $def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
657
-            $def_options = &$GLOBALS['_PEAR_default_error_options'];
658
-        }
659
-        $stack[] = array($def_mode, $def_options);
660
-
661
-        if (isset($this) && is_a($this, 'PEAR')) {
662
-            $this->setErrorHandling($mode, $options);
663
-        } else {
664
-            PEAR::setErrorHandling($mode, $options);
665
-        }
666
-        $stack[] = array($mode, $options);
667
-        return true;
668
-    }
669
-
670
-    /**
671
-    * Pop the last error handler used
672
-    *
673
-    * @return bool Always true
674
-    *
675
-    * @see PEAR::pushErrorHandling
676
-    */
677
-    function popErrorHandling()
678
-    {
679
-        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
680
-        array_pop($stack);
681
-        list($mode, $options) = $stack[sizeof($stack) - 1];
682
-        array_pop($stack);
683
-        if (isset($this) && is_a($this, 'PEAR')) {
684
-            $this->setErrorHandling($mode, $options);
685
-        } else {
686
-            PEAR::setErrorHandling($mode, $options);
687
-        }
688
-        return true;
689
-    }
690
-
691
-    /**
692
-    * OS independent PHP extension load. Remember to take care
693
-    * on the correct extension name for case sensitive OSes.
694
-    *
695
-    * @param string $ext The extension name
696
-    * @return bool Success or not on the dl() call
697
-    */
698
-    function loadExtension($ext)
699
-    {
700
-        if (extension_loaded($ext)) {
701
-            return true;
702
-        }
703
-
704
-        // if either returns true dl() will produce a FATAL error, stop that
705
-        if (
706
-            function_exists('dl') === false ||
707
-            ini_get('enable_dl') != 1 ||
708
-            ini_get('safe_mode') == 1
709
-        ) {
710
-            return false;
711
-        }
712
-
713
-        if (OS_WINDOWS) {
714
-            $suffix = '.dll';
715
-        } elseif (PHP_OS == 'HP-UX') {
716
-            $suffix = '.sl';
717
-        } elseif (PHP_OS == 'AIX') {
718
-            $suffix = '.a';
719
-        } elseif (PHP_OS == 'OSX') {
720
-            $suffix = '.bundle';
721
-        } else {
722
-            $suffix = '.so';
723
-        }
724
-
725
-        return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
726
-    }
89
+	/**
90
+	 * Whether to enable internal debug messages.
91
+	 *
92
+	 * @var     bool
93
+	 * @access  private
94
+	 */
95
+	var $_debug = false;
96
+
97
+	/**
98
+	 * Default error mode for this object.
99
+	 *
100
+	 * @var     int
101
+	 * @access  private
102
+	 */
103
+	var $_default_error_mode = null;
104
+
105
+	/**
106
+	 * Default error options used for this object when error mode
107
+	 * is PEAR_ERROR_TRIGGER.
108
+	 *
109
+	 * @var     int
110
+	 * @access  private
111
+	 */
112
+	var $_default_error_options = null;
113
+
114
+	/**
115
+	 * Default error handler (callback) for this object, if error mode is
116
+	 * PEAR_ERROR_CALLBACK.
117
+	 *
118
+	 * @var     string
119
+	 * @access  private
120
+	 */
121
+	var $_default_error_handler = '';
122
+
123
+	/**
124
+	 * Which class to use for error objects.
125
+	 *
126
+	 * @var     string
127
+	 * @access  private
128
+	 */
129
+	var $_error_class = 'PEAR_Error';
130
+
131
+	/**
132
+	 * An array of expected errors.
133
+	 *
134
+	 * @var     array
135
+	 * @access  private
136
+	 */
137
+	var $_expected_errors = array();
138
+
139
+	/**
140
+	 * Constructor.  Registers this object in
141
+	 * $_PEAR_destructor_object_list for destructor emulation if a
142
+	 * destructor object exists.
143
+	 *
144
+	 * @param string $error_class  (optional) which class to use for
145
+	 *        error objects, defaults to PEAR_Error.
146
+	 * @access public
147
+	 * @return void
148
+	 */
149
+	function PEAR($error_class = null)
150
+	{
151
+		$classname = strtolower(get_class($this));
152
+		if ($this->_debug) {
153
+			print "PEAR constructor called, class=$classname\n";
154
+		}
155
+
156
+		if ($error_class !== null) {
157
+			$this->_error_class = $error_class;
158
+		}
159
+
160
+		while ($classname && strcasecmp($classname, "pear")) {
161
+			$destructor = "_$classname";
162
+			if (method_exists($this, $destructor)) {
163
+				global $_PEAR_destructor_object_list;
164
+				$_PEAR_destructor_object_list[] = &$this;
165
+				if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
166
+					register_shutdown_function("_PEAR_call_destructors");
167
+					$GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
168
+				}
169
+				break;
170
+			} else {
171
+				$classname = get_parent_class($classname);
172
+			}
173
+		}
174
+	}
175
+
176
+	/**
177
+	 * Destructor (the emulated type of...).  Does nothing right now,
178
+	 * but is included for forward compatibility, so subclass
179
+	 * destructors should always call it.
180
+	 *
181
+	 * See the note in the class desciption about output from
182
+	 * destructors.
183
+	 *
184
+	 * @access public
185
+	 * @return void
186
+	 */
187
+	function _PEAR() {
188
+		if ($this->_debug) {
189
+			printf("PEAR destructor called, class=%s\n", strtolower(get_class($this)));
190
+		}
191
+	}
192
+
193
+	/**
194
+	 * If you have a class that's mostly/entirely static, and you need static
195
+	 * properties, you can use this method to simulate them. Eg. in your method(s)
196
+	 * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
197
+	 * You MUST use a reference, or they will not persist!
198
+	 *
199
+	 * @access public
200
+	 * @param  string $class  The calling classname, to prevent clashes
201
+	 * @param  string $var    The variable to retrieve.
202
+	 * @return mixed   A reference to the variable. If not set it will be
203
+	 *                 auto initialised to NULL.
204
+	 */
205
+	function &getStaticProperty($class, $var)
206
+	{
207
+		static $properties;
208
+		if (!isset($properties[$class])) {
209
+			$properties[$class] = array();
210
+		}
211
+
212
+		if (!array_key_exists($var, $properties[$class])) {
213
+			$properties[$class][$var] = null;
214
+		}
215
+
216
+		return $properties[$class][$var];
217
+	}
218
+
219
+	/**
220
+	 * Use this function to register a shutdown method for static
221
+	 * classes.
222
+	 *
223
+	 * @access public
224
+	 * @param  mixed $func  The function name (or array of class/method) to call
225
+	 * @param  mixed $args  The arguments to pass to the function
226
+	 * @return void
227
+	 */
228
+	function registerShutdownFunc($func, $args = array())
229
+	{
230
+		// if we are called statically, there is a potential
231
+		// that no shutdown func is registered.  Bug #6445
232
+		if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
233
+			register_shutdown_function("_PEAR_call_destructors");
234
+			$GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
235
+		}
236
+		$GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
237
+	}
238
+
239
+	/**
240
+	 * Tell whether a value is a PEAR error.
241
+	 *
242
+	 * @param   mixed $data   the value to test
243
+	 * @param   int   $code   if $data is an error object, return true
244
+	 *                        only if $code is a string and
245
+	 *                        $obj->getMessage() == $code or
246
+	 *                        $code is an integer and $obj->getCode() == $code
247
+	 * @access  public
248
+	 * @return  bool    true if parameter is an error
249
+	 */
250
+	function isError($data, $code = null)
251
+	{
252
+		if (!is_a($data, 'PEAR_Error')) {
253
+			return false;
254
+		}
255
+
256
+		if (is_null($code)) {
257
+			return true;
258
+		} elseif (is_string($code)) {
259
+			return $data->getMessage() == $code;
260
+		}
261
+
262
+		return $data->getCode() == $code;
263
+	}
264
+
265
+	/**
266
+	 * Sets how errors generated by this object should be handled.
267
+	 * Can be invoked both in objects and statically.  If called
268
+	 * statically, setErrorHandling sets the default behaviour for all
269
+	 * PEAR objects.  If called in an object, setErrorHandling sets
270
+	 * the default behaviour for that object.
271
+	 *
272
+	 * @param int $mode
273
+	 *        One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
274
+	 *        PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
275
+	 *        PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
276
+	 *
277
+	 * @param mixed $options
278
+	 *        When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
279
+	 *        of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
280
+	 *
281
+	 *        When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
282
+	 *        to be the callback function or method.  A callback
283
+	 *        function is a string with the name of the function, a
284
+	 *        callback method is an array of two elements: the element
285
+	 *        at index 0 is the object, and the element at index 1 is
286
+	 *        the name of the method to call in the object.
287
+	 *
288
+	 *        When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
289
+	 *        a printf format string used when printing the error
290
+	 *        message.
291
+	 *
292
+	 * @access public
293
+	 * @return void
294
+	 * @see PEAR_ERROR_RETURN
295
+	 * @see PEAR_ERROR_PRINT
296
+	 * @see PEAR_ERROR_TRIGGER
297
+	 * @see PEAR_ERROR_DIE
298
+	 * @see PEAR_ERROR_CALLBACK
299
+	 * @see PEAR_ERROR_EXCEPTION
300
+	 *
301
+	 * @since PHP 4.0.5
302
+	 */
303
+	function setErrorHandling($mode = null, $options = null)
304
+	{
305
+		if (isset($this) && is_a($this, 'PEAR')) {
306
+			$setmode     = &$this->_default_error_mode;
307
+			$setoptions  = &$this->_default_error_options;
308
+		} else {
309
+			$setmode     = &$GLOBALS['_PEAR_default_error_mode'];
310
+			$setoptions  = &$GLOBALS['_PEAR_default_error_options'];
311
+		}
312
+
313
+		switch ($mode) {
314
+			case PEAR_ERROR_EXCEPTION:
315
+			case PEAR_ERROR_RETURN:
316
+			case PEAR_ERROR_PRINT:
317
+			case PEAR_ERROR_TRIGGER:
318
+			case PEAR_ERROR_DIE:
319
+			case null:
320
+				$setmode = $mode;
321
+				$setoptions = $options;
322
+				break;
323
+
324
+			case PEAR_ERROR_CALLBACK:
325
+				$setmode = $mode;
326
+				// class/object method callback
327
+				if (is_callable($options)) {
328
+					$setoptions = $options;
329
+				} else {
330
+					trigger_error("invalid error callback", E_USER_WARNING);
331
+				}
332
+				break;
333
+
334
+			default:
335
+				trigger_error("invalid error mode", E_USER_WARNING);
336
+				break;
337
+		}
338
+	}
339
+
340
+	/**
341
+	 * This method is used to tell which errors you expect to get.
342
+	 * Expected errors are always returned with error mode
343
+	 * PEAR_ERROR_RETURN.  Expected error codes are stored in a stack,
344
+	 * and this method pushes a new element onto it.  The list of
345
+	 * expected errors are in effect until they are popped off the
346
+	 * stack with the popExpect() method.
347
+	 *
348
+	 * Note that this method can not be called statically
349
+	 *
350
+	 * @param mixed $code a single error code or an array of error codes to expect
351
+	 *
352
+	 * @return int     the new depth of the "expected errors" stack
353
+	 * @access public
354
+	 */
355
+	function expectError($code = '*')
356
+	{
357
+		if (is_array($code)) {
358
+			array_push($this->_expected_errors, $code);
359
+		} else {
360
+			array_push($this->_expected_errors, array($code));
361
+		}
362
+		return count($this->_expected_errors);
363
+	}
364
+
365
+	/**
366
+	 * This method pops one element off the expected error codes
367
+	 * stack.
368
+	 *
369
+	 * @return array   the list of error codes that were popped
370
+	 */
371
+	function popExpect()
372
+	{
373
+		return array_pop($this->_expected_errors);
374
+	}
375
+
376
+	/**
377
+	 * This method checks unsets an error code if available
378
+	 *
379
+	 * @param mixed error code
380
+	 * @return bool true if the error code was unset, false otherwise
381
+	 * @access private
382
+	 * @since PHP 4.3.0
383
+	 */
384
+	function _checkDelExpect($error_code)
385
+	{
386
+		$deleted = false;
387
+		foreach ($this->_expected_errors as $key => $error_array) {
388
+			if (in_array($error_code, $error_array)) {
389
+				unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
390
+				$deleted = true;
391
+			}
392
+
393
+			// clean up empty arrays
394
+			if (0 == count($this->_expected_errors[$key])) {
395
+				unset($this->_expected_errors[$key]);
396
+			}
397
+		}
398
+
399
+		return $deleted;
400
+	}
401
+
402
+	/**
403
+	 * This method deletes all occurences of the specified element from
404
+	 * the expected error codes stack.
405
+	 *
406
+	 * @param  mixed $error_code error code that should be deleted
407
+	 * @return mixed list of error codes that were deleted or error
408
+	 * @access public
409
+	 * @since PHP 4.3.0
410
+	 */
411
+	function delExpect($error_code)
412
+	{
413
+		$deleted = false;
414
+		if ((is_array($error_code) && (0 != count($error_code)))) {
415
+			// $error_code is a non-empty array here; we walk through it trying
416
+			// to unset all values
417
+			foreach ($error_code as $key => $error) {
418
+				$deleted =  $this->_checkDelExpect($error) ? true : false;
419
+			}
420
+
421
+			return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
422
+		} elseif (!empty($error_code)) {
423
+			// $error_code comes alone, trying to unset it
424
+			if ($this->_checkDelExpect($error_code)) {
425
+				return true;
426
+			}
427
+
428
+			return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
429
+		}
430
+
431
+		// $error_code is empty
432
+		return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
433
+	}
434
+
435
+	/**
436
+	 * This method is a wrapper that returns an instance of the
437
+	 * configured error class with this object's default error
438
+	 * handling applied.  If the $mode and $options parameters are not
439
+	 * specified, the object's defaults are used.
440
+	 *
441
+	 * @param mixed $message a text error message or a PEAR error object
442
+	 *
443
+	 * @param int $code      a numeric error code (it is up to your class
444
+	 *                  to define these if you want to use codes)
445
+	 *
446
+	 * @param int $mode      One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
447
+	 *                  PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
448
+	 *                  PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION.
449
+	 *
450
+	 * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter
451
+	 *                  specifies the PHP-internal error level (one of
452
+	 *                  E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
453
+	 *                  If $mode is PEAR_ERROR_CALLBACK, this
454
+	 *                  parameter specifies the callback function or
455
+	 *                  method.  In other error modes this parameter
456
+	 *                  is ignored.
457
+	 *
458
+	 * @param string $userinfo If you need to pass along for example debug
459
+	 *                  information, this parameter is meant for that.
460
+	 *
461
+	 * @param string $error_class The returned error object will be
462
+	 *                  instantiated from this class, if specified.
463
+	 *
464
+	 * @param bool $skipmsg If true, raiseError will only pass error codes,
465
+	 *                  the error message parameter will be dropped.
466
+	 *
467
+	 * @access public
468
+	 * @return object   a PEAR error object
469
+	 * @see PEAR::setErrorHandling
470
+	 * @since PHP 4.0.5
471
+	 */
472
+	function &raiseError($message = null,
473
+						 $code = null,
474
+						 $mode = null,
475
+						 $options = null,
476
+						 $userinfo = null,
477
+						 $error_class = null,
478
+						 $skipmsg = false)
479
+	{
480
+		// The error is yet a PEAR error object
481
+		if (is_object($message)) {
482
+			$code        = $message->getCode();
483
+			$userinfo    = $message->getUserInfo();
484
+			$error_class = $message->getType();
485
+			$message->error_message_prefix = '';
486
+			$message     = $message->getMessage();
487
+		}
488
+
489
+		if (
490
+			isset($this) &&
491
+			isset($this->_expected_errors) &&
492
+			count($this->_expected_errors) > 0 &&
493
+			count($exp = end($this->_expected_errors))
494
+		) {
495
+			if ($exp[0] == "*" ||
496
+				(is_int(reset($exp)) && in_array($code, $exp)) ||
497
+				(is_string(reset($exp)) && in_array($message, $exp))
498
+			) {
499
+				$mode = PEAR_ERROR_RETURN;
500
+			}
501
+		}
502
+
503
+		// No mode given, try global ones
504
+		if ($mode === null) {
505
+			// Class error handler
506
+			if (isset($this) && isset($this->_default_error_mode)) {
507
+				$mode    = $this->_default_error_mode;
508
+				$options = $this->_default_error_options;
509
+			// Global error handler
510
+			} elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {
511
+				$mode    = $GLOBALS['_PEAR_default_error_mode'];
512
+				$options = $GLOBALS['_PEAR_default_error_options'];
513
+			}
514
+		}
515
+
516
+		if ($error_class !== null) {
517
+			$ec = $error_class;
518
+		} elseif (isset($this) && isset($this->_error_class)) {
519
+			$ec = $this->_error_class;
520
+		} else {
521
+			$ec = 'PEAR_Error';
522
+		}
523
+
524
+		if (intval(PHP_VERSION) < 5) {
525
+			// little non-eval hack to fix bug #12147
526
+			include 'PEAR/FixPHP5PEARWarnings.php';
527
+			return $a;
528
+		}
529
+
530
+		if ($skipmsg) {
531
+			$a = new $ec($code, $mode, $options, $userinfo);
532
+		} else {
533
+			$a = new $ec($message, $code, $mode, $options, $userinfo);
534
+		}
535
+
536
+		return $a;
537
+	}
538
+
539
+	/**
540
+	 * Simpler form of raiseError with fewer options.  In most cases
541
+	 * message, code and userinfo are enough.
542
+	 *
543
+	 * @param mixed $message a text error message or a PEAR error object
544
+	 *
545
+	 * @param int $code      a numeric error code (it is up to your class
546
+	 *                  to define these if you want to use codes)
547
+	 *
548
+	 * @param string $userinfo If you need to pass along for example debug
549
+	 *                  information, this parameter is meant for that.
550
+	 *
551
+	 * @access public
552
+	 * @return object   a PEAR error object
553
+	 * @see PEAR::raiseError
554
+	 */
555
+	function &throwError($message = null, $code = null, $userinfo = null)
556
+	{
557
+		if (isset($this) && is_a($this, 'PEAR')) {
558
+			$a = &$this->raiseError($message, $code, null, null, $userinfo);
559
+			return $a;
560
+		}
561
+
562
+		$a = &PEAR::raiseError($message, $code, null, null, $userinfo);
563
+		return $a;
564
+	}
565
+
566
+	function staticPushErrorHandling($mode, $options = null)
567
+	{
568
+		$stack       = &$GLOBALS['_PEAR_error_handler_stack'];
569
+		$def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
570
+		$def_options = &$GLOBALS['_PEAR_default_error_options'];
571
+		$stack[] = array($def_mode, $def_options);
572
+		switch ($mode) {
573
+			case PEAR_ERROR_EXCEPTION:
574
+			case PEAR_ERROR_RETURN:
575
+			case PEAR_ERROR_PRINT:
576
+			case PEAR_ERROR_TRIGGER:
577
+			case PEAR_ERROR_DIE:
578
+			case null:
579
+				$def_mode = $mode;
580
+				$def_options = $options;
581
+				break;
582
+
583
+			case PEAR_ERROR_CALLBACK:
584
+				$def_mode = $mode;
585
+				// class/object method callback
586
+				if (is_callable($options)) {
587
+					$def_options = $options;
588
+				} else {
589
+					trigger_error("invalid error callback", E_USER_WARNING);
590
+				}
591
+				break;
592
+
593
+			default:
594
+				trigger_error("invalid error mode", E_USER_WARNING);
595
+				break;
596
+		}
597
+		$stack[] = array($mode, $options);
598
+		return true;
599
+	}
600
+
601
+	function staticPopErrorHandling()
602
+	{
603
+		$stack = &$GLOBALS['_PEAR_error_handler_stack'];
604
+		$setmode     = &$GLOBALS['_PEAR_default_error_mode'];
605
+		$setoptions  = &$GLOBALS['_PEAR_default_error_options'];
606
+		array_pop($stack);
607
+		list($mode, $options) = $stack[sizeof($stack) - 1];
608
+		array_pop($stack);
609
+		switch ($mode) {
610
+			case PEAR_ERROR_EXCEPTION:
611
+			case PEAR_ERROR_RETURN:
612
+			case PEAR_ERROR_PRINT:
613
+			case PEAR_ERROR_TRIGGER:
614
+			case PEAR_ERROR_DIE:
615
+			case null:
616
+				$setmode = $mode;
617
+				$setoptions = $options;
618
+				break;
619
+
620
+			case PEAR_ERROR_CALLBACK:
621
+				$setmode = $mode;
622
+				// class/object method callback
623
+				if (is_callable($options)) {
624
+					$setoptions = $options;
625
+				} else {
626
+					trigger_error("invalid error callback", E_USER_WARNING);
627
+				}
628
+				break;
629
+
630
+			default:
631
+				trigger_error("invalid error mode", E_USER_WARNING);
632
+				break;
633
+		}
634
+		return true;
635
+	}
636
+
637
+	/**
638
+	 * Push a new error handler on top of the error handler options stack. With this
639
+	 * you can easily override the actual error handler for some code and restore
640
+	 * it later with popErrorHandling.
641
+	 *
642
+	 * @param mixed $mode (same as setErrorHandling)
643
+	 * @param mixed $options (same as setErrorHandling)
644
+	 *
645
+	 * @return bool Always true
646
+	 *
647
+	 * @see PEAR::setErrorHandling
648
+	 */
649
+	function pushErrorHandling($mode, $options = null)
650
+	{
651
+		$stack = &$GLOBALS['_PEAR_error_handler_stack'];
652
+		if (isset($this) && is_a($this, 'PEAR')) {
653
+			$def_mode    = &$this->_default_error_mode;
654
+			$def_options = &$this->_default_error_options;
655
+		} else {
656
+			$def_mode    = &$GLOBALS['_PEAR_default_error_mode'];
657
+			$def_options = &$GLOBALS['_PEAR_default_error_options'];
658
+		}
659
+		$stack[] = array($def_mode, $def_options);
660
+
661
+		if (isset($this) && is_a($this, 'PEAR')) {
662
+			$this->setErrorHandling($mode, $options);
663
+		} else {
664
+			PEAR::setErrorHandling($mode, $options);
665
+		}
666
+		$stack[] = array($mode, $options);
667
+		return true;
668
+	}
669
+
670
+	/**
671
+	 * Pop the last error handler used
672
+	 *
673
+	 * @return bool Always true
674
+	 *
675
+	 * @see PEAR::pushErrorHandling
676
+	 */
677
+	function popErrorHandling()
678
+	{
679
+		$stack = &$GLOBALS['_PEAR_error_handler_stack'];
680
+		array_pop($stack);
681
+		list($mode, $options) = $stack[sizeof($stack) - 1];
682
+		array_pop($stack);
683
+		if (isset($this) && is_a($this, 'PEAR')) {
684
+			$this->setErrorHandling($mode, $options);
685
+		} else {
686
+			PEAR::setErrorHandling($mode, $options);
687
+		}
688
+		return true;
689
+	}
690
+
691
+	/**
692
+	 * OS independent PHP extension load. Remember to take care
693
+	 * on the correct extension name for case sensitive OSes.
694
+	 *
695
+	 * @param string $ext The extension name
696
+	 * @return bool Success or not on the dl() call
697
+	 */
698
+	function loadExtension($ext)
699
+	{
700
+		if (extension_loaded($ext)) {
701
+			return true;
702
+		}
703
+
704
+		// if either returns true dl() will produce a FATAL error, stop that
705
+		if (
706
+			function_exists('dl') === false ||
707
+			ini_get('enable_dl') != 1 ||
708
+			ini_get('safe_mode') == 1
709
+		) {
710
+			return false;
711
+		}
712
+
713
+		if (OS_WINDOWS) {
714
+			$suffix = '.dll';
715
+		} elseif (PHP_OS == 'HP-UX') {
716
+			$suffix = '.sl';
717
+		} elseif (PHP_OS == 'AIX') {
718
+			$suffix = '.a';
719
+		} elseif (PHP_OS == 'OSX') {
720
+			$suffix = '.bundle';
721
+		} else {
722
+			$suffix = '.so';
723
+		}
724
+
725
+		return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
726
+	}
727 727
 }
728 728
 
729 729
 if (PEAR_ZE2) {
730
-    include_once 'PEAR5.php';
730
+	include_once 'PEAR5.php';
731 731
 }
732 732
 
733 733
 function _PEAR_call_destructors()
734 734
 {
735
-    global $_PEAR_destructor_object_list;
736
-    if (is_array($_PEAR_destructor_object_list) &&
737
-        sizeof($_PEAR_destructor_object_list))
738
-    {
739
-        reset($_PEAR_destructor_object_list);
740
-        if (PEAR_ZE2) {
741
-            $destructLifoExists = PEAR5::getStaticProperty('PEAR', 'destructlifo');
742
-        } else {
743
-            $destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo');
744
-        }
745
-
746
-        if ($destructLifoExists) {
747
-            $_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list);
748
-        }
749
-
750
-        while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
751
-            $classname = get_class($objref);
752
-            while ($classname) {
753
-                $destructor = "_$classname";
754
-                if (method_exists($objref, $destructor)) {
755
-                    $objref->$destructor();
756
-                    break;
757
-                } else {
758
-                    $classname = get_parent_class($classname);
759
-                }
760
-            }
761
-        }
762
-        // Empty the object list to ensure that destructors are
763
-        // not called more than once.
764
-        $_PEAR_destructor_object_list = array();
765
-    }
766
-
767
-    // Now call the shutdown functions
768
-    if (
769
-        isset($GLOBALS['_PEAR_shutdown_funcs']) &&
770
-        is_array($GLOBALS['_PEAR_shutdown_funcs']) &&
771
-        !empty($GLOBALS['_PEAR_shutdown_funcs'])
772
-    ) {
773
-        foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
774
-            call_user_func_array($value[0], $value[1]);
775
-        }
776
-    }
735
+	global $_PEAR_destructor_object_list;
736
+	if (is_array($_PEAR_destructor_object_list) &&
737
+		sizeof($_PEAR_destructor_object_list))
738
+	{
739
+		reset($_PEAR_destructor_object_list);
740
+		if (PEAR_ZE2) {
741
+			$destructLifoExists = PEAR5::getStaticProperty('PEAR', 'destructlifo');
742
+		} else {
743
+			$destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo');
744
+		}
745
+
746
+		if ($destructLifoExists) {
747
+			$_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list);
748
+		}
749
+
750
+		while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
751
+			$classname = get_class($objref);
752
+			while ($classname) {
753
+				$destructor = "_$classname";
754
+				if (method_exists($objref, $destructor)) {
755
+					$objref->$destructor();
756
+					break;
757
+				} else {
758
+					$classname = get_parent_class($classname);
759
+				}
760
+			}
761
+		}
762
+		// Empty the object list to ensure that destructors are
763
+		// not called more than once.
764
+		$_PEAR_destructor_object_list = array();
765
+	}
766
+
767
+	// Now call the shutdown functions
768
+	if (
769
+		isset($GLOBALS['_PEAR_shutdown_funcs']) &&
770
+		is_array($GLOBALS['_PEAR_shutdown_funcs']) &&
771
+		!empty($GLOBALS['_PEAR_shutdown_funcs'])
772
+	) {
773
+		foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
774
+			call_user_func_array($value[0], $value[1]);
775
+		}
776
+	}
777 777
 }
778 778
 
779 779
 /**
@@ -795,263 +795,263 @@  discard block
 block discarded – undo
795 795
  */
796 796
 class PEAR_Error
797 797
 {
798
-    var $error_message_prefix = '';
799
-    var $mode                 = PEAR_ERROR_RETURN;
800
-    var $level                = E_USER_NOTICE;
801
-    var $code                 = -1;
802
-    var $message              = '';
803
-    var $userinfo             = '';
804
-    var $backtrace            = null;
805
-
806
-    /**
807
-     * PEAR_Error constructor
808
-     *
809
-     * @param string $message  message
810
-     *
811
-     * @param int $code     (optional) error code
812
-     *
813
-     * @param int $mode     (optional) error mode, one of: PEAR_ERROR_RETURN,
814
-     * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER,
815
-     * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION
816
-     *
817
-     * @param mixed $options   (optional) error level, _OR_ in the case of
818
-     * PEAR_ERROR_CALLBACK, the callback function or object/method
819
-     * tuple.
820
-     *
821
-     * @param string $userinfo (optional) additional user/debug info
822
-     *
823
-     * @access public
824
-     *
825
-     */
826
-    function PEAR_Error($message = 'unknown error', $code = null,
827
-                        $mode = null, $options = null, $userinfo = null)
828
-    {
829
-        if ($mode === null) {
830
-            $mode = PEAR_ERROR_RETURN;
831
-        }
832
-        $this->message   = $message;
833
-        $this->code      = $code;
834
-        $this->mode      = $mode;
835
-        $this->userinfo  = $userinfo;
836
-
837
-        if (PEAR_ZE2) {
838
-            $skiptrace = PEAR5::getStaticProperty('PEAR_Error', 'skiptrace');
839
-        } else {
840
-            $skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
841
-        }
842
-
843
-        if (!$skiptrace) {
844
-            $this->backtrace = debug_backtrace();
845
-            if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
846
-                unset($this->backtrace[0]['object']);
847
-            }
848
-        }
849
-
850
-        if ($mode & PEAR_ERROR_CALLBACK) {
851
-            $this->level = E_USER_NOTICE;
852
-            $this->callback = $options;
853
-        } else {
854
-            if ($options === null) {
855
-                $options = E_USER_NOTICE;
856
-            }
857
-
858
-            $this->level = $options;
859
-            $this->callback = null;
860
-        }
861
-
862
-        if ($this->mode & PEAR_ERROR_PRINT) {
863
-            if (is_null($options) || is_int($options)) {
864
-                $format = "%s";
865
-            } else {
866
-                $format = $options;
867
-            }
868
-
869
-            printf($format, $this->getMessage());
870
-        }
871
-
872
-        if ($this->mode & PEAR_ERROR_TRIGGER) {
873
-            trigger_error($this->getMessage(), $this->level);
874
-        }
875
-
876
-        if ($this->mode & PEAR_ERROR_DIE) {
877
-            $msg = $this->getMessage();
878
-            if (is_null($options) || is_int($options)) {
879
-                $format = "%s";
880
-                if (substr($msg, -1) != "\n") {
881
-                    $msg .= "\n";
882
-                }
883
-            } else {
884
-                $format = $options;
885
-            }
886
-            die(sprintf($format, $msg));
887
-        }
888
-
889
-        if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) {
890
-            call_user_func($this->callback, $this);
891
-        }
892
-
893
-        if ($this->mode & PEAR_ERROR_EXCEPTION) {
894
-            trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
895
-            eval('$e = new Exception($this->message, $this->code);throw($e);');
896
-        }
897
-    }
898
-
899
-    /**
900
-     * Get the error mode from an error object.
901
-     *
902
-     * @return int error mode
903
-     * @access public
904
-     */
905
-    function getMode()
906
-    {
907
-        return $this->mode;
908
-    }
909
-
910
-    /**
911
-     * Get the callback function/method from an error object.
912
-     *
913
-     * @return mixed callback function or object/method array
914
-     * @access public
915
-     */
916
-    function getCallback()
917
-    {
918
-        return $this->callback;
919
-    }
920
-
921
-    /**
922
-     * Get the error message from an error object.
923
-     *
924
-     * @return  string  full error message
925
-     * @access public
926
-     */
927
-    function getMessage()
928
-    {
929
-        return ($this->error_message_prefix . $this->message);
930
-    }
931
-
932
-    /**
933
-     * Get error code from an error object
934
-     *
935
-     * @return int error code
936
-     * @access public
937
-     */
938
-     function getCode()
939
-     {
940
-        return $this->code;
941
-     }
942
-
943
-    /**
944
-     * Get the name of this error/exception.
945
-     *
946
-     * @return string error/exception name (type)
947
-     * @access public
948
-     */
949
-    function getType()
950
-    {
951
-        return get_class($this);
952
-    }
953
-
954
-    /**
955
-     * Get additional user-supplied information.
956
-     *
957
-     * @return string user-supplied information
958
-     * @access public
959
-     */
960
-    function getUserInfo()
961
-    {
962
-        return $this->userinfo;
963
-    }
964
-
965
-    /**
966
-     * Get additional debug information supplied by the application.
967
-     *
968
-     * @return string debug information
969
-     * @access public
970
-     */
971
-    function getDebugInfo()
972
-    {
973
-        return $this->getUserInfo();
974
-    }
975
-
976
-    /**
977
-     * Get the call backtrace from where the error was generated.
978
-     * Supported with PHP 4.3.0 or newer.
979
-     *
980
-     * @param int $frame (optional) what frame to fetch
981
-     * @return array Backtrace, or NULL if not available.
982
-     * @access public
983
-     */
984
-    function getBacktrace($frame = null)
985
-    {
986
-        if (defined('PEAR_IGNORE_BACKTRACE')) {
987
-            return null;
988
-        }
989
-        if ($frame === null) {
990
-            return $this->backtrace;
991
-        }
992
-        return $this->backtrace[$frame];
993
-    }
994
-
995
-    function addUserInfo($info)
996
-    {
997
-        if (empty($this->userinfo)) {
998
-            $this->userinfo = $info;
999
-        } else {
1000
-            $this->userinfo .= " ** $info";
1001
-        }
1002
-    }
1003
-
1004
-    function __toString()
1005
-    {
1006
-        return $this->getMessage();
1007
-    }
1008
-
1009
-    /**
1010
-     * Make a string representation of this object.
1011
-     *
1012
-     * @return string a string with an object summary
1013
-     * @access public
1014
-     */
1015
-    function toString()
1016
-    {
1017
-        $modes = array();
1018
-        $levels = array(E_USER_NOTICE  => 'notice',
1019
-                        E_USER_WARNING => 'warning',
1020
-                        E_USER_ERROR   => 'error');
1021
-        if ($this->mode & PEAR_ERROR_CALLBACK) {
1022
-            if (is_array($this->callback)) {
1023
-                $callback = (is_object($this->callback[0]) ?
1024
-                    strtolower(get_class($this->callback[0])) :
1025
-                    $this->callback[0]) . '::' .
1026
-                    $this->callback[1];
1027
-            } else {
1028
-                $callback = $this->callback;
1029
-            }
1030
-            return sprintf('[%s: message="%s" code=%d mode=callback '.
1031
-                           'callback=%s prefix="%s" info="%s"]',
1032
-                           strtolower(get_class($this)), $this->message, $this->code,
1033
-                           $callback, $this->error_message_prefix,
1034
-                           $this->userinfo);
1035
-        }
1036
-        if ($this->mode & PEAR_ERROR_PRINT) {
1037
-            $modes[] = 'print';
1038
-        }
1039
-        if ($this->mode & PEAR_ERROR_TRIGGER) {
1040
-            $modes[] = 'trigger';
1041
-        }
1042
-        if ($this->mode & PEAR_ERROR_DIE) {
1043
-            $modes[] = 'die';
1044
-        }
1045
-        if ($this->mode & PEAR_ERROR_RETURN) {
1046
-            $modes[] = 'return';
1047
-        }
1048
-        return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
1049
-                       'prefix="%s" info="%s"]',
1050
-                       strtolower(get_class($this)), $this->message, $this->code,
1051
-                       implode("|", $modes), $levels[$this->level],
1052
-                       $this->error_message_prefix,
1053
-                       $this->userinfo);
1054
-    }
798
+	var $error_message_prefix = '';
799
+	var $mode                 = PEAR_ERROR_RETURN;
800
+	var $level                = E_USER_NOTICE;
801
+	var $code                 = -1;
802
+	var $message              = '';
803
+	var $userinfo             = '';
804
+	var $backtrace            = null;
805
+
806
+	/**
807
+	 * PEAR_Error constructor
808
+	 *
809
+	 * @param string $message  message
810
+	 *
811
+	 * @param int $code     (optional) error code
812
+	 *
813
+	 * @param int $mode     (optional) error mode, one of: PEAR_ERROR_RETURN,
814
+	 * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER,
815
+	 * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION
816
+	 *
817
+	 * @param mixed $options   (optional) error level, _OR_ in the case of
818
+	 * PEAR_ERROR_CALLBACK, the callback function or object/method
819
+	 * tuple.
820
+	 *
821
+	 * @param string $userinfo (optional) additional user/debug info
822
+	 *
823
+	 * @access public
824
+	 *
825
+	 */
826
+	function PEAR_Error($message = 'unknown error', $code = null,
827
+						$mode = null, $options = null, $userinfo = null)
828
+	{
829
+		if ($mode === null) {
830
+			$mode = PEAR_ERROR_RETURN;
831
+		}
832
+		$this->message   = $message;
833
+		$this->code      = $code;
834
+		$this->mode      = $mode;
835
+		$this->userinfo  = $userinfo;
836
+
837
+		if (PEAR_ZE2) {
838
+			$skiptrace = PEAR5::getStaticProperty('PEAR_Error', 'skiptrace');
839
+		} else {
840
+			$skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
841
+		}
842
+
843
+		if (!$skiptrace) {
844
+			$this->backtrace = debug_backtrace();
845
+			if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
846
+				unset($this->backtrace[0]['object']);
847
+			}
848
+		}
849
+
850
+		if ($mode & PEAR_ERROR_CALLBACK) {
851
+			$this->level = E_USER_NOTICE;
852
+			$this->callback = $options;
853
+		} else {
854
+			if ($options === null) {
855
+				$options = E_USER_NOTICE;
856
+			}
857
+
858
+			$this->level = $options;
859
+			$this->callback = null;
860
+		}
861
+
862
+		if ($this->mode & PEAR_ERROR_PRINT) {
863
+			if (is_null($options) || is_int($options)) {
864
+				$format = "%s";
865
+			} else {
866
+				$format = $options;
867
+			}
868
+
869
+			printf($format, $this->getMessage());
870
+		}
871
+
872
+		if ($this->mode & PEAR_ERROR_TRIGGER) {
873
+			trigger_error($this->getMessage(), $this->level);
874
+		}
875
+
876
+		if ($this->mode & PEAR_ERROR_DIE) {
877
+			$msg = $this->getMessage();
878
+			if (is_null($options) || is_int($options)) {
879
+				$format = "%s";
880
+				if (substr($msg, -1) != "\n") {
881
+					$msg .= "\n";
882
+				}
883
+			} else {
884
+				$format = $options;
885
+			}
886
+			die(sprintf($format, $msg));
887
+		}
888
+
889
+		if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) {
890
+			call_user_func($this->callback, $this);
891
+		}
892
+
893
+		if ($this->mode & PEAR_ERROR_EXCEPTION) {
894
+			trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
895
+			eval('$e = new Exception($this->message, $this->code);throw($e);');
896
+		}
897
+	}
898
+
899
+	/**
900
+	 * Get the error mode from an error object.
901
+	 *
902
+	 * @return int error mode
903
+	 * @access public
904
+	 */
905
+	function getMode()
906
+	{
907
+		return $this->mode;
908
+	}
909
+
910
+	/**
911
+	 * Get the callback function/method from an error object.
912
+	 *
913
+	 * @return mixed callback function or object/method array
914
+	 * @access public
915
+	 */
916
+	function getCallback()
917
+	{
918
+		return $this->callback;
919
+	}
920
+
921
+	/**
922
+	 * Get the error message from an error object.
923
+	 *
924
+	 * @return  string  full error message
925
+	 * @access public
926
+	 */
927
+	function getMessage()
928
+	{
929
+		return ($this->error_message_prefix . $this->message);
930
+	}
931
+
932
+	/**
933
+	 * Get error code from an error object
934
+	 *
935
+	 * @return int error code
936
+	 * @access public
937
+	 */
938
+	 function getCode()
939
+	 {
940
+		return $this->code;
941
+	 }
942
+
943
+	/**
944
+	 * Get the name of this error/exception.
945
+	 *
946
+	 * @return string error/exception name (type)
947
+	 * @access public
948
+	 */
949
+	function getType()
950
+	{
951
+		return get_class($this);
952
+	}
953
+
954
+	/**
955
+	 * Get additional user-supplied information.
956
+	 *
957
+	 * @return string user-supplied information
958
+	 * @access public
959
+	 */
960
+	function getUserInfo()
961
+	{
962
+		return $this->userinfo;
963
+	}
964
+
965
+	/**
966
+	 * Get additional debug information supplied by the application.
967
+	 *
968
+	 * @return string debug information
969
+	 * @access public
970
+	 */
971
+	function getDebugInfo()
972
+	{
973
+		return $this->getUserInfo();
974
+	}
975
+
976
+	/**
977
+	 * Get the call backtrace from where the error was generated.
978
+	 * Supported with PHP 4.3.0 or newer.
979
+	 *
980
+	 * @param int $frame (optional) what frame to fetch
981
+	 * @return array Backtrace, or NULL if not available.
982
+	 * @access public
983
+	 */
984
+	function getBacktrace($frame = null)
985
+	{
986
+		if (defined('PEAR_IGNORE_BACKTRACE')) {
987
+			return null;
988
+		}
989
+		if ($frame === null) {
990
+			return $this->backtrace;
991
+		}
992
+		return $this->backtrace[$frame];
993
+	}
994
+
995
+	function addUserInfo($info)
996
+	{
997
+		if (empty($this->userinfo)) {
998
+			$this->userinfo = $info;
999
+		} else {
1000
+			$this->userinfo .= " ** $info";
1001
+		}
1002
+	}
1003
+
1004
+	function __toString()
1005
+	{
1006
+		return $this->getMessage();
1007
+	}
1008
+
1009
+	/**
1010
+	 * Make a string representation of this object.
1011
+	 *
1012
+	 * @return string a string with an object summary
1013
+	 * @access public
1014
+	 */
1015
+	function toString()
1016
+	{
1017
+		$modes = array();
1018
+		$levels = array(E_USER_NOTICE  => 'notice',
1019
+						E_USER_WARNING => 'warning',
1020
+						E_USER_ERROR   => 'error');
1021
+		if ($this->mode & PEAR_ERROR_CALLBACK) {
1022
+			if (is_array($this->callback)) {
1023
+				$callback = (is_object($this->callback[0]) ?
1024
+					strtolower(get_class($this->callback[0])) :
1025
+					$this->callback[0]) . '::' .
1026
+					$this->callback[1];
1027
+			} else {
1028
+				$callback = $this->callback;
1029
+			}
1030
+			return sprintf('[%s: message="%s" code=%d mode=callback '.
1031
+						   'callback=%s prefix="%s" info="%s"]',
1032
+						   strtolower(get_class($this)), $this->message, $this->code,
1033
+						   $callback, $this->error_message_prefix,
1034
+						   $this->userinfo);
1035
+		}
1036
+		if ($this->mode & PEAR_ERROR_PRINT) {
1037
+			$modes[] = 'print';
1038
+		}
1039
+		if ($this->mode & PEAR_ERROR_TRIGGER) {
1040
+			$modes[] = 'trigger';
1041
+		}
1042
+		if ($this->mode & PEAR_ERROR_DIE) {
1043
+			$modes[] = 'die';
1044
+		}
1045
+		if ($this->mode & PEAR_ERROR_RETURN) {
1046
+			$modes[] = 'return';
1047
+		}
1048
+		return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
1049
+					   'prefix="%s" info="%s"]',
1050
+					   strtolower(get_class($this)), $this->message, $this->code,
1051
+					   implode("|", $modes), $levels[$this->level],
1052
+					   $this->error_message_prefix,
1053
+					   $this->userinfo);
1054
+	}
1055 1055
 }
1056 1056
 
1057 1057
 /*
Please login to merge, or discard this patch.
Spacing   +14 added lines, -15 removed lines patch added patch discarded remove patch
@@ -22,11 +22,11 @@  discard block
 block discarded – undo
22 22
 /**#@+
23 23
  * ERROR constants
24 24
  */
25
-define('PEAR_ERROR_RETURN',     1);
26
-define('PEAR_ERROR_PRINT',      2);
27
-define('PEAR_ERROR_TRIGGER',    4);
28
-define('PEAR_ERROR_DIE',        8);
29
-define('PEAR_ERROR_CALLBACK',  16);
25
+define('PEAR_ERROR_RETURN', 1);
26
+define('PEAR_ERROR_PRINT', 2);
27
+define('PEAR_ERROR_TRIGGER', 4);
28
+define('PEAR_ERROR_DIE', 8);
29
+define('PEAR_ERROR_CALLBACK', 16);
30 30
 /**
31 31
  * WARNING: obsolete
32 32
  * @deprecated
@@ -38,12 +38,12 @@  discard block
 block discarded – undo
38 38
 
39 39
 if (substr(PHP_OS, 0, 3) == 'WIN') {
40 40
     define('OS_WINDOWS', true);
41
-    define('OS_UNIX',    false);
42
-    define('PEAR_OS',    'Windows');
41
+    define('OS_UNIX', false);
42
+    define('PEAR_OS', 'Windows');
43 43
 } else {
44 44
     define('OS_WINDOWS', false);
45
-    define('OS_UNIX',    true);
46
-    define('PEAR_OS',    'Unix'); // blatant assumption
45
+    define('OS_UNIX', true);
46
+    define('PEAR_OS', 'Unix'); // blatant assumption
47 47
 }
48 48
 
49 49
 $GLOBALS['_PEAR_default_error_mode']     = PEAR_ERROR_RETURN;
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
             // $error_code is a non-empty array here; we walk through it trying
416 416
             // to unset all values
417 417
             foreach ($error_code as $key => $error) {
418
-                $deleted =  $this->_checkDelExpect($error) ? true : false;
418
+                $deleted = $this->_checkDelExpect($error) ? true : false;
419 419
             }
420 420
 
421 421
             return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
             $suffix = '.so';
723 723
         }
724 724
 
725
-        return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
725
+        return @dl('php_' . $ext . $suffix) || @dl($ext . $suffix);
726 726
     }
727 727
 }
728 728
 
@@ -1021,13 +1021,12 @@  discard block
 block discarded – undo
1021 1021
         if ($this->mode & PEAR_ERROR_CALLBACK) {
1022 1022
             if (is_array($this->callback)) {
1023 1023
                 $callback = (is_object($this->callback[0]) ?
1024
-                    strtolower(get_class($this->callback[0])) :
1025
-                    $this->callback[0]) . '::' .
1024
+                    strtolower(get_class($this->callback[0])) : $this->callback[0]) . '::' .
1026 1025
                     $this->callback[1];
1027 1026
             } else {
1028 1027
                 $callback = $this->callback;
1029 1028
             }
1030
-            return sprintf('[%s: message="%s" code=%d mode=callback '.
1029
+            return sprintf('[%s: message="%s" code=%d mode=callback ' .
1031 1030
                            'callback=%s prefix="%s" info="%s"]',
1032 1031
                            strtolower(get_class($this)), $this->message, $this->code,
1033 1032
                            $callback, $this->error_message_prefix,
@@ -1045,7 +1044,7 @@  discard block
 block discarded – undo
1045 1044
         if ($this->mode & PEAR_ERROR_RETURN) {
1046 1045
             $modes[] = 'return';
1047 1046
         }
1048
-        return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
1047
+        return sprintf('[%s: message="%s" code=%d mode=%s level=%s ' .
1049 1048
                        'prefix="%s" info="%s"]',
1050 1049
                        strtolower(get_class($this)), $this->message, $this->code,
1051 1050
                        implode("|", $modes), $levels[$this->level],
Please login to merge, or discard this patch.
libs/PEAR.1.9.5/PEAR/Exception.php 4 patches
Spacing   +8 added lines, -10 removed lines patch added patch discarded remove patch
@@ -277,11 +277,9 @@  discard block
 block discarded – undo
277 277
                         'class' => $cause['package'],
278 278
                         'message' => $cause['message'],
279 279
                         'file' => isset($cause['context']['file']) ?
280
-                                            $cause['context']['file'] :
281
-                                            'unknown',
280
+                                            $cause['context']['file'] : 'unknown',
282 281
                         'line' => isset($cause['context']['line']) ?
283
-                                            $cause['context']['line'] :
284
-                                            'unknown',
282
+                                            $cause['context']['line'] : 'unknown',
285 283
                     );
286 284
                 }
287 285
             }
@@ -294,7 +292,7 @@  discard block
 block discarded – undo
294 292
             $this->_trace = $this->getTrace();
295 293
             if (empty($this->_trace)) {
296 294
                 $backtrace = debug_backtrace();
297
-                $this->_trace = array($backtrace[count($backtrace)-1]);
295
+                $this->_trace = array($backtrace[count($backtrace) - 1]);
298 296
             }
299 297
         }
300 298
         return $this->_trace;
@@ -325,7 +323,7 @@  discard block
 block discarded – undo
325 323
         $trace = $this->getTraceSafe();
326 324
         $causes = array();
327 325
         $this->getCauseMessage($causes);
328
-        $html =  '<table style="border: 1px" cellspacing="0">' . "\n";
326
+        $html = '<table style="border: 1px" cellspacing="0">' . "\n";
329 327
         foreach ($causes as $i => $cause) {
330 328
             $html .= '<tr><td colspan="3" style="background: #ff9999">'
331 329
                . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
@@ -350,24 +348,24 @@  discard block
 block discarded – undo
350 348
                 foreach ($v['args'] as $arg) {
351 349
                     if (is_null($arg)) $args[] = 'null';
352 350
                     elseif (is_array($arg)) $args[] = 'Array';
353
-                    elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
351
+                    elseif (is_object($arg)) $args[] = 'Object(' . get_class($arg) . ')';
354 352
                     elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
355 353
                     elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
356 354
                     else {
357
-                        $arg = (string)$arg;
355
+                        $arg = (string) $arg;
358 356
                         $str = htmlspecialchars(substr($arg, 0, 16));
359 357
                         if (strlen($arg) > 16) $str .= '&hellip;';
360 358
                         $args[] = "'" . $str . "'";
361 359
                     }
362 360
                 }
363 361
             }
364
-            $html .= '(' . implode(', ',$args) . ')'
362
+            $html .= '(' . implode(', ', $args) . ')'
365 363
                    . '</td>'
366 364
                    . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
367 365
                    . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
368 366
                    . '</td></tr>' . "\n";
369 367
         }
370
-        $html .= '<tr><td style="text-align: center;">' . ($k+1) . '</td>'
368
+        $html .= '<tr><td style="text-align: center;">' . ($k + 1) . '</td>'
371 369
                . '<td>{main}</td>'
372 370
                . '<td>&nbsp;</td></tr>' . "\n"
373 371
                . '</table>';
Please login to merge, or discard this patch.
Doc Comments   +2 added lines patch added patch discarded remove patch
@@ -117,6 +117,8 @@
 block discarded – undo
117 117
      * @param string exception message
118 118
      * @param int|Exception|PEAR_Error|array|null exception cause
119 119
      * @param int|null exception code or null
120
+     * @param string|null $message
121
+     * @param integer $p2
120 122
      */
121 123
     public function __construct($message, $p2 = null, $p3 = null)
122 124
     {
Please login to merge, or discard this patch.
Braces   +14 added lines, -7 removed lines patch added patch discarded remove patch
@@ -348,15 +348,22 @@
 block discarded – undo
348 348
             $args = array();
349 349
             if (!empty($v['args'])) {
350 350
                 foreach ($v['args'] as $arg) {
351
-                    if (is_null($arg)) $args[] = 'null';
352
-                    elseif (is_array($arg)) $args[] = 'Array';
353
-                    elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
354
-                    elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
355
-                    elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
356
-                    else {
351
+                    if (is_null($arg)) {
352
+                    	$args[] = 'null';
353
+                    } elseif (is_array($arg)) {
354
+                    	$args[] = 'Array';
355
+                    } elseif (is_object($arg)) {
356
+                    	$args[] = 'Object('.get_class($arg).')';
357
+                    } elseif (is_bool($arg)) {
358
+                    	$args[] = $arg ? 'true' : 'false';
359
+                    } elseif (is_int($arg) || is_double($arg)) {
360
+                    	$args[] = $arg;
361
+                    } else {
357 362
                         $arg = (string)$arg;
358 363
                         $str = htmlspecialchars(substr($arg, 0, 16), ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
359
-                        if (strlen($arg) > 16) $str .= '&hellip;';
364
+                        if (strlen($arg) > 16) {
365
+                        	$str .= '&hellip;';
366
+                        }
360 367
                         $args[] = "'" . $str . "'";
361 368
                     }
362 369
                 }
Please login to merge, or discard this patch.
Indentation   +291 added lines, -291 removed lines patch added patch discarded remove patch
@@ -1,22 +1,22 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 3
 /**
4
- * PEAR_Exception
5
- *
6
- * PHP versions 4 and 5
7
- *
8
- * @category   pear
9
- * @package    PEAR
10
- * @author     Tomas V. V. Cox <[email protected]>
11
- * @author     Hans Lellelid <[email protected]>
12
- * @author     Bertrand Mansion <[email protected]>
13
- * @author     Greg Beaver <[email protected]>
14
- * @copyright  1997-2009 The Authors
15
- * @license    http://opensource.org/licenses/bsd-license.php New BSD License
16
- * @version    CVS: $Id$
17
- * @link       http://pear.php.net/package/PEAR
18
- * @since      File available since Release 1.3.3
19
- */
4
+	 * PEAR_Exception
5
+	 *
6
+	 * PHP versions 4 and 5
7
+	 *
8
+	 * @category   pear
9
+	 * @package    PEAR
10
+	 * @author     Tomas V. V. Cox <[email protected]>
11
+	 * @author     Hans Lellelid <[email protected]>
12
+	 * @author     Bertrand Mansion <[email protected]>
13
+	 * @author     Greg Beaver <[email protected]>
14
+	 * @copyright  1997-2009 The Authors
15
+	 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
16
+	 * @version    CVS: $Id$
17
+	 * @link       http://pear.php.net/package/PEAR
18
+	 * @since      File available since Release 1.3.3
19
+	 */
20 20
 
21 21
 
22 22
 /**
@@ -96,294 +96,294 @@  discard block
 block discarded – undo
96 96
  */
97 97
 class PEAR_Exception extends Exception
98 98
 {
99
-    const OBSERVER_PRINT = -2;
100
-    const OBSERVER_TRIGGER = -4;
101
-    const OBSERVER_DIE = -8;
102
-    protected $cause;
103
-    private static $_observers = array();
104
-    private static $_uniqueid = 0;
105
-    private $_trace;
99
+	const OBSERVER_PRINT = -2;
100
+	const OBSERVER_TRIGGER = -4;
101
+	const OBSERVER_DIE = -8;
102
+	protected $cause;
103
+	private static $_observers = array();
104
+	private static $_uniqueid = 0;
105
+	private $_trace;
106 106
 
107
-    /**
108
-     * Supported signatures:
109
-     *  - PEAR_Exception(string $message);
110
-     *  - PEAR_Exception(string $message, int $code);
111
-     *  - PEAR_Exception(string $message, Exception $cause);
112
-     *  - PEAR_Exception(string $message, Exception $cause, int $code);
113
-     *  - PEAR_Exception(string $message, PEAR_Error $cause);
114
-     *  - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
115
-     *  - PEAR_Exception(string $message, array $causes);
116
-     *  - PEAR_Exception(string $message, array $causes, int $code);
117
-     * @param string exception message
118
-     * @param int|Exception|PEAR_Error|array|null exception cause
119
-     * @param int|null exception code or null
120
-     */
121
-    public function __construct($message, $p2 = null, $p3 = null)
122
-    {
123
-        if (is_int($p2)) {
124
-            $code = $p2;
125
-            $this->cause = null;
126
-        } elseif (is_object($p2) || is_array($p2)) {
127
-            // using is_object allows both Exception and PEAR_Error
128
-            if (is_object($p2) && !($p2 instanceof Exception)) {
129
-                if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
130
-                    throw new PEAR_Exception('exception cause must be Exception, ' .
131
-                        'array, or PEAR_Error');
132
-                }
133
-            }
134
-            $code = $p3;
135
-            if (is_array($p2) && isset($p2['message'])) {
136
-                // fix potential problem of passing in a single warning
137
-                $p2 = array($p2);
138
-            }
139
-            $this->cause = $p2;
140
-        } else {
141
-            $code = null;
142
-            $this->cause = null;
143
-        }
144
-        parent::__construct($message, $code);
145
-        $this->signal();
146
-    }
107
+	/**
108
+	 * Supported signatures:
109
+	 *  - PEAR_Exception(string $message);
110
+	 *  - PEAR_Exception(string $message, int $code);
111
+	 *  - PEAR_Exception(string $message, Exception $cause);
112
+	 *  - PEAR_Exception(string $message, Exception $cause, int $code);
113
+	 *  - PEAR_Exception(string $message, PEAR_Error $cause);
114
+	 *  - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
115
+	 *  - PEAR_Exception(string $message, array $causes);
116
+	 *  - PEAR_Exception(string $message, array $causes, int $code);
117
+	 * @param string exception message
118
+	 * @param int|Exception|PEAR_Error|array|null exception cause
119
+	 * @param int|null exception code or null
120
+	 */
121
+	public function __construct($message, $p2 = null, $p3 = null)
122
+	{
123
+		if (is_int($p2)) {
124
+			$code = $p2;
125
+			$this->cause = null;
126
+		} elseif (is_object($p2) || is_array($p2)) {
127
+			// using is_object allows both Exception and PEAR_Error
128
+			if (is_object($p2) && !($p2 instanceof Exception)) {
129
+				if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
130
+					throw new PEAR_Exception('exception cause must be Exception, ' .
131
+						'array, or PEAR_Error');
132
+				}
133
+			}
134
+			$code = $p3;
135
+			if (is_array($p2) && isset($p2['message'])) {
136
+				// fix potential problem of passing in a single warning
137
+				$p2 = array($p2);
138
+			}
139
+			$this->cause = $p2;
140
+		} else {
141
+			$code = null;
142
+			$this->cause = null;
143
+		}
144
+		parent::__construct($message, $code);
145
+		$this->signal();
146
+	}
147 147
 
148
-    /**
149
-     * @param mixed $callback  - A valid php callback, see php func is_callable()
150
-     *                         - A PEAR_Exception::OBSERVER_* constant
151
-     *                         - An array(const PEAR_Exception::OBSERVER_*,
152
-     *                           mixed $options)
153
-     * @param string $label    The name of the observer. Use this if you want
154
-     *                         to remove it later with removeObserver()
155
-     */
156
-    public static function addObserver($callback, $label = 'default')
157
-    {
158
-        self::$_observers[$label] = $callback;
159
-    }
148
+	/**
149
+	 * @param mixed $callback  - A valid php callback, see php func is_callable()
150
+	 *                         - A PEAR_Exception::OBSERVER_* constant
151
+	 *                         - An array(const PEAR_Exception::OBSERVER_*,
152
+	 *                           mixed $options)
153
+	 * @param string $label    The name of the observer. Use this if you want
154
+	 *                         to remove it later with removeObserver()
155
+	 */
156
+	public static function addObserver($callback, $label = 'default')
157
+	{
158
+		self::$_observers[$label] = $callback;
159
+	}
160 160
 
161
-    public static function removeObserver($label = 'default')
162
-    {
163
-        unset(self::$_observers[$label]);
164
-    }
161
+	public static function removeObserver($label = 'default')
162
+	{
163
+		unset(self::$_observers[$label]);
164
+	}
165 165
 
166
-    /**
167
-     * @return int unique identifier for an observer
168
-     */
169
-    public static function getUniqueId()
170
-    {
171
-        return self::$_uniqueid++;
172
-    }
166
+	/**
167
+	 * @return int unique identifier for an observer
168
+	 */
169
+	public static function getUniqueId()
170
+	{
171
+		return self::$_uniqueid++;
172
+	}
173 173
 
174
-    private function signal()
175
-    {
176
-        foreach (self::$_observers as $func) {
177
-            if (is_callable($func)) {
178
-                call_user_func($func, $this);
179
-                continue;
180
-            }
181
-            settype($func, 'array');
182
-            switch ($func[0]) {
183
-                case self::OBSERVER_PRINT :
184
-                    $f = (isset($func[1])) ? $func[1] : '%s';
185
-                    printf($f, $this->getMessage());
186
-                    break;
187
-                case self::OBSERVER_TRIGGER :
188
-                    $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
189
-                    trigger_error($this->getMessage(), $f);
190
-                    break;
191
-                case self::OBSERVER_DIE :
192
-                    $f = (isset($func[1])) ? $func[1] : '%s';
193
-                    die(printf($f, $this->getMessage()));
194
-                    break;
195
-                default:
196
-                    trigger_error('invalid observer type', E_USER_WARNING);
197
-            }
198
-        }
199
-    }
174
+	private function signal()
175
+	{
176
+		foreach (self::$_observers as $func) {
177
+			if (is_callable($func)) {
178
+				call_user_func($func, $this);
179
+				continue;
180
+			}
181
+			settype($func, 'array');
182
+			switch ($func[0]) {
183
+				case self::OBSERVER_PRINT :
184
+					$f = (isset($func[1])) ? $func[1] : '%s';
185
+					printf($f, $this->getMessage());
186
+					break;
187
+				case self::OBSERVER_TRIGGER :
188
+					$f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
189
+					trigger_error($this->getMessage(), $f);
190
+					break;
191
+				case self::OBSERVER_DIE :
192
+					$f = (isset($func[1])) ? $func[1] : '%s';
193
+					die(printf($f, $this->getMessage()));
194
+					break;
195
+				default:
196
+					trigger_error('invalid observer type', E_USER_WARNING);
197
+			}
198
+		}
199
+	}
200 200
 
201
-    /**
202
-     * Return specific error information that can be used for more detailed
203
-     * error messages or translation.
204
-     *
205
-     * This method may be overridden in child exception classes in order
206
-     * to add functionality not present in PEAR_Exception and is a placeholder
207
-     * to define API
208
-     *
209
-     * The returned array must be an associative array of parameter => value like so:
210
-     * <pre>
211
-     * array('name' => $name, 'context' => array(...))
212
-     * </pre>
213
-     * @return array
214
-     */
215
-    public function getErrorData()
216
-    {
217
-        return array();
218
-    }
201
+	/**
202
+	 * Return specific error information that can be used for more detailed
203
+	 * error messages or translation.
204
+	 *
205
+	 * This method may be overridden in child exception classes in order
206
+	 * to add functionality not present in PEAR_Exception and is a placeholder
207
+	 * to define API
208
+	 *
209
+	 * The returned array must be an associative array of parameter => value like so:
210
+	 * <pre>
211
+	 * array('name' => $name, 'context' => array(...))
212
+	 * </pre>
213
+	 * @return array
214
+	 */
215
+	public function getErrorData()
216
+	{
217
+		return array();
218
+	}
219 219
 
220
-    /**
221
-     * Returns the exception that caused this exception to be thrown
222
-     * @access public
223
-     * @return Exception|array The context of the exception
224
-     */
225
-    public function getCause()
226
-    {
227
-        return $this->cause;
228
-    }
220
+	/**
221
+	 * Returns the exception that caused this exception to be thrown
222
+	 * @access public
223
+	 * @return Exception|array The context of the exception
224
+	 */
225
+	public function getCause()
226
+	{
227
+		return $this->cause;
228
+	}
229 229
 
230
-    /**
231
-     * Function must be public to call on caused exceptions
232
-     * @param array
233
-     */
234
-    public function getCauseMessage(&$causes)
235
-    {
236
-        $trace = $this->getTraceSafe();
237
-        $cause = array('class'   => get_class($this),
238
-                       'message' => $this->message,
239
-                       'file' => 'unknown',
240
-                       'line' => 'unknown');
241
-        if (isset($trace[0])) {
242
-            if (isset($trace[0]['file'])) {
243
-                $cause['file'] = $trace[0]['file'];
244
-                $cause['line'] = $trace[0]['line'];
245
-            }
246
-        }
247
-        $causes[] = $cause;
248
-        if ($this->cause instanceof PEAR_Exception) {
249
-            $this->cause->getCauseMessage($causes);
250
-        } elseif ($this->cause instanceof Exception) {
251
-            $causes[] = array('class'   => get_class($this->cause),
252
-                              'message' => $this->cause->getMessage(),
253
-                              'file' => $this->cause->getFile(),
254
-                              'line' => $this->cause->getLine());
255
-        } elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
256
-            $causes[] = array('class' => get_class($this->cause),
257
-                              'message' => $this->cause->getMessage(),
258
-                              'file' => 'unknown',
259
-                              'line' => 'unknown');
260
-        } elseif (is_array($this->cause)) {
261
-            foreach ($this->cause as $cause) {
262
-                if ($cause instanceof PEAR_Exception) {
263
-                    $cause->getCauseMessage($causes);
264
-                } elseif ($cause instanceof Exception) {
265
-                    $causes[] = array('class'   => get_class($cause),
266
-                                   'message' => $cause->getMessage(),
267
-                                   'file' => $cause->getFile(),
268
-                                   'line' => $cause->getLine());
269
-                } elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
270
-                    $causes[] = array('class' => get_class($cause),
271
-                                      'message' => $cause->getMessage(),
272
-                                      'file' => 'unknown',
273
-                                      'line' => 'unknown');
274
-                } elseif (is_array($cause) && isset($cause['message'])) {
275
-                    // PEAR_ErrorStack warning
276
-                    $causes[] = array(
277
-                        'class' => $cause['package'],
278
-                        'message' => $cause['message'],
279
-                        'file' => isset($cause['context']['file']) ?
280
-                                            $cause['context']['file'] :
281
-                                            'unknown',
282
-                        'line' => isset($cause['context']['line']) ?
283
-                                            $cause['context']['line'] :
284
-                                            'unknown',
285
-                    );
286
-                }
287
-            }
288
-        }
289
-    }
230
+	/**
231
+	 * Function must be public to call on caused exceptions
232
+	 * @param array
233
+	 */
234
+	public function getCauseMessage(&$causes)
235
+	{
236
+		$trace = $this->getTraceSafe();
237
+		$cause = array('class'   => get_class($this),
238
+					   'message' => $this->message,
239
+					   'file' => 'unknown',
240
+					   'line' => 'unknown');
241
+		if (isset($trace[0])) {
242
+			if (isset($trace[0]['file'])) {
243
+				$cause['file'] = $trace[0]['file'];
244
+				$cause['line'] = $trace[0]['line'];
245
+			}
246
+		}
247
+		$causes[] = $cause;
248
+		if ($this->cause instanceof PEAR_Exception) {
249
+			$this->cause->getCauseMessage($causes);
250
+		} elseif ($this->cause instanceof Exception) {
251
+			$causes[] = array('class'   => get_class($this->cause),
252
+							  'message' => $this->cause->getMessage(),
253
+							  'file' => $this->cause->getFile(),
254
+							  'line' => $this->cause->getLine());
255
+		} elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
256
+			$causes[] = array('class' => get_class($this->cause),
257
+							  'message' => $this->cause->getMessage(),
258
+							  'file' => 'unknown',
259
+							  'line' => 'unknown');
260
+		} elseif (is_array($this->cause)) {
261
+			foreach ($this->cause as $cause) {
262
+				if ($cause instanceof PEAR_Exception) {
263
+					$cause->getCauseMessage($causes);
264
+				} elseif ($cause instanceof Exception) {
265
+					$causes[] = array('class'   => get_class($cause),
266
+								   'message' => $cause->getMessage(),
267
+								   'file' => $cause->getFile(),
268
+								   'line' => $cause->getLine());
269
+				} elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
270
+					$causes[] = array('class' => get_class($cause),
271
+									  'message' => $cause->getMessage(),
272
+									  'file' => 'unknown',
273
+									  'line' => 'unknown');
274
+				} elseif (is_array($cause) && isset($cause['message'])) {
275
+					// PEAR_ErrorStack warning
276
+					$causes[] = array(
277
+						'class' => $cause['package'],
278
+						'message' => $cause['message'],
279
+						'file' => isset($cause['context']['file']) ?
280
+											$cause['context']['file'] :
281
+											'unknown',
282
+						'line' => isset($cause['context']['line']) ?
283
+											$cause['context']['line'] :
284
+											'unknown',
285
+					);
286
+				}
287
+			}
288
+		}
289
+	}
290 290
 
291
-    public function getTraceSafe()
292
-    {
293
-        if (!isset($this->_trace)) {
294
-            $this->_trace = $this->getTrace();
295
-            if (empty($this->_trace)) {
296
-                $backtrace = debug_backtrace();
297
-                $this->_trace = array($backtrace[count($backtrace)-1]);
298
-            }
299
-        }
300
-        return $this->_trace;
301
-    }
291
+	public function getTraceSafe()
292
+	{
293
+		if (!isset($this->_trace)) {
294
+			$this->_trace = $this->getTrace();
295
+			if (empty($this->_trace)) {
296
+				$backtrace = debug_backtrace();
297
+				$this->_trace = array($backtrace[count($backtrace)-1]);
298
+			}
299
+		}
300
+		return $this->_trace;
301
+	}
302 302
 
303
-    public function getErrorClass()
304
-    {
305
-        $trace = $this->getTraceSafe();
306
-        return $trace[0]['class'];
307
-    }
303
+	public function getErrorClass()
304
+	{
305
+		$trace = $this->getTraceSafe();
306
+		return $trace[0]['class'];
307
+	}
308 308
 
309
-    public function getErrorMethod()
310
-    {
311
-        $trace = $this->getTraceSafe();
312
-        return $trace[0]['function'];
313
-    }
309
+	public function getErrorMethod()
310
+	{
311
+		$trace = $this->getTraceSafe();
312
+		return $trace[0]['function'];
313
+	}
314 314
 
315
-    public function __toString()
316
-    {
317
-        if (isset($_SERVER['REQUEST_URI'])) {
318
-            return $this->toHtml();
319
-        }
320
-        return $this->toText();
321
-    }
315
+	public function __toString()
316
+	{
317
+		if (isset($_SERVER['REQUEST_URI'])) {
318
+			return $this->toHtml();
319
+		}
320
+		return $this->toText();
321
+	}
322 322
 
323
-    public function toHtml()
324
-    {
325
-        $trace = $this->getTraceSafe();
326
-        $causes = array();
327
-        $this->getCauseMessage($causes);
328
-        $html =  '<table style="border: 1px" cellspacing="0">' . "\n";
329
-        foreach ($causes as $i => $cause) {
330
-            $html .= '<tr><td colspan="3" style="background: #ff9999">'
331
-               . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
332
-               . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
333
-               . 'on line <b>' . $cause['line'] . '</b>'
334
-               . "</td></tr>\n";
335
-        }
336
-        $html .= '<tr><td colspan="3" style="background-color: #aaaaaa; text-align: center; font-weight: bold;">Exception trace</td></tr>' . "\n"
337
-               . '<tr><td style="text-align: center; background: #cccccc; width:20px; font-weight: bold;">#</td>'
338
-               . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Function</td>'
339
-               . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Location</td></tr>' . "\n";
323
+	public function toHtml()
324
+	{
325
+		$trace = $this->getTraceSafe();
326
+		$causes = array();
327
+		$this->getCauseMessage($causes);
328
+		$html =  '<table style="border: 1px" cellspacing="0">' . "\n";
329
+		foreach ($causes as $i => $cause) {
330
+			$html .= '<tr><td colspan="3" style="background: #ff9999">'
331
+			   . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
332
+			   . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
333
+			   . 'on line <b>' . $cause['line'] . '</b>'
334
+			   . "</td></tr>\n";
335
+		}
336
+		$html .= '<tr><td colspan="3" style="background-color: #aaaaaa; text-align: center; font-weight: bold;">Exception trace</td></tr>' . "\n"
337
+			   . '<tr><td style="text-align: center; background: #cccccc; width:20px; font-weight: bold;">#</td>'
338
+			   . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Function</td>'
339
+			   . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Location</td></tr>' . "\n";
340 340
 
341
-        foreach ($trace as $k => $v) {
342
-            $html .= '<tr><td style="text-align: center;">' . $k . '</td>'
343
-                   . '<td>';
344
-            if (!empty($v['class'])) {
345
-                $html .= $v['class'] . $v['type'];
346
-            }
347
-            $html .= $v['function'];
348
-            $args = array();
349
-            if (!empty($v['args'])) {
350
-                foreach ($v['args'] as $arg) {
351
-                    if (is_null($arg)) $args[] = 'null';
352
-                    elseif (is_array($arg)) $args[] = 'Array';
353
-                    elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
354
-                    elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
355
-                    elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
356
-                    else {
357
-                        $arg = (string)$arg;
358
-                        $str = htmlspecialchars(substr($arg, 0, 16));
359
-                        if (strlen($arg) > 16) $str .= '&hellip;';
360
-                        $args[] = "'" . $str . "'";
361
-                    }
362
-                }
363
-            }
364
-            $html .= '(' . implode(', ',$args) . ')'
365
-                   . '</td>'
366
-                   . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
367
-                   . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
368
-                   . '</td></tr>' . "\n";
369
-        }
370
-        $html .= '<tr><td style="text-align: center;">' . ($k+1) . '</td>'
371
-               . '<td>{main}</td>'
372
-               . '<td>&nbsp;</td></tr>' . "\n"
373
-               . '</table>';
374
-        return $html;
375
-    }
341
+		foreach ($trace as $k => $v) {
342
+			$html .= '<tr><td style="text-align: center;">' . $k . '</td>'
343
+				   . '<td>';
344
+			if (!empty($v['class'])) {
345
+				$html .= $v['class'] . $v['type'];
346
+			}
347
+			$html .= $v['function'];
348
+			$args = array();
349
+			if (!empty($v['args'])) {
350
+				foreach ($v['args'] as $arg) {
351
+					if (is_null($arg)) $args[] = 'null';
352
+					elseif (is_array($arg)) $args[] = 'Array';
353
+					elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
354
+					elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
355
+					elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
356
+					else {
357
+						$arg = (string)$arg;
358
+						$str = htmlspecialchars(substr($arg, 0, 16));
359
+						if (strlen($arg) > 16) $str .= '&hellip;';
360
+						$args[] = "'" . $str . "'";
361
+					}
362
+				}
363
+			}
364
+			$html .= '(' . implode(', ',$args) . ')'
365
+				   . '</td>'
366
+				   . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
367
+				   . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
368
+				   . '</td></tr>' . "\n";
369
+		}
370
+		$html .= '<tr><td style="text-align: center;">' . ($k+1) . '</td>'
371
+			   . '<td>{main}</td>'
372
+			   . '<td>&nbsp;</td></tr>' . "\n"
373
+			   . '</table>';
374
+		return $html;
375
+	}
376 376
 
377
-    public function toText()
378
-    {
379
-        $causes = array();
380
-        $this->getCauseMessage($causes);
381
-        $causeMsg = '';
382
-        foreach ($causes as $i => $cause) {
383
-            $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
384
-                   . $cause['message'] . ' in ' . $cause['file']
385
-                   . ' on line ' . $cause['line'] . "\n";
386
-        }
387
-        return $causeMsg . $this->getTraceAsString();
388
-    }
377
+	public function toText()
378
+	{
379
+		$causes = array();
380
+		$this->getCauseMessage($causes);
381
+		$causeMsg = '';
382
+		foreach ($causes as $i => $cause) {
383
+			$causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
384
+				   . $cause['message'] . ' in ' . $cause['file']
385
+				   . ' on line ' . $cause['line'] . "\n";
386
+		}
387
+		return $causeMsg . $this->getTraceAsString();
388
+	}
389 389
 }
390 390
\ No newline at end of file
Please login to merge, or discard this patch.
libs/PEAR.1.9/HTTP/Request.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -18,28 +18,28 @@
 block discarded – undo
18 18
 	}
19 19
 
20 20
 	public function getResponseCode() {
21
-		if($this->response)
21
+		if ($this->response)
22 22
 		{
23 23
 			return $this->response->getStatus();
24 24
 		}
25 25
 	}
26 26
 
27 27
 	public function getResponseHeader() {
28
-		if($this->response)
28
+		if ($this->response)
29 29
 		{
30 30
 			return $this->response->getHeader();	
31 31
 		}
32 32
 	}
33 33
 
34 34
 	public function getResponseBody() {
35
-		if($this->response)
35
+		if ($this->response)
36 36
 		{
37 37
 			return $this->response->getBody();
38 38
 		}
39 39
 	}
40 40
 
41 41
 	public function getResponseCookies() {
42
-		if($this->response)
42
+		if ($this->response)
43 43
 		{
44 44
 			return $this->response->getCookies();
45 45
 		}
Please login to merge, or discard this patch.
libs/PEAR.1.9/HTTP/Request2/Adapter.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -1,45 +1,45 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Base class for HTTP_Request2 adapters
4
- *
5
- * PHP version 5
6
- *
7
- * LICENSE:
8
- *
9
- * Copyright (c) 2008, 2009, Alexey Borzov <[email protected]>
10
- * All rights reserved.
11
- *
12
- * Redistribution and use in source and binary forms, with or without
13
- * modification, are permitted provided that the following conditions
14
- * are met:
15
- *
16
- *    * Redistributions of source code must retain the above copyright
17
- *      notice, this list of conditions and the following disclaimer.
18
- *    * Redistributions in binary form must reproduce the above copyright
19
- *      notice, this list of conditions and the following disclaimer in the
20
- *      documentation and/or other materials provided with the distribution.
21
- *    * The names of the authors may not be used to endorse or promote products
22
- *      derived from this software without specific prior written permission.
23
- *
24
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
- *
36
- * @category   HTTP
37
- * @package    HTTP_Request2
38
- * @author     Alexey Borzov <[email protected]>
39
- * @license    http://opensource.org/licenses/bsd-license.php New BSD License
40
- * @version    SVN: $Id: Adapter.php 291118 2009-11-21 17:58:23Z avb $
41
- * @link       http://pear.php.net/package/HTTP_Request2
42
- */
3
+	 * Base class for HTTP_Request2 adapters
4
+	 *
5
+	 * PHP version 5
6
+	 *
7
+	 * LICENSE:
8
+	 *
9
+	 * Copyright (c) 2008, 2009, Alexey Borzov <[email protected]>
10
+	 * All rights reserved.
11
+	 *
12
+	 * Redistribution and use in source and binary forms, with or without
13
+	 * modification, are permitted provided that the following conditions
14
+	 * are met:
15
+	 *
16
+	 *    * Redistributions of source code must retain the above copyright
17
+	 *      notice, this list of conditions and the following disclaimer.
18
+	 *    * Redistributions in binary form must reproduce the above copyright
19
+	 *      notice, this list of conditions and the following disclaimer in the
20
+	 *      documentation and/or other materials provided with the distribution.
21
+	 *    * The names of the authors may not be used to endorse or promote products
22
+	 *      derived from this software without specific prior written permission.
23
+	 *
24
+	 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25
+	 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26
+	 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27
+	 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28
+	 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29
+	 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30
+	 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31
+	 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32
+	 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33
+	 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
+	 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+	 *
36
+	 * @category   HTTP
37
+	 * @package    HTTP_Request2
38
+	 * @author     Alexey Borzov <[email protected]>
39
+	 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
40
+	 * @version    SVN: $Id: Adapter.php 291118 2009-11-21 17:58:23Z avb $
41
+	 * @link       http://pear.php.net/package/HTTP_Request2
42
+	 */
43 43
 
44 44
 /**
45 45
  * Class representing a HTTP response
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
     * A list of methods that MUST NOT have a request body, per RFC 2616
65 65
     * @var  array
66 66
     */
67
-    protected static $bodyDisallowed = array('TRACE');
67
+	protected static $bodyDisallowed = array('TRACE');
68 68
 
69 69
    /**
70 70
     * Methods having defined semantics for request body
@@ -76,26 +76,26 @@  discard block
 block discarded – undo
76 76
     * @link http://pear.php.net/bugs/bug.php?id=12900
77 77
     * @link http://pear.php.net/bugs/bug.php?id=14740
78 78
     */
79
-    protected static $bodyRequired = array('POST', 'PUT');
79
+	protected static $bodyRequired = array('POST', 'PUT');
80 80
 
81 81
    /**
82 82
     * Request being sent
83 83
     * @var  HTTP_Request2
84 84
     */
85
-    protected $request;
85
+	protected $request;
86 86
 
87 87
    /**
88 88
     * Request body
89 89
     * @var  string|resource|HTTP_Request2_MultipartBody
90 90
     * @see  HTTP_Request2::getBody()
91 91
     */
92
-    protected $requestBody;
92
+	protected $requestBody;
93 93
 
94 94
    /**
95 95
     * Length of the request body
96 96
     * @var  integer
97 97
     */
98
-    protected $contentLength;
98
+	protected $contentLength;
99 99
 
100 100
    /**
101 101
     * Sends request to the remote server and returns its response
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
     * @return   HTTP_Request2_Response
105 105
     * @throws   HTTP_Request2_Exception
106 106
     */
107
-    abstract public function sendRequest(HTTP_Request2 $request);
107
+	abstract public function sendRequest(HTTP_Request2 $request);
108 108
 
109 109
    /**
110 110
     * Calculates length of the request body, adds proper headers
@@ -113,42 +113,42 @@  discard block
 block discarded – undo
113 113
     *                   add proper 'Content-Length' and 'Content-Type' headers
114 114
     *                   to this array (or remove them if not needed)
115 115
     */
116
-    protected function calculateRequestLength(&$headers)
117
-    {
118
-        $this->requestBody = $this->request->getBody();
116
+	protected function calculateRequestLength(&$headers)
117
+	{
118
+		$this->requestBody = $this->request->getBody();
119 119
 
120
-        if (is_string($this->requestBody)) {
121
-            $this->contentLength = strlen($this->requestBody);
122
-        } elseif (is_resource($this->requestBody)) {
123
-            $stat = fstat($this->requestBody);
124
-            $this->contentLength = $stat['size'];
125
-            rewind($this->requestBody);
126
-        } else {
127
-            $this->contentLength = $this->requestBody->getLength();
128
-            $headers['content-type'] = 'multipart/form-data; boundary=' .
129
-                                       $this->requestBody->getBoundary();
130
-            $this->requestBody->rewind();
131
-        }
120
+		if (is_string($this->requestBody)) {
121
+			$this->contentLength = strlen($this->requestBody);
122
+		} elseif (is_resource($this->requestBody)) {
123
+			$stat = fstat($this->requestBody);
124
+			$this->contentLength = $stat['size'];
125
+			rewind($this->requestBody);
126
+		} else {
127
+			$this->contentLength = $this->requestBody->getLength();
128
+			$headers['content-type'] = 'multipart/form-data; boundary=' .
129
+									   $this->requestBody->getBoundary();
130
+			$this->requestBody->rewind();
131
+		}
132 132
 
133
-        if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
134
-            0 == $this->contentLength
135
-        ) {
136
-            // No body: send a Content-Length header nonetheless (request #12900),
137
-            // but do that only for methods that require a body (bug #14740)
138
-            if (in_array($this->request->getMethod(), self::$bodyRequired)) {
139
-                $headers['content-length'] = 0;
140
-            } else {
141
-                unset($headers['content-length']);
142
-                // if the method doesn't require a body and doesn't have a
143
-                // body, don't send a Content-Type header. (request #16799)
144
-                unset($headers['content-type']);
145
-            }
146
-        } else {
147
-            if (empty($headers['content-type'])) {
148
-                $headers['content-type'] = 'application/x-www-form-urlencoded';
149
-            }
150
-            $headers['content-length'] = $this->contentLength;
151
-        }
152
-    }
133
+		if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
134
+			0 == $this->contentLength
135
+		) {
136
+			// No body: send a Content-Length header nonetheless (request #12900),
137
+			// but do that only for methods that require a body (bug #14740)
138
+			if (in_array($this->request->getMethod(), self::$bodyRequired)) {
139
+				$headers['content-length'] = 0;
140
+			} else {
141
+				unset($headers['content-length']);
142
+				// if the method doesn't require a body and doesn't have a
143
+				// body, don't send a Content-Type header. (request #16799)
144
+				unset($headers['content-type']);
145
+			}
146
+		} else {
147
+			if (empty($headers['content-type'])) {
148
+				$headers['content-type'] = 'application/x-www-form-urlencoded';
149
+			}
150
+			$headers['content-length'] = $this->contentLength;
151
+		}
152
+	}
153 153
 }
154 154
 ?>
Please login to merge, or discard this patch.
libs/PEAR.1.9/HTTP/Request2/Adapter/Mock.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -1,45 +1,45 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Mock adapter intended for testing
4
- *
5
- * PHP version 5
6
- *
7
- * LICENSE:
8
- *
9
- * Copyright (c) 2008, 2009, Alexey Borzov <[email protected]>
10
- * All rights reserved.
11
- *
12
- * Redistribution and use in source and binary forms, with or without
13
- * modification, are permitted provided that the following conditions
14
- * are met:
15
- *
16
- *    * Redistributions of source code must retain the above copyright
17
- *      notice, this list of conditions and the following disclaimer.
18
- *    * Redistributions in binary form must reproduce the above copyright
19
- *      notice, this list of conditions and the following disclaimer in the
20
- *      documentation and/or other materials provided with the distribution.
21
- *    * The names of the authors may not be used to endorse or promote products
22
- *      derived from this software without specific prior written permission.
23
- *
24
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
- *
36
- * @category   HTTP
37
- * @package    HTTP_Request2
38
- * @author     Alexey Borzov <[email protected]>
39
- * @license    http://opensource.org/licenses/bsd-license.php New BSD License
40
- * @version    SVN: $Id: Mock.php 290192 2009-11-03 21:29:32Z avb $
41
- * @link       http://pear.php.net/package/HTTP_Request2
42
- */
3
+	 * Mock adapter intended for testing
4
+	 *
5
+	 * PHP version 5
6
+	 *
7
+	 * LICENSE:
8
+	 *
9
+	 * Copyright (c) 2008, 2009, Alexey Borzov <[email protected]>
10
+	 * All rights reserved.
11
+	 *
12
+	 * Redistribution and use in source and binary forms, with or without
13
+	 * modification, are permitted provided that the following conditions
14
+	 * are met:
15
+	 *
16
+	 *    * Redistributions of source code must retain the above copyright
17
+	 *      notice, this list of conditions and the following disclaimer.
18
+	 *    * Redistributions in binary form must reproduce the above copyright
19
+	 *      notice, this list of conditions and the following disclaimer in the
20
+	 *      documentation and/or other materials provided with the distribution.
21
+	 *    * The names of the authors may not be used to endorse or promote products
22
+	 *      derived from this software without specific prior written permission.
23
+	 *
24
+	 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25
+	 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26
+	 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27
+	 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28
+	 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29
+	 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30
+	 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31
+	 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32
+	 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33
+	 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
+	 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+	 *
36
+	 * @category   HTTP
37
+	 * @package    HTTP_Request2
38
+	 * @author     Alexey Borzov <[email protected]>
39
+	 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
40
+	 * @version    SVN: $Id: Mock.php 290192 2009-11-03 21:29:32Z avb $
41
+	 * @link       http://pear.php.net/package/HTTP_Request2
42
+	 */
43 43
 
44 44
 /**
45 45
  * Base class for HTTP_Request2 adapters
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
     * A queue of responses to be returned by sendRequest()
75 75
     * @var  array
76 76
     */
77
-    protected $responses = array();
77
+	protected $responses = array();
78 78
 
79 79
    /**
80 80
     * Returns the next response from the queue built by addResponse()
@@ -86,23 +86,23 @@  discard block
 block discarded – undo
86 86
     * @return   HTTP_Request2_Response
87 87
     * @throws   Exception
88 88
     */
89
-    public function sendRequest(HTTP_Request2 $request)
90
-    {
91
-        if (count($this->responses) > 0) {
92
-            $response = array_shift($this->responses);
93
-            if ($response instanceof HTTP_Request2_Response) {
94
-                return $response;
95
-            } else {
96
-                // rethrow the exception
97
-                $class   = get_class($response);
98
-                $message = $response->getMessage();
99
-                $code    = $response->getCode();
100
-                throw new $class($message, $code);
101
-            }
102
-        } else {
103
-            return self::createResponseFromString("HTTP/1.1 400 Bad Request\r\n\r\n");
104
-        }
105
-    }
89
+	public function sendRequest(HTTP_Request2 $request)
90
+	{
91
+		if (count($this->responses) > 0) {
92
+			$response = array_shift($this->responses);
93
+			if ($response instanceof HTTP_Request2_Response) {
94
+				return $response;
95
+			} else {
96
+				// rethrow the exception
97
+				$class   = get_class($response);
98
+				$message = $response->getMessage();
99
+				$code    = $response->getCode();
100
+				throw new $class($message, $code);
101
+			}
102
+		} else {
103
+			return self::createResponseFromString("HTTP/1.1 400 Bad Request\r\n\r\n");
104
+		}
105
+	}
106 106
 
107 107
    /**
108 108
     * Adds response to the queue
@@ -111,19 +111,19 @@  discard block
 block discarded – undo
111 111
     *                   an instance of HTTP_Request2_Response or Exception
112 112
     * @throws   HTTP_Request2_Exception
113 113
     */
114
-    public function addResponse($response)
115
-    {
116
-        if (is_string($response)) {
117
-            $response = self::createResponseFromString($response);
118
-        } elseif (is_resource($response)) {
119
-            $response = self::createResponseFromFile($response);
120
-        } elseif (!$response instanceof HTTP_Request2_Response &&
121
-                  !$response instanceof Exception
122
-        ) {
123
-            throw new HTTP_Request2_Exception('Parameter is not a valid response');
124
-        }
125
-        $this->responses[] = $response;
126
-    }
114
+	public function addResponse($response)
115
+	{
116
+		if (is_string($response)) {
117
+			$response = self::createResponseFromString($response);
118
+		} elseif (is_resource($response)) {
119
+			$response = self::createResponseFromFile($response);
120
+		} elseif (!$response instanceof HTTP_Request2_Response &&
121
+				  !$response instanceof Exception
122
+		) {
123
+			throw new HTTP_Request2_Exception('Parameter is not a valid response');
124
+		}
125
+		$this->responses[] = $response;
126
+	}
127 127
 
128 128
    /**
129 129
     * Creates a new HTTP_Request2_Response object from a string
@@ -132,20 +132,20 @@  discard block
 block discarded – undo
132 132
     * @return   HTTP_Request2_Response
133 133
     * @throws   HTTP_Request2_Exception
134 134
     */
135
-    public static function createResponseFromString($str)
136
-    {
137
-        $parts       = preg_split('!(\r?\n){2}!m', $str, 2);
138
-        $headerLines = explode("\n", $parts[0]);
139
-        $response    = new HTTP_Request2_Response(array_shift($headerLines));
140
-        foreach ($headerLines as $headerLine) {
141
-            $response->parseHeaderLine($headerLine);
142
-        }
143
-        $response->parseHeaderLine('');
144
-        if (isset($parts[1])) {
145
-            $response->appendBody($parts[1]);
146
-        }
147
-        return $response;
148
-    }
135
+	public static function createResponseFromString($str)
136
+	{
137
+		$parts       = preg_split('!(\r?\n){2}!m', $str, 2);
138
+		$headerLines = explode("\n", $parts[0]);
139
+		$response    = new HTTP_Request2_Response(array_shift($headerLines));
140
+		foreach ($headerLines as $headerLine) {
141
+			$response->parseHeaderLine($headerLine);
142
+		}
143
+		$response->parseHeaderLine('');
144
+		if (isset($parts[1])) {
145
+			$response->appendBody($parts[1]);
146
+		}
147
+		return $response;
148
+	}
149 149
 
150 150
    /**
151 151
     * Creates a new HTTP_Request2_Response object from a file
@@ -154,18 +154,18 @@  discard block
 block discarded – undo
154 154
     * @return   HTTP_Request2_Response
155 155
     * @throws   HTTP_Request2_Exception
156 156
     */
157
-    public static function createResponseFromFile($fp)
158
-    {
159
-        $response = new HTTP_Request2_Response(fgets($fp));
160
-        do {
161
-            $headerLine = fgets($fp);
162
-            $response->parseHeaderLine($headerLine);
163
-        } while ('' != trim($headerLine));
157
+	public static function createResponseFromFile($fp)
158
+	{
159
+		$response = new HTTP_Request2_Response(fgets($fp));
160
+		do {
161
+			$headerLine = fgets($fp);
162
+			$response->parseHeaderLine($headerLine);
163
+		} while ('' != trim($headerLine));
164 164
 
165
-        while (!feof($fp)) {
166
-            $response->appendBody(fread($fp, 8192));
167
-        }
168
-        return $response;
169
-    }
165
+		while (!feof($fp)) {
166
+			$response->appendBody(fread($fp, 8192));
167
+		}
168
+		return $response;
169
+	}
170 170
 }
171 171
 ?>
172 172
\ No newline at end of file
Please login to merge, or discard this patch.
libs/PEAR.1.9/HTTP/Request2/Adapter/Socket.php 2 patches
Indentation   +759 added lines, -759 removed lines patch added patch discarded remove patch
@@ -1,45 +1,45 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Socket-based adapter for HTTP_Request2
4
- *
5
- * PHP version 5
6
- *
7
- * LICENSE:
8
- *
9
- * Copyright (c) 2008, 2009, Alexey Borzov <[email protected]>
10
- * All rights reserved.
11
- *
12
- * Redistribution and use in source and binary forms, with or without
13
- * modification, are permitted provided that the following conditions
14
- * are met:
15
- *
16
- *    * Redistributions of source code must retain the above copyright
17
- *      notice, this list of conditions and the following disclaimer.
18
- *    * Redistributions in binary form must reproduce the above copyright
19
- *      notice, this list of conditions and the following disclaimer in the
20
- *      documentation and/or other materials provided with the distribution.
21
- *    * The names of the authors may not be used to endorse or promote products
22
- *      derived from this software without specific prior written permission.
23
- *
24
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
- *
36
- * @category   HTTP
37
- * @package    HTTP_Request2
38
- * @author     Alexey Borzov <[email protected]>
39
- * @license    http://opensource.org/licenses/bsd-license.php New BSD License
40
- * @version    SVN: $Id: Socket.php 290921 2009-11-18 17:31:58Z avb $
41
- * @link       http://pear.php.net/package/HTTP_Request2
42
- */
3
+	 * Socket-based adapter for HTTP_Request2
4
+	 *
5
+	 * PHP version 5
6
+	 *
7
+	 * LICENSE:
8
+	 *
9
+	 * Copyright (c) 2008, 2009, Alexey Borzov <[email protected]>
10
+	 * All rights reserved.
11
+	 *
12
+	 * Redistribution and use in source and binary forms, with or without
13
+	 * modification, are permitted provided that the following conditions
14
+	 * are met:
15
+	 *
16
+	 *    * Redistributions of source code must retain the above copyright
17
+	 *      notice, this list of conditions and the following disclaimer.
18
+	 *    * Redistributions in binary form must reproduce the above copyright
19
+	 *      notice, this list of conditions and the following disclaimer in the
20
+	 *      documentation and/or other materials provided with the distribution.
21
+	 *    * The names of the authors may not be used to endorse or promote products
22
+	 *      derived from this software without specific prior written permission.
23
+	 *
24
+	 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25
+	 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26
+	 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27
+	 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28
+	 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29
+	 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30
+	 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31
+	 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
32
+	 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33
+	 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34
+	 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+	 *
36
+	 * @category   HTTP
37
+	 * @package    HTTP_Request2
38
+	 * @author     Alexey Borzov <[email protected]>
39
+	 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
40
+	 * @version    SVN: $Id: Socket.php 290921 2009-11-18 17:31:58Z avb $
41
+	 * @link       http://pear.php.net/package/HTTP_Request2
42
+	 */
43 43
 
44 44
 /**
45 45
  * Base class for HTTP_Request2 adapters
@@ -62,19 +62,19 @@  discard block
 block discarded – undo
62 62
    /**
63 63
     * Regular expression for 'token' rule from RFC 2616
64 64
     */
65
-    const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';
65
+	const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';
66 66
 
67 67
    /**
68 68
     * Regular expression for 'quoted-string' rule from RFC 2616
69 69
     */
70
-    const REGEXP_QUOTED_STRING = '"(?:\\\\.|[^\\\\"])*"';
70
+	const REGEXP_QUOTED_STRING = '"(?:\\\\.|[^\\\\"])*"';
71 71
 
72 72
    /**
73 73
     * Connected sockets, needed for Keep-Alive support
74 74
     * @var  array
75 75
     * @see  connect()
76 76
     */
77
-    protected static $sockets = array();
77
+	protected static $sockets = array();
78 78
 
79 79
    /**
80 80
     * Data for digest authentication scheme
@@ -88,39 +88,39 @@  discard block
 block discarded – undo
88 88
     *
89 89
     * @var  array
90 90
     */
91
-    protected static $challenges = array();
91
+	protected static $challenges = array();
92 92
 
93 93
    /**
94 94
     * Connected socket
95 95
     * @var  resource
96 96
     * @see  connect()
97 97
     */
98
-    protected $socket;
98
+	protected $socket;
99 99
 
100 100
    /**
101 101
     * Challenge used for server digest authentication
102 102
     * @var  array
103 103
     */
104
-    protected $serverChallenge;
104
+	protected $serverChallenge;
105 105
 
106 106
    /**
107 107
     * Challenge used for proxy digest authentication
108 108
     * @var  array
109 109
     */
110
-    protected $proxyChallenge;
110
+	protected $proxyChallenge;
111 111
 
112 112
    /**
113 113
     * Sum of start time and global timeout, exception will be thrown if request continues past this time
114 114
     * @var  integer
115 115
     */
116
-    protected $deadline = null;
116
+	protected $deadline = null;
117 117
 
118 118
    /**
119 119
     * Remaining length of the current chunk, when reading chunked response
120 120
     * @var  integer
121 121
     * @see  readChunked()
122 122
     */
123
-    protected $chunkLength = 0;
123
+	protected $chunkLength = 0;
124 124
 
125 125
    /**
126 126
     * Remaining amount of redirections to follow
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
     *
131 131
     * @var  integer
132 132
     */
133
-    protected $redirectCountdown = null;
133
+	protected $redirectCountdown = null;
134 134
 
135 135
    /**
136 136
     * Sends request to the remote server and returns its response
@@ -139,69 +139,69 @@  discard block
 block discarded – undo
139 139
     * @return   HTTP_Request2_Response
140 140
     * @throws   HTTP_Request2_Exception
141 141
     */
142
-    public function sendRequest(HTTP_Request2 $request)
143
-    {
144
-        $this->request = $request;
145
-
146
-        // Use global request timeout if given, see feature requests #5735, #8964
147
-        if ($timeout = $request->getConfig('timeout')) {
148
-            $this->deadline = time() + $timeout;
149
-        } else {
150
-            $this->deadline = null;
151
-        }
152
-
153
-        try {
154
-            $keepAlive = $this->connect();
155
-            $headers   = $this->prepareHeaders();
156
-            if (false === @fwrite($this->socket, $headers, strlen($headers))) {
157
-                throw new HTTP_Request2_Exception('Error writing request');
158
-            }
159
-            // provide request headers to the observer, see request #7633
160
-            $this->request->setLastEvent('sentHeaders', $headers);
161
-            $this->writeBody();
162
-
163
-            if ($this->deadline && time() > $this->deadline) {
164
-                throw new HTTP_Request2_Exception(
165
-                    'Request timed out after ' .
166
-                    $request->getConfig('timeout') . ' second(s)'
167
-                );
168
-            }
169
-
170
-            $response = $this->readResponse();
171
-
172
-            if (!$this->canKeepAlive($keepAlive, $response)) {
173
-                $this->disconnect();
174
-            }
175
-
176
-            if ($this->shouldUseProxyDigestAuth($response)) {
177
-                return $this->sendRequest($request);
178
-            }
179
-            if ($this->shouldUseServerDigestAuth($response)) {
180
-                return $this->sendRequest($request);
181
-            }
182
-            if ($authInfo = $response->getHeader('authentication-info')) {
183
-                $this->updateChallenge($this->serverChallenge, $authInfo);
184
-            }
185
-            if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {
186
-                $this->updateChallenge($this->proxyChallenge, $proxyInfo);
187
-            }
188
-
189
-        } catch (Exception $e) {
190
-            $this->disconnect();
191
-        }
192
-
193
-        unset($this->request, $this->requestBody);
194
-
195
-        if (!empty($e)) {
196
-            throw $e;
197
-        }
198
-
199
-        if (!$request->getConfig('follow_redirects') || !$response->isRedirect()) {
200
-            return $response;
201
-        } else {
202
-            return $this->handleRedirect($request, $response);
203
-        }
204
-    }
142
+	public function sendRequest(HTTP_Request2 $request)
143
+	{
144
+		$this->request = $request;
145
+
146
+		// Use global request timeout if given, see feature requests #5735, #8964
147
+		if ($timeout = $request->getConfig('timeout')) {
148
+			$this->deadline = time() + $timeout;
149
+		} else {
150
+			$this->deadline = null;
151
+		}
152
+
153
+		try {
154
+			$keepAlive = $this->connect();
155
+			$headers   = $this->prepareHeaders();
156
+			if (false === @fwrite($this->socket, $headers, strlen($headers))) {
157
+				throw new HTTP_Request2_Exception('Error writing request');
158
+			}
159
+			// provide request headers to the observer, see request #7633
160
+			$this->request->setLastEvent('sentHeaders', $headers);
161
+			$this->writeBody();
162
+
163
+			if ($this->deadline && time() > $this->deadline) {
164
+				throw new HTTP_Request2_Exception(
165
+					'Request timed out after ' .
166
+					$request->getConfig('timeout') . ' second(s)'
167
+				);
168
+			}
169
+
170
+			$response = $this->readResponse();
171
+
172
+			if (!$this->canKeepAlive($keepAlive, $response)) {
173
+				$this->disconnect();
174
+			}
175
+
176
+			if ($this->shouldUseProxyDigestAuth($response)) {
177
+				return $this->sendRequest($request);
178
+			}
179
+			if ($this->shouldUseServerDigestAuth($response)) {
180
+				return $this->sendRequest($request);
181
+			}
182
+			if ($authInfo = $response->getHeader('authentication-info')) {
183
+				$this->updateChallenge($this->serverChallenge, $authInfo);
184
+			}
185
+			if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {
186
+				$this->updateChallenge($this->proxyChallenge, $proxyInfo);
187
+			}
188
+
189
+		} catch (Exception $e) {
190
+			$this->disconnect();
191
+		}
192
+
193
+		unset($this->request, $this->requestBody);
194
+
195
+		if (!empty($e)) {
196
+			throw $e;
197
+		}
198
+
199
+		if (!$request->getConfig('follow_redirects') || !$response->isRedirect()) {
200
+			return $response;
201
+		} else {
202
+			return $this->handleRedirect($request, $response);
203
+		}
204
+	}
205 205
 
206 206
    /**
207 207
     * Connects to the remote server
@@ -209,114 +209,114 @@  discard block
 block discarded – undo
209 209
     * @return   bool    whether the connection can be persistent
210 210
     * @throws   HTTP_Request2_Exception
211 211
     */
212
-    protected function connect()
213
-    {
214
-        $secure  = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
215
-        $tunnel  = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
216
-        $headers = $this->request->getHeaders();
217
-        $reqHost = $this->request->getUrl()->getHost();
218
-        if (!($reqPort = $this->request->getUrl()->getPort())) {
219
-            $reqPort = $secure? 443: 80;
220
-        }
221
-
222
-        if ($host = $this->request->getConfig('proxy_host')) {
223
-            if (!($port = $this->request->getConfig('proxy_port'))) {
224
-                throw new HTTP_Request2_Exception('Proxy port not provided');
225
-            }
226
-            $proxy = true;
227
-        } else {
228
-            $host  = $reqHost;
229
-            $port  = $reqPort;
230
-            $proxy = false;
231
-        }
232
-
233
-        if ($tunnel && !$proxy) {
234
-            throw new HTTP_Request2_Exception(
235
-                "Trying to perform CONNECT request without proxy"
236
-            );
237
-        }
238
-        if ($secure && !in_array('ssl', stream_get_transports())) {
239
-            throw new HTTP_Request2_Exception(
240
-                'Need OpenSSL support for https:// requests'
241
-            );
242
-        }
243
-
244
-        // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
245
-        // connection token to a proxy server...
246
-        if ($proxy && !$secure &&
247
-            !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']
248
-        ) {
249
-            $this->request->setHeader('connection');
250
-        }
251
-
252
-        $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&
253
-                      empty($headers['connection'])) ||
254
-                     (!empty($headers['connection']) &&
255
-                      'Keep-Alive' == $headers['connection']);
256
-        $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;
257
-
258
-        $options = array();
259
-        if ($secure || $tunnel) {
260
-            foreach ($this->request->getConfig() as $name => $value) {
261
-                if ('ssl_' == substr($name, 0, 4) && null !== $value) {
262
-                    if ('ssl_verify_host' == $name) {
263
-                        if ($value) {
264
-                            $options['CN_match'] = $reqHost;
265
-                        }
266
-                    } else {
267
-                        $options[substr($name, 4)] = $value;
268
-                    }
269
-                }
270
-            }
271
-            ksort($options);
272
-        }
273
-
274
-        // Changing SSL context options after connection is established does *not*
275
-        // work, we need a new connection if options change
276
-        $remote    = $host . ':' . $port;
277
-        $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .
278
-                     (empty($options)? '': ':' . serialize($options));
279
-        unset($this->socket);
280
-
281
-        // We use persistent connections and have a connected socket?
282
-        // Ensure that the socket is still connected, see bug #16149
283
-        if ($keepAlive && !empty(self::$sockets[$socketKey]) &&
284
-            !feof(self::$sockets[$socketKey])
285
-        ) {
286
-            $this->socket =& self::$sockets[$socketKey];
287
-
288
-        } elseif ($secure && $proxy && !$tunnel) {
289
-            $this->establishTunnel();
290
-            $this->request->setLastEvent(
291
-                'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"
292
-            );
293
-            self::$sockets[$socketKey] =& $this->socket;
294
-
295
-        } else {
296
-            // Set SSL context options if doing HTTPS request or creating a tunnel
297
-            $context = stream_context_create();
298
-            foreach ($options as $name => $value) {
299
-                if (!stream_context_set_option($context, 'ssl', $name, $value)) {
300
-                    throw new HTTP_Request2_Exception(
301
-                        "Error setting SSL context option '{$name}'"
302
-                    );
303
-                }
304
-            }
305
-            $this->socket = @stream_socket_client(
306
-                $remote, $errno, $errstr,
307
-                $this->request->getConfig('connect_timeout'),
308
-                STREAM_CLIENT_CONNECT, $context
309
-            );
310
-            if (!$this->socket) {
311
-                throw new HTTP_Request2_Exception(
312
-                    "Unable to connect to {$remote}. Error #{$errno}: {$errstr}"
313
-                );
314
-            }
315
-            $this->request->setLastEvent('connect', $remote);
316
-            self::$sockets[$socketKey] =& $this->socket;
317
-        }
318
-        return $keepAlive;
319
-    }
212
+	protected function connect()
213
+	{
214
+		$secure  = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
215
+		$tunnel  = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
216
+		$headers = $this->request->getHeaders();
217
+		$reqHost = $this->request->getUrl()->getHost();
218
+		if (!($reqPort = $this->request->getUrl()->getPort())) {
219
+			$reqPort = $secure? 443: 80;
220
+		}
221
+
222
+		if ($host = $this->request->getConfig('proxy_host')) {
223
+			if (!($port = $this->request->getConfig('proxy_port'))) {
224
+				throw new HTTP_Request2_Exception('Proxy port not provided');
225
+			}
226
+			$proxy = true;
227
+		} else {
228
+			$host  = $reqHost;
229
+			$port  = $reqPort;
230
+			$proxy = false;
231
+		}
232
+
233
+		if ($tunnel && !$proxy) {
234
+			throw new HTTP_Request2_Exception(
235
+				"Trying to perform CONNECT request without proxy"
236
+			);
237
+		}
238
+		if ($secure && !in_array('ssl', stream_get_transports())) {
239
+			throw new HTTP_Request2_Exception(
240
+				'Need OpenSSL support for https:// requests'
241
+			);
242
+		}
243
+
244
+		// RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
245
+		// connection token to a proxy server...
246
+		if ($proxy && !$secure &&
247
+			!empty($headers['connection']) && 'Keep-Alive' == $headers['connection']
248
+		) {
249
+			$this->request->setHeader('connection');
250
+		}
251
+
252
+		$keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&
253
+					  empty($headers['connection'])) ||
254
+					 (!empty($headers['connection']) &&
255
+					  'Keep-Alive' == $headers['connection']);
256
+		$host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;
257
+
258
+		$options = array();
259
+		if ($secure || $tunnel) {
260
+			foreach ($this->request->getConfig() as $name => $value) {
261
+				if ('ssl_' == substr($name, 0, 4) && null !== $value) {
262
+					if ('ssl_verify_host' == $name) {
263
+						if ($value) {
264
+							$options['CN_match'] = $reqHost;
265
+						}
266
+					} else {
267
+						$options[substr($name, 4)] = $value;
268
+					}
269
+				}
270
+			}
271
+			ksort($options);
272
+		}
273
+
274
+		// Changing SSL context options after connection is established does *not*
275
+		// work, we need a new connection if options change
276
+		$remote    = $host . ':' . $port;
277
+		$socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .
278
+					 (empty($options)? '': ':' . serialize($options));
279
+		unset($this->socket);
280
+
281
+		// We use persistent connections and have a connected socket?
282
+		// Ensure that the socket is still connected, see bug #16149
283
+		if ($keepAlive && !empty(self::$sockets[$socketKey]) &&
284
+			!feof(self::$sockets[$socketKey])
285
+		) {
286
+			$this->socket =& self::$sockets[$socketKey];
287
+
288
+		} elseif ($secure && $proxy && !$tunnel) {
289
+			$this->establishTunnel();
290
+			$this->request->setLastEvent(
291
+				'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"
292
+			);
293
+			self::$sockets[$socketKey] =& $this->socket;
294
+
295
+		} else {
296
+			// Set SSL context options if doing HTTPS request or creating a tunnel
297
+			$context = stream_context_create();
298
+			foreach ($options as $name => $value) {
299
+				if (!stream_context_set_option($context, 'ssl', $name, $value)) {
300
+					throw new HTTP_Request2_Exception(
301
+						"Error setting SSL context option '{$name}'"
302
+					);
303
+				}
304
+			}
305
+			$this->socket = @stream_socket_client(
306
+				$remote, $errno, $errstr,
307
+				$this->request->getConfig('connect_timeout'),
308
+				STREAM_CLIENT_CONNECT, $context
309
+			);
310
+			if (!$this->socket) {
311
+				throw new HTTP_Request2_Exception(
312
+					"Unable to connect to {$remote}. Error #{$errno}: {$errstr}"
313
+				);
314
+			}
315
+			$this->request->setLastEvent('connect', $remote);
316
+			self::$sockets[$socketKey] =& $this->socket;
317
+		}
318
+		return $keepAlive;
319
+	}
320 320
 
321 321
    /**
322 322
     * Establishes a tunnel to a secure remote server via HTTP CONNECT request
@@ -328,40 +328,40 @@  discard block
 block discarded – undo
328 328
     * @link     http://tools.ietf.org/html/rfc2817#section-5.2
329 329
     * @throws   HTTP_Request2_Exception
330 330
     */
331
-    protected function establishTunnel()
332
-    {
333
-        $donor   = new self;
334
-        $connect = new HTTP_Request2(
335
-            $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
336
-            array_merge($this->request->getConfig(),
337
-                        array('adapter' => $donor))
338
-        );
339
-        $response = $connect->send();
340
-        // Need any successful (2XX) response
341
-        if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
342
-            throw new HTTP_Request2_Exception(
343
-                'Failed to connect via HTTPS proxy. Proxy response: ' .
344
-                $response->getStatus() . ' ' . $response->getReasonPhrase()
345
-            );
346
-        }
347
-        $this->socket = $donor->socket;
348
-
349
-        $modes = array(
350
-            STREAM_CRYPTO_METHOD_TLS_CLIENT,
351
-            STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
352
-            STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
353
-            STREAM_CRYPTO_METHOD_SSLv2_CLIENT
354
-        );
355
-
356
-        foreach ($modes as $mode) {
357
-            if (stream_socket_enable_crypto($this->socket, true, $mode)) {
358
-                return;
359
-            }
360
-        }
361
-        throw new HTTP_Request2_Exception(
362
-            'Failed to enable secure connection when connecting through proxy'
363
-        );
364
-    }
331
+	protected function establishTunnel()
332
+	{
333
+		$donor   = new self;
334
+		$connect = new HTTP_Request2(
335
+			$this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
336
+			array_merge($this->request->getConfig(),
337
+						array('adapter' => $donor))
338
+		);
339
+		$response = $connect->send();
340
+		// Need any successful (2XX) response
341
+		if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
342
+			throw new HTTP_Request2_Exception(
343
+				'Failed to connect via HTTPS proxy. Proxy response: ' .
344
+				$response->getStatus() . ' ' . $response->getReasonPhrase()
345
+			);
346
+		}
347
+		$this->socket = $donor->socket;
348
+
349
+		$modes = array(
350
+			STREAM_CRYPTO_METHOD_TLS_CLIENT,
351
+			STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
352
+			STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
353
+			STREAM_CRYPTO_METHOD_SSLv2_CLIENT
354
+		);
355
+
356
+		foreach ($modes as $mode) {
357
+			if (stream_socket_enable_crypto($this->socket, true, $mode)) {
358
+				return;
359
+			}
360
+		}
361
+		throw new HTTP_Request2_Exception(
362
+			'Failed to enable secure connection when connecting through proxy'
363
+		);
364
+	}
365 365
 
366 366
    /**
367 367
     * Checks whether current connection may be reused or should be closed
@@ -371,34 +371,34 @@  discard block
 block discarded – undo
371 371
     * @param    HTTP_Request2_Response  response object to check
372 372
     * @return   boolean
373 373
     */
374
-    protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
375
-    {
376
-        // Do not close socket on successful CONNECT request
377
-        if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
378
-            200 <= $response->getStatus() && 300 > $response->getStatus()
379
-        ) {
380
-            return true;
381
-        }
382
-
383
-        $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding')) ||
384
-                       null !== $response->getHeader('content-length');
385
-        $persistent  = 'keep-alive' == strtolower($response->getHeader('connection')) ||
386
-                       (null === $response->getHeader('connection') &&
387
-                        '1.1' == $response->getVersion());
388
-        return $requestKeepAlive && $lengthKnown && $persistent;
389
-    }
374
+	protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
375
+	{
376
+		// Do not close socket on successful CONNECT request
377
+		if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
378
+			200 <= $response->getStatus() && 300 > $response->getStatus()
379
+		) {
380
+			return true;
381
+		}
382
+
383
+		$lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding')) ||
384
+					   null !== $response->getHeader('content-length');
385
+		$persistent  = 'keep-alive' == strtolower($response->getHeader('connection')) ||
386
+					   (null === $response->getHeader('connection') &&
387
+						'1.1' == $response->getVersion());
388
+		return $requestKeepAlive && $lengthKnown && $persistent;
389
+	}
390 390
 
391 391
    /**
392 392
     * Disconnects from the remote server
393 393
     */
394
-    protected function disconnect()
395
-    {
396
-        if (is_resource($this->socket)) {
397
-            fclose($this->socket);
398
-            $this->socket = null;
399
-            $this->request->setLastEvent('disconnect');
400
-        }
401
-    }
394
+	protected function disconnect()
395
+	{
396
+		if (is_resource($this->socket)) {
397
+			fclose($this->socket);
398
+			$this->socket = null;
399
+			$this->request->setLastEvent('disconnect');
400
+		}
401
+	}
402 402
 
403 403
    /**
404 404
     * Handles HTTP redirection
@@ -412,49 +412,49 @@  discard block
 block discarded – undo
412 412
     * @return   HTTP_Request2_Response      Response from a new location
413 413
     * @throws   HTTP_Request2_Exception
414 414
     */
415
-    protected function handleRedirect(HTTP_Request2 $request,
416
-                                      HTTP_Request2_Response $response)
417
-    {
418
-        if (is_null($this->redirectCountdown)) {
419
-            $this->redirectCountdown = $request->getConfig('max_redirects');
420
-        }
421
-        if (0 == $this->redirectCountdown) {
422
-            // Copying cURL behaviour
423
-            throw new HTTP_Request2_Exception(
424
-                'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed'
425
-            );
426
-        }
427
-        $redirectUrl = new Net_URL2(
428
-            $response->getHeader('location'),
429
-            array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
430
-        );
431
-        // refuse non-HTTP redirect
432
-        if ($redirectUrl->isAbsolute()
433
-            && !in_array($redirectUrl->getScheme(), array('http', 'https'))
434
-        ) {
435
-            throw new HTTP_Request2_Exception(
436
-                'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString()
437
-            );
438
-        }
439
-        // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
440
-        // but in practice it is often not
441
-        if (!$redirectUrl->isAbsolute()) {
442
-            $redirectUrl = $request->getUrl()->resolve($redirectUrl);
443
-        }
444
-        $redirect = clone $request;
445
-        $redirect->setUrl($redirectUrl);
446
-        if (303 == $response->getStatus() || (!$request->getConfig('strict_redirects')
447
-             && in_array($response->getStatus(), array(301, 302)))
448
-        ) {
449
-            $redirect->setMethod(HTTP_Request2::METHOD_GET);
450
-            $redirect->setBody('');
451
-        }
452
-
453
-        if (0 < $this->redirectCountdown) {
454
-            $this->redirectCountdown--;
455
-        }
456
-        return $this->sendRequest($redirect);
457
-    }
415
+	protected function handleRedirect(HTTP_Request2 $request,
416
+									  HTTP_Request2_Response $response)
417
+	{
418
+		if (is_null($this->redirectCountdown)) {
419
+			$this->redirectCountdown = $request->getConfig('max_redirects');
420
+		}
421
+		if (0 == $this->redirectCountdown) {
422
+			// Copying cURL behaviour
423
+			throw new HTTP_Request2_Exception(
424
+				'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed'
425
+			);
426
+		}
427
+		$redirectUrl = new Net_URL2(
428
+			$response->getHeader('location'),
429
+			array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
430
+		);
431
+		// refuse non-HTTP redirect
432
+		if ($redirectUrl->isAbsolute()
433
+			&& !in_array($redirectUrl->getScheme(), array('http', 'https'))
434
+		) {
435
+			throw new HTTP_Request2_Exception(
436
+				'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString()
437
+			);
438
+		}
439
+		// Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
440
+		// but in practice it is often not
441
+		if (!$redirectUrl->isAbsolute()) {
442
+			$redirectUrl = $request->getUrl()->resolve($redirectUrl);
443
+		}
444
+		$redirect = clone $request;
445
+		$redirect->setUrl($redirectUrl);
446
+		if (303 == $response->getStatus() || (!$request->getConfig('strict_redirects')
447
+			 && in_array($response->getStatus(), array(301, 302)))
448
+		) {
449
+			$redirect->setMethod(HTTP_Request2::METHOD_GET);
450
+			$redirect->setBody('');
451
+		}
452
+
453
+		if (0 < $this->redirectCountdown) {
454
+			$this->redirectCountdown--;
455
+		}
456
+		return $this->sendRequest($redirect);
457
+	}
458 458
 
459 459
    /**
460 460
     * Checks whether another request should be performed with server digest auth
@@ -473,52 +473,52 @@  discard block
 block discarded – undo
473 473
     * @return   boolean whether another request should be performed
474 474
     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters
475 475
     */
476
-    protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
477
-    {
478
-        // no sense repeating a request if we don't have credentials
479
-        if (401 != $response->getStatus() || !$this->request->getAuth()) {
480
-            return false;
481
-        }
482
-        if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
483
-            return false;
484
-        }
485
-
486
-        $url    = $this->request->getUrl();
487
-        $scheme = $url->getScheme();
488
-        $host   = $scheme . '://' . $url->getHost();
489
-        if ($port = $url->getPort()) {
490
-            if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||
491
-                (0 == strcasecmp($scheme, 'https') && 443 != $port)
492
-            ) {
493
-                $host .= ':' . $port;
494
-            }
495
-        }
496
-
497
-        if (!empty($challenge['domain'])) {
498
-            $prefixes = array();
499
-            foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
500
-                // don't bother with different servers
501
-                if ('/' == substr($prefix, 0, 1)) {
502
-                    $prefixes[] = $host . $prefix;
503
-                }
504
-            }
505
-        }
506
-        if (empty($prefixes)) {
507
-            $prefixes = array($host . '/');
508
-        }
509
-
510
-        $ret = true;
511
-        foreach ($prefixes as $prefix) {
512
-            if (!empty(self::$challenges[$prefix]) &&
513
-                (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
514
-            ) {
515
-                // probably credentials are invalid
516
-                $ret = false;
517
-            }
518
-            self::$challenges[$prefix] =& $challenge;
519
-        }
520
-        return $ret;
521
-    }
476
+	protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
477
+	{
478
+		// no sense repeating a request if we don't have credentials
479
+		if (401 != $response->getStatus() || !$this->request->getAuth()) {
480
+			return false;
481
+		}
482
+		if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
483
+			return false;
484
+		}
485
+
486
+		$url    = $this->request->getUrl();
487
+		$scheme = $url->getScheme();
488
+		$host   = $scheme . '://' . $url->getHost();
489
+		if ($port = $url->getPort()) {
490
+			if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||
491
+				(0 == strcasecmp($scheme, 'https') && 443 != $port)
492
+			) {
493
+				$host .= ':' . $port;
494
+			}
495
+		}
496
+
497
+		if (!empty($challenge['domain'])) {
498
+			$prefixes = array();
499
+			foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
500
+				// don't bother with different servers
501
+				if ('/' == substr($prefix, 0, 1)) {
502
+					$prefixes[] = $host . $prefix;
503
+				}
504
+			}
505
+		}
506
+		if (empty($prefixes)) {
507
+			$prefixes = array($host . '/');
508
+		}
509
+
510
+		$ret = true;
511
+		foreach ($prefixes as $prefix) {
512
+			if (!empty(self::$challenges[$prefix]) &&
513
+				(empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
514
+			) {
515
+				// probably credentials are invalid
516
+				$ret = false;
517
+			}
518
+			self::$challenges[$prefix] =& $challenge;
519
+		}
520
+		return $ret;
521
+	}
522 522
 
523 523
    /**
524 524
     * Checks whether another request should be performed with proxy digest auth
@@ -537,28 +537,28 @@  discard block
 block discarded – undo
537 537
     * @return   boolean whether another request should be performed
538 538
     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters
539 539
     */
540
-    protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
541
-    {
542
-        if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
543
-            return false;
544
-        }
545
-        if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
546
-            return false;
547
-        }
548
-
549
-        $key = 'proxy://' . $this->request->getConfig('proxy_host') .
550
-               ':' . $this->request->getConfig('proxy_port');
551
-
552
-        if (!empty(self::$challenges[$key]) &&
553
-            (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
554
-        ) {
555
-            $ret = false;
556
-        } else {
557
-            $ret = true;
558
-        }
559
-        self::$challenges[$key] = $challenge;
560
-        return $ret;
561
-    }
540
+	protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
541
+	{
542
+		if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
543
+			return false;
544
+		}
545
+		if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
546
+			return false;
547
+		}
548
+
549
+		$key = 'proxy://' . $this->request->getConfig('proxy_host') .
550
+			   ':' . $this->request->getConfig('proxy_port');
551
+
552
+		if (!empty(self::$challenges[$key]) &&
553
+			(empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
554
+		) {
555
+			$ret = false;
556
+		} else {
557
+			$ret = true;
558
+		}
559
+		self::$challenges[$key] = $challenge;
560
+		return $ret;
561
+	}
562 562
 
563 563
    /**
564 564
     * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value
@@ -588,48 +588,48 @@  discard block
 block discarded – undo
588 588
     *                   no challenge is present in header value
589 589
     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters
590 590
     */
591
-    protected function parseDigestChallenge($headerValue)
592
-    {
593
-        $authParam   = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
594
-                       self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
595
-        $challenge   = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
596
-        if (!preg_match($challenge, $headerValue, $matches)) {
597
-            return false;
598
-        }
599
-
600
-        preg_match_all('!' . $authParam . '!', $matches[0], $params);
601
-        $paramsAry   = array();
602
-        $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
603
-                             'algorithm', 'qop');
604
-        for ($i = 0; $i < count($params[0]); $i++) {
605
-            // section 3.2.1: Any unrecognized directive MUST be ignored.
606
-            if (in_array($params[1][$i], $knownParams)) {
607
-                if ('"' == substr($params[2][$i], 0, 1)) {
608
-                    $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
609
-                } else {
610
-                    $paramsAry[$params[1][$i]] = $params[2][$i];
611
-                }
612
-            }
613
-        }
614
-        // we only support qop=auth
615
-        if (!empty($paramsAry['qop']) &&
616
-            !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
617
-        ) {
618
-            throw new HTTP_Request2_Exception(
619
-                "Only 'auth' qop is currently supported in digest authentication, " .
620
-                "server requested '{$paramsAry['qop']}'"
621
-            );
622
-        }
623
-        // we only support algorithm=MD5
624
-        if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
625
-            throw new HTTP_Request2_Exception(
626
-                "Only 'MD5' algorithm is currently supported in digest authentication, " .
627
-                "server requested '{$paramsAry['algorithm']}'"
628
-            );
629
-        }
630
-
631
-        return $paramsAry;
632
-    }
591
+	protected function parseDigestChallenge($headerValue)
592
+	{
593
+		$authParam   = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
594
+					   self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
595
+		$challenge   = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
596
+		if (!preg_match($challenge, $headerValue, $matches)) {
597
+			return false;
598
+		}
599
+
600
+		preg_match_all('!' . $authParam . '!', $matches[0], $params);
601
+		$paramsAry   = array();
602
+		$knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
603
+							 'algorithm', 'qop');
604
+		for ($i = 0; $i < count($params[0]); $i++) {
605
+			// section 3.2.1: Any unrecognized directive MUST be ignored.
606
+			if (in_array($params[1][$i], $knownParams)) {
607
+				if ('"' == substr($params[2][$i], 0, 1)) {
608
+					$paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
609
+				} else {
610
+					$paramsAry[$params[1][$i]] = $params[2][$i];
611
+				}
612
+			}
613
+		}
614
+		// we only support qop=auth
615
+		if (!empty($paramsAry['qop']) &&
616
+			!in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
617
+		) {
618
+			throw new HTTP_Request2_Exception(
619
+				"Only 'auth' qop is currently supported in digest authentication, " .
620
+				"server requested '{$paramsAry['qop']}'"
621
+			);
622
+		}
623
+		// we only support algorithm=MD5
624
+		if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
625
+			throw new HTTP_Request2_Exception(
626
+				"Only 'MD5' algorithm is currently supported in digest authentication, " .
627
+				"server requested '{$paramsAry['algorithm']}'"
628
+			);
629
+		}
630
+
631
+		return $paramsAry;
632
+	}
633 633
 
634 634
    /**
635 635
     * Parses [Proxy-]Authentication-Info header value and updates challenge
@@ -638,26 +638,26 @@  discard block
 block discarded – undo
638 638
     * @param    string  value of [Proxy-]Authentication-Info header
639 639
     * @todo     validate server rspauth response
640 640
     */
641
-    protected function updateChallenge(&$challenge, $headerValue)
642
-    {
643
-        $authParam   = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
644
-                       self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
645
-        $paramsAry   = array();
646
-
647
-        preg_match_all($authParam, $headerValue, $params);
648
-        for ($i = 0; $i < count($params[0]); $i++) {
649
-            if ('"' == substr($params[2][$i], 0, 1)) {
650
-                $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
651
-            } else {
652
-                $paramsAry[$params[1][$i]] = $params[2][$i];
653
-            }
654
-        }
655
-        // for now, just update the nonce value
656
-        if (!empty($paramsAry['nextnonce'])) {
657
-            $challenge['nonce'] = $paramsAry['nextnonce'];
658
-            $challenge['nc']    = 1;
659
-        }
660
-    }
641
+	protected function updateChallenge(&$challenge, $headerValue)
642
+	{
643
+		$authParam   = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
644
+					   self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
645
+		$paramsAry   = array();
646
+
647
+		preg_match_all($authParam, $headerValue, $params);
648
+		for ($i = 0; $i < count($params[0]); $i++) {
649
+			if ('"' == substr($params[2][$i], 0, 1)) {
650
+				$paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
651
+			} else {
652
+				$paramsAry[$params[1][$i]] = $params[2][$i];
653
+			}
654
+		}
655
+		// for now, just update the nonce value
656
+		if (!empty($paramsAry['nextnonce'])) {
657
+			$challenge['nonce'] = $paramsAry['nextnonce'];
658
+			$challenge['nc']    = 1;
659
+		}
660
+	}
661 661
 
662 662
    /**
663 663
     * Creates a value for [Proxy-]Authorization header when using digest authentication
@@ -669,40 +669,40 @@  discard block
 block discarded – undo
669 669
     * @return   string  value of [Proxy-]Authorization request header
670 670
     * @link     http://tools.ietf.org/html/rfc2617#section-3.2.2
671 671
     */
672
-    protected function createDigestResponse($user, $password, $url, &$challenge)
673
-    {
674
-        if (false !== ($q = strpos($url, '?')) &&
675
-            $this->request->getConfig('digest_compat_ie')
676
-        ) {
677
-            $url = substr($url, 0, $q);
678
-        }
679
-
680
-        $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
681
-        $a2 = md5($this->request->getMethod() . ':' . $url);
682
-
683
-        if (empty($challenge['qop'])) {
684
-            $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
685
-        } else {
686
-            $challenge['cnonce'] = 'Req2.' . rand();
687
-            if (empty($challenge['nc'])) {
688
-                $challenge['nc'] = 1;
689
-            }
690
-            $nc     = sprintf('%08x', $challenge['nc']++);
691
-            $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
692
-                          $challenge['cnonce'] . ':auth:' . $a2);
693
-        }
694
-        return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
695
-               'realm="' . $challenge['realm'] . '", ' .
696
-               'nonce="' . $challenge['nonce'] . '", ' .
697
-               'uri="' . $url . '", ' .
698
-               'response="' . $digest . '"' .
699
-               (!empty($challenge['opaque'])?
700
-                ', opaque="' . $challenge['opaque'] . '"':
701
-                '') .
702
-               (!empty($challenge['qop'])?
703
-                ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
704
-                '');
705
-    }
672
+	protected function createDigestResponse($user, $password, $url, &$challenge)
673
+	{
674
+		if (false !== ($q = strpos($url, '?')) &&
675
+			$this->request->getConfig('digest_compat_ie')
676
+		) {
677
+			$url = substr($url, 0, $q);
678
+		}
679
+
680
+		$a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
681
+		$a2 = md5($this->request->getMethod() . ':' . $url);
682
+
683
+		if (empty($challenge['qop'])) {
684
+			$digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
685
+		} else {
686
+			$challenge['cnonce'] = 'Req2.' . rand();
687
+			if (empty($challenge['nc'])) {
688
+				$challenge['nc'] = 1;
689
+			}
690
+			$nc     = sprintf('%08x', $challenge['nc']++);
691
+			$digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
692
+						  $challenge['cnonce'] . ':auth:' . $a2);
693
+		}
694
+		return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
695
+			   'realm="' . $challenge['realm'] . '", ' .
696
+			   'nonce="' . $challenge['nonce'] . '", ' .
697
+			   'uri="' . $url . '", ' .
698
+			   'response="' . $digest . '"' .
699
+			   (!empty($challenge['opaque'])?
700
+				', opaque="' . $challenge['opaque'] . '"':
701
+				'') .
702
+			   (!empty($challenge['qop'])?
703
+				', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
704
+				'');
705
+	}
706 706
 
707 707
    /**
708 708
     * Adds 'Authorization' header (if needed) to request headers array
@@ -712,41 +712,41 @@  discard block
 block discarded – undo
712 712
     * @param    string  request URL (needed for digest authentication)
713 713
     * @throws   HTTP_Request2_Exception
714 714
     */
715
-    protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
716
-    {
717
-        if (!($auth = $this->request->getAuth())) {
718
-            return;
719
-        }
720
-        switch ($auth['scheme']) {
721
-            case HTTP_Request2::AUTH_BASIC:
722
-                $headers['authorization'] =
723
-                    'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);
724
-                break;
725
-
726
-            case HTTP_Request2::AUTH_DIGEST:
727
-                unset($this->serverChallenge);
728
-                $fullUrl = ('/' == $requestUrl[0])?
729
-                           $this->request->getUrl()->getScheme() . '://' .
730
-                            $requestHost . $requestUrl:
731
-                           $requestUrl;
732
-                foreach (array_keys(self::$challenges) as $key) {
733
-                    if ($key == substr($fullUrl, 0, strlen($key))) {
734
-                        $headers['authorization'] = $this->createDigestResponse(
735
-                            $auth['user'], $auth['password'],
736
-                            $requestUrl, self::$challenges[$key]
737
-                        );
738
-                        $this->serverChallenge =& self::$challenges[$key];
739
-                        break;
740
-                    }
741
-                }
742
-                break;
743
-
744
-            default:
745
-                throw new HTTP_Request2_Exception(
746
-                    "Unknown HTTP authentication scheme '{$auth['scheme']}'"
747
-                );
748
-        }
749
-    }
715
+	protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
716
+	{
717
+		if (!($auth = $this->request->getAuth())) {
718
+			return;
719
+		}
720
+		switch ($auth['scheme']) {
721
+			case HTTP_Request2::AUTH_BASIC:
722
+				$headers['authorization'] =
723
+					'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);
724
+				break;
725
+
726
+			case HTTP_Request2::AUTH_DIGEST:
727
+				unset($this->serverChallenge);
728
+				$fullUrl = ('/' == $requestUrl[0])?
729
+						   $this->request->getUrl()->getScheme() . '://' .
730
+							$requestHost . $requestUrl:
731
+						   $requestUrl;
732
+				foreach (array_keys(self::$challenges) as $key) {
733
+					if ($key == substr($fullUrl, 0, strlen($key))) {
734
+						$headers['authorization'] = $this->createDigestResponse(
735
+							$auth['user'], $auth['password'],
736
+							$requestUrl, self::$challenges[$key]
737
+						);
738
+						$this->serverChallenge =& self::$challenges[$key];
739
+						break;
740
+					}
741
+				}
742
+				break;
743
+
744
+			default:
745
+				throw new HTTP_Request2_Exception(
746
+					"Unknown HTTP authentication scheme '{$auth['scheme']}'"
747
+				);
748
+		}
749
+	}
750 750
 
751 751
    /**
752 752
     * Adds 'Proxy-Authorization' header (if needed) to request headers array
@@ -755,43 +755,43 @@  discard block
 block discarded – undo
755 755
     * @param    string  request URL (needed for digest authentication)
756 756
     * @throws   HTTP_Request2_Exception
757 757
     */
758
-    protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
759
-    {
760
-        if (!$this->request->getConfig('proxy_host') ||
761
-            !($user = $this->request->getConfig('proxy_user')) ||
762
-            (0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&
763
-             HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
764
-        ) {
765
-            return;
766
-        }
767
-
768
-        $password = $this->request->getConfig('proxy_password');
769
-        switch ($this->request->getConfig('proxy_auth_scheme')) {
770
-            case HTTP_Request2::AUTH_BASIC:
771
-                $headers['proxy-authorization'] =
772
-                    'Basic ' . base64_encode($user . ':' . $password);
773
-                break;
774
-
775
-            case HTTP_Request2::AUTH_DIGEST:
776
-                unset($this->proxyChallenge);
777
-                $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
778
-                            ':' . $this->request->getConfig('proxy_port');
779
-                if (!empty(self::$challenges[$proxyUrl])) {
780
-                    $headers['proxy-authorization'] = $this->createDigestResponse(
781
-                        $user, $password,
782
-                        $requestUrl, self::$challenges[$proxyUrl]
783
-                    );
784
-                    $this->proxyChallenge =& self::$challenges[$proxyUrl];
785
-                }
786
-                break;
787
-
788
-            default:
789
-                throw new HTTP_Request2_Exception(
790
-                    "Unknown HTTP authentication scheme '" .
791
-                    $this->request->getConfig('proxy_auth_scheme') . "'"
792
-                );
793
-        }
794
-    }
758
+	protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
759
+	{
760
+		if (!$this->request->getConfig('proxy_host') ||
761
+			!($user = $this->request->getConfig('proxy_user')) ||
762
+			(0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&
763
+			 HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
764
+		) {
765
+			return;
766
+		}
767
+
768
+		$password = $this->request->getConfig('proxy_password');
769
+		switch ($this->request->getConfig('proxy_auth_scheme')) {
770
+			case HTTP_Request2::AUTH_BASIC:
771
+				$headers['proxy-authorization'] =
772
+					'Basic ' . base64_encode($user . ':' . $password);
773
+				break;
774
+
775
+			case HTTP_Request2::AUTH_DIGEST:
776
+				unset($this->proxyChallenge);
777
+				$proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
778
+							':' . $this->request->getConfig('proxy_port');
779
+				if (!empty(self::$challenges[$proxyUrl])) {
780
+					$headers['proxy-authorization'] = $this->createDigestResponse(
781
+						$user, $password,
782
+						$requestUrl, self::$challenges[$proxyUrl]
783
+					);
784
+					$this->proxyChallenge =& self::$challenges[$proxyUrl];
785
+				}
786
+				break;
787
+
788
+			default:
789
+				throw new HTTP_Request2_Exception(
790
+					"Unknown HTTP authentication scheme '" .
791
+					$this->request->getConfig('proxy_auth_scheme') . "'"
792
+				);
793
+		}
794
+	}
795 795
 
796 796
 
797 797
    /**
@@ -800,88 +800,88 @@  discard block
 block discarded – undo
800 800
     * @return   string
801 801
     * @throws   HTTP_Request2_Exception
802 802
     */
803
-    protected function prepareHeaders()
804
-    {
805
-        $headers = $this->request->getHeaders();
806
-        $url     = $this->request->getUrl();
807
-        $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
808
-        $host    = $url->getHost();
809
-
810
-        $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
811
-        if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
812
-            $host .= ':' . (empty($port)? $defaultPort: $port);
813
-        }
814
-        // Do not overwrite explicitly set 'Host' header, see bug #16146
815
-        if (!isset($headers['host'])) {
816
-            $headers['host'] = $host;
817
-        }
818
-
819
-        if ($connect) {
820
-            $requestUrl = $host;
821
-
822
-        } else {
823
-            if (!$this->request->getConfig('proxy_host') ||
824
-                0 == strcasecmp($url->getScheme(), 'https')
825
-            ) {
826
-                $requestUrl = '';
827
-            } else {
828
-                $requestUrl = $url->getScheme() . '://' . $host;
829
-            }
830
-            $path        = $url->getPath();
831
-            $query       = $url->getQuery();
832
-            $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
833
-        }
834
-
835
-        if ('1.1' == $this->request->getConfig('protocol_version') &&
836
-            extension_loaded('zlib') && !isset($headers['accept-encoding'])
837
-        ) {
838
-            $headers['accept-encoding'] = 'gzip, deflate';
839
-        }
840
-
841
-        $this->addAuthorizationHeader($headers, $host, $requestUrl);
842
-        $this->addProxyAuthorizationHeader($headers, $requestUrl);
843
-        $this->calculateRequestLength($headers);
844
-
845
-        $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
846
-                      $this->request->getConfig('protocol_version') . "\r\n";
847
-        foreach ($headers as $name => $value) {
848
-            $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
849
-            $headersStr   .= $canonicalName . ': ' . $value . "\r\n";
850
-        }
851
-        return $headersStr . "\r\n";
852
-    }
803
+	protected function prepareHeaders()
804
+	{
805
+		$headers = $this->request->getHeaders();
806
+		$url     = $this->request->getUrl();
807
+		$connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
808
+		$host    = $url->getHost();
809
+
810
+		$defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
811
+		if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
812
+			$host .= ':' . (empty($port)? $defaultPort: $port);
813
+		}
814
+		// Do not overwrite explicitly set 'Host' header, see bug #16146
815
+		if (!isset($headers['host'])) {
816
+			$headers['host'] = $host;
817
+		}
818
+
819
+		if ($connect) {
820
+			$requestUrl = $host;
821
+
822
+		} else {
823
+			if (!$this->request->getConfig('proxy_host') ||
824
+				0 == strcasecmp($url->getScheme(), 'https')
825
+			) {
826
+				$requestUrl = '';
827
+			} else {
828
+				$requestUrl = $url->getScheme() . '://' . $host;
829
+			}
830
+			$path        = $url->getPath();
831
+			$query       = $url->getQuery();
832
+			$requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
833
+		}
834
+
835
+		if ('1.1' == $this->request->getConfig('protocol_version') &&
836
+			extension_loaded('zlib') && !isset($headers['accept-encoding'])
837
+		) {
838
+			$headers['accept-encoding'] = 'gzip, deflate';
839
+		}
840
+
841
+		$this->addAuthorizationHeader($headers, $host, $requestUrl);
842
+		$this->addProxyAuthorizationHeader($headers, $requestUrl);
843
+		$this->calculateRequestLength($headers);
844
+
845
+		$headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
846
+					  $this->request->getConfig('protocol_version') . "\r\n";
847
+		foreach ($headers as $name => $value) {
848
+			$canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
849
+			$headersStr   .= $canonicalName . ': ' . $value . "\r\n";
850
+		}
851
+		return $headersStr . "\r\n";
852
+	}
853 853
 
854 854
    /**
855 855
     * Sends the request body
856 856
     *
857 857
     * @throws   HTTP_Request2_Exception
858 858
     */
859
-    protected function writeBody()
860
-    {
861
-        if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
862
-            0 == $this->contentLength
863
-        ) {
864
-            return;
865
-        }
866
-
867
-        $position   = 0;
868
-        $bufferSize = $this->request->getConfig('buffer_size');
869
-        while ($position < $this->contentLength) {
870
-            if (is_string($this->requestBody)) {
871
-                $str = substr($this->requestBody, $position, $bufferSize);
872
-            } elseif (is_resource($this->requestBody)) {
873
-                $str = fread($this->requestBody, $bufferSize);
874
-            } else {
875
-                $str = $this->requestBody->read($bufferSize);
876
-            }
877
-            if (false === @fwrite($this->socket, $str, strlen($str))) {
878
-                throw new HTTP_Request2_Exception('Error writing request');
879
-            }
880
-            // Provide the length of written string to the observer, request #7630
881
-            $this->request->setLastEvent('sentBodyPart', strlen($str));
882
-            $position += strlen($str);
883
-        }
884
-    }
859
+	protected function writeBody()
860
+	{
861
+		if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
862
+			0 == $this->contentLength
863
+		) {
864
+			return;
865
+		}
866
+
867
+		$position   = 0;
868
+		$bufferSize = $this->request->getConfig('buffer_size');
869
+		while ($position < $this->contentLength) {
870
+			if (is_string($this->requestBody)) {
871
+				$str = substr($this->requestBody, $position, $bufferSize);
872
+			} elseif (is_resource($this->requestBody)) {
873
+				$str = fread($this->requestBody, $bufferSize);
874
+			} else {
875
+				$str = $this->requestBody->read($bufferSize);
876
+			}
877
+			if (false === @fwrite($this->socket, $str, strlen($str))) {
878
+				throw new HTTP_Request2_Exception('Error writing request');
879
+			}
880
+			// Provide the length of written string to the observer, request #7630
881
+			$this->request->setLastEvent('sentBodyPart', strlen($str));
882
+			$position += strlen($str);
883
+		}
884
+	}
885 885
 
886 886
    /**
887 887
     * Reads the remote server's response
@@ -889,70 +889,70 @@  discard block
 block discarded – undo
889 889
     * @return   HTTP_Request2_Response
890 890
     * @throws   HTTP_Request2_Exception
891 891
     */
892
-    protected function readResponse()
893
-    {
894
-        $bufferSize = $this->request->getConfig('buffer_size');
895
-
896
-        do {
897
-            $response = new HTTP_Request2_Response($this->readLine($bufferSize), true);
898
-            do {
899
-                $headerLine = $this->readLine($bufferSize);
900
-                $response->parseHeaderLine($headerLine);
901
-            } while ('' != $headerLine);
902
-        } while (in_array($response->getStatus(), array(100, 101)));
903
-
904
-        $this->request->setLastEvent('receivedHeaders', $response);
905
-
906
-        // No body possible in such responses
907
-        if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||
908
-            (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
909
-             200 <= $response->getStatus() && 300 > $response->getStatus()) ||
910
-            in_array($response->getStatus(), array(204, 304))
911
-        ) {
912
-            return $response;
913
-        }
914
-
915
-        $chunked = 'chunked' == $response->getHeader('transfer-encoding');
916
-        $length  = $response->getHeader('content-length');
917
-        $hasBody = false;
918
-        if ($chunked || null === $length || 0 < intval($length)) {
919
-            // RFC 2616, section 4.4:
920
-            // 3. ... If a message is received with both a
921
-            // Transfer-Encoding header field and a Content-Length header field,
922
-            // the latter MUST be ignored.
923
-            $toRead = ($chunked || null === $length)? null: $length;
924
-            $this->chunkLength = 0;
925
-
926
-            while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
927
-                if ($chunked) {
928
-                    $data = $this->readChunked($bufferSize);
929
-                } elseif (is_null($toRead)) {
930
-                    $data = $this->fread($bufferSize);
931
-                } else {
932
-                    $data    = $this->fread(min($toRead, $bufferSize));
933
-                    $toRead -= strlen($data);
934
-                }
935
-                if ('' == $data && (!$this->chunkLength || feof($this->socket))) {
936
-                    break;
937
-                }
938
-
939
-                $hasBody = true;
940
-                if ($this->request->getConfig('store_body')) {
941
-                    $response->appendBody($data);
942
-                }
943
-                if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
944
-                    $this->request->setLastEvent('receivedEncodedBodyPart', $data);
945
-                } else {
946
-                    $this->request->setLastEvent('receivedBodyPart', $data);
947
-                }
948
-            }
949
-        }
950
-
951
-        if ($hasBody) {
952
-            $this->request->setLastEvent('receivedBody', $response);
953
-        }
954
-        return $response;
955
-    }
892
+	protected function readResponse()
893
+	{
894
+		$bufferSize = $this->request->getConfig('buffer_size');
895
+
896
+		do {
897
+			$response = new HTTP_Request2_Response($this->readLine($bufferSize), true);
898
+			do {
899
+				$headerLine = $this->readLine($bufferSize);
900
+				$response->parseHeaderLine($headerLine);
901
+			} while ('' != $headerLine);
902
+		} while (in_array($response->getStatus(), array(100, 101)));
903
+
904
+		$this->request->setLastEvent('receivedHeaders', $response);
905
+
906
+		// No body possible in such responses
907
+		if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||
908
+			(HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
909
+			 200 <= $response->getStatus() && 300 > $response->getStatus()) ||
910
+			in_array($response->getStatus(), array(204, 304))
911
+		) {
912
+			return $response;
913
+		}
914
+
915
+		$chunked = 'chunked' == $response->getHeader('transfer-encoding');
916
+		$length  = $response->getHeader('content-length');
917
+		$hasBody = false;
918
+		if ($chunked || null === $length || 0 < intval($length)) {
919
+			// RFC 2616, section 4.4:
920
+			// 3. ... If a message is received with both a
921
+			// Transfer-Encoding header field and a Content-Length header field,
922
+			// the latter MUST be ignored.
923
+			$toRead = ($chunked || null === $length)? null: $length;
924
+			$this->chunkLength = 0;
925
+
926
+			while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
927
+				if ($chunked) {
928
+					$data = $this->readChunked($bufferSize);
929
+				} elseif (is_null($toRead)) {
930
+					$data = $this->fread($bufferSize);
931
+				} else {
932
+					$data    = $this->fread(min($toRead, $bufferSize));
933
+					$toRead -= strlen($data);
934
+				}
935
+				if ('' == $data && (!$this->chunkLength || feof($this->socket))) {
936
+					break;
937
+				}
938
+
939
+				$hasBody = true;
940
+				if ($this->request->getConfig('store_body')) {
941
+					$response->appendBody($data);
942
+				}
943
+				if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
944
+					$this->request->setLastEvent('receivedEncodedBodyPart', $data);
945
+				} else {
946
+					$this->request->setLastEvent('receivedBodyPart', $data);
947
+				}
948
+			}
949
+		}
950
+
951
+		if ($hasBody) {
952
+			$this->request->setLastEvent('receivedBody', $response);
953
+		}
954
+		return $response;
955
+	}
956 956
 
957 957
    /**
958 958
     * Reads until either the end of the socket or a newline, whichever comes first
@@ -964,27 +964,27 @@  discard block
 block discarded – undo
964 964
     * @return   Available data up to the newline (not including newline)
965 965
     * @throws   HTTP_Request2_Exception     In case of timeout
966 966
     */
967
-    protected function readLine($bufferSize)
968
-    {
969
-        $line = '';
970
-        while (!feof($this->socket)) {
971
-            if ($this->deadline) {
972
-                stream_set_timeout($this->socket, max($this->deadline - time(), 1));
973
-            }
974
-            $line .= @fgets($this->socket, $bufferSize);
975
-            $info  = stream_get_meta_data($this->socket);
976
-            if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
977
-                $reason = $this->deadline
978
-                          ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
979
-                          : 'due to default_socket_timeout php.ini setting';
980
-                throw new HTTP_Request2_Exception("Request timed out {$reason}");
981
-            }
982
-            if (substr($line, -1) == "\n") {
983
-                return rtrim($line, "\r\n");
984
-            }
985
-        }
986
-        return $line;
987
-    }
967
+	protected function readLine($bufferSize)
968
+	{
969
+		$line = '';
970
+		while (!feof($this->socket)) {
971
+			if ($this->deadline) {
972
+				stream_set_timeout($this->socket, max($this->deadline - time(), 1));
973
+			}
974
+			$line .= @fgets($this->socket, $bufferSize);
975
+			$info  = stream_get_meta_data($this->socket);
976
+			if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
977
+				$reason = $this->deadline
978
+						  ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
979
+						  : 'due to default_socket_timeout php.ini setting';
980
+				throw new HTTP_Request2_Exception("Request timed out {$reason}");
981
+			}
982
+			if (substr($line, -1) == "\n") {
983
+				return rtrim($line, "\r\n");
984
+			}
985
+		}
986
+		return $line;
987
+	}
988 988
 
989 989
    /**
990 990
     * Wrapper around fread(), handles global request timeout
@@ -993,21 +993,21 @@  discard block
 block discarded – undo
993 993
     * @return   Data read from socket
994 994
     * @throws   HTTP_Request2_Exception     In case of timeout
995 995
     */
996
-    protected function fread($length)
997
-    {
998
-        if ($this->deadline) {
999
-            stream_set_timeout($this->socket, max($this->deadline - time(), 1));
1000
-        }
1001
-        $data = fread($this->socket, $length);
1002
-        $info = stream_get_meta_data($this->socket);
1003
-        if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
1004
-            $reason = $this->deadline
1005
-                      ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
1006
-                      : 'due to default_socket_timeout php.ini setting';
1007
-            throw new HTTP_Request2_Exception("Request timed out {$reason}");
1008
-        }
1009
-        return $data;
1010
-    }
996
+	protected function fread($length)
997
+	{
998
+		if ($this->deadline) {
999
+			stream_set_timeout($this->socket, max($this->deadline - time(), 1));
1000
+		}
1001
+		$data = fread($this->socket, $length);
1002
+		$info = stream_get_meta_data($this->socket);
1003
+		if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
1004
+			$reason = $this->deadline
1005
+					  ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
1006
+					  : 'due to default_socket_timeout php.ini setting';
1007
+			throw new HTTP_Request2_Exception("Request timed out {$reason}");
1008
+		}
1009
+		return $data;
1010
+	}
1011 1011
 
1012 1012
    /**
1013 1013
     * Reads a part of response body encoded with chunked Transfer-Encoding
@@ -1016,31 +1016,31 @@  discard block
 block discarded – undo
1016 1016
     * @return   string
1017 1017
     * @throws   HTTP_Request2_Exception
1018 1018
     */
1019
-    protected function readChunked($bufferSize)
1020
-    {
1021
-        // at start of the next chunk?
1022
-        if (0 == $this->chunkLength) {
1023
-            $line = $this->readLine($bufferSize);
1024
-            if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
1025
-                throw new HTTP_Request2_Exception(
1026
-                    "Cannot decode chunked response, invalid chunk length '{$line}'"
1027
-                );
1028
-            } else {
1029
-                $this->chunkLength = hexdec($matches[1]);
1030
-                // Chunk with zero length indicates the end
1031
-                if (0 == $this->chunkLength) {
1032
-                    $this->readLine($bufferSize);
1033
-                    return '';
1034
-                }
1035
-            }
1036
-        }
1037
-        $data = $this->fread(min($this->chunkLength, $bufferSize));
1038
-        $this->chunkLength -= strlen($data);
1039
-        if (0 == $this->chunkLength) {
1040
-            $this->readLine($bufferSize); // Trailing CRLF
1041
-        }
1042
-        return $data;
1043
-    }
1019
+	protected function readChunked($bufferSize)
1020
+	{
1021
+		// at start of the next chunk?
1022
+		if (0 == $this->chunkLength) {
1023
+			$line = $this->readLine($bufferSize);
1024
+			if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
1025
+				throw new HTTP_Request2_Exception(
1026
+					"Cannot decode chunked response, invalid chunk length '{$line}'"
1027
+				);
1028
+			} else {
1029
+				$this->chunkLength = hexdec($matches[1]);
1030
+				// Chunk with zero length indicates the end
1031
+				if (0 == $this->chunkLength) {
1032
+					$this->readLine($bufferSize);
1033
+					return '';
1034
+				}
1035
+			}
1036
+		}
1037
+		$data = $this->fread(min($this->chunkLength, $bufferSize));
1038
+		$this->chunkLength -= strlen($data);
1039
+		if (0 == $this->chunkLength) {
1040
+			$this->readLine($bufferSize); // Trailing CRLF
1041
+		}
1042
+		return $data;
1043
+	}
1044 1044
 }
1045 1045
 
1046 1046
 ?>
1047 1047
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +20 added lines, -23 removed lines patch added patch discarded remove patch
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
         $headers = $this->request->getHeaders();
217 217
         $reqHost = $this->request->getUrl()->getHost();
218 218
         if (!($reqPort = $this->request->getUrl()->getPort())) {
219
-            $reqPort = $secure? 443: 80;
219
+            $reqPort = $secure ? 443 : 80;
220 220
         }
221 221
 
222 222
         if ($host = $this->request->getConfig('proxy_host')) {
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
                       empty($headers['connection'])) ||
254 254
                      (!empty($headers['connection']) &&
255 255
                       'Keep-Alive' == $headers['connection']);
256
-        $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;
256
+        $host = ((!$secure || $proxy) ? 'tcp://' : 'ssl://') . $host;
257 257
 
258 258
         $options = array();
259 259
         if ($secure || $tunnel) {
@@ -274,8 +274,8 @@  discard block
 block discarded – undo
274 274
         // Changing SSL context options after connection is established does *not*
275 275
         // work, we need a new connection if options change
276 276
         $remote    = $host . ':' . $port;
277
-        $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .
278
-                     (empty($options)? '': ':' . serialize($options));
277
+        $socketKey = $remote . (($secure && $proxy) ? "->{$reqHost}:{$reqPort}" : '') .
278
+                     (empty($options) ? '' : ':' . serialize($options));
279 279
         unset($this->socket);
280 280
 
281 281
         // We use persistent connections and have a connected socket?
@@ -283,14 +283,14 @@  discard block
 block discarded – undo
283 283
         if ($keepAlive && !empty(self::$sockets[$socketKey]) &&
284 284
             !feof(self::$sockets[$socketKey])
285 285
         ) {
286
-            $this->socket =& self::$sockets[$socketKey];
286
+            $this->socket = & self::$sockets[$socketKey];
287 287
 
288 288
         } elseif ($secure && $proxy && !$tunnel) {
289 289
             $this->establishTunnel();
290 290
             $this->request->setLastEvent(
291 291
                 'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"
292 292
             );
293
-            self::$sockets[$socketKey] =& $this->socket;
293
+            self::$sockets[$socketKey] = & $this->socket;
294 294
 
295 295
         } else {
296 296
             // Set SSL context options if doing HTTPS request or creating a tunnel
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
                 );
314 314
             }
315 315
             $this->request->setLastEvent('connect', $remote);
316
-            self::$sockets[$socketKey] =& $this->socket;
316
+            self::$sockets[$socketKey] = & $this->socket;
317 317
         }
318 318
         return $keepAlive;
319 319
     }
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
                 // probably credentials are invalid
516 516
                 $ret = false;
517 517
             }
518
-            self::$challenges[$prefix] =& $challenge;
518
+            self::$challenges[$prefix] = & $challenge;
519 519
         }
520 520
         return $ret;
521 521
     }
@@ -696,12 +696,10 @@  discard block
 block discarded – undo
696 696
                'nonce="' . $challenge['nonce'] . '", ' .
697 697
                'uri="' . $url . '", ' .
698 698
                'response="' . $digest . '"' .
699
-               (!empty($challenge['opaque'])?
700
-                ', opaque="' . $challenge['opaque'] . '"':
701
-                '') .
702
-               (!empty($challenge['qop'])?
703
-                ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
704
-                '');
699
+               (!empty($challenge['opaque']) ?
700
+                ', opaque="' . $challenge['opaque'] . '"' : '') .
701
+               (!empty($challenge['qop']) ?
702
+                ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"' : '');
705 703
     }
706 704
 
707 705
    /**
@@ -725,17 +723,16 @@  discard block
 block discarded – undo
725 723
 
726 724
             case HTTP_Request2::AUTH_DIGEST:
727 725
                 unset($this->serverChallenge);
728
-                $fullUrl = ('/' == $requestUrl[0])?
726
+                $fullUrl = ('/' == $requestUrl[0]) ?
729 727
                            $this->request->getUrl()->getScheme() . '://' .
730
-                            $requestHost . $requestUrl:
731
-                           $requestUrl;
728
+                            $requestHost . $requestUrl : $requestUrl;
732 729
                 foreach (array_keys(self::$challenges) as $key) {
733 730
                     if ($key == substr($fullUrl, 0, strlen($key))) {
734 731
                         $headers['authorization'] = $this->createDigestResponse(
735 732
                             $auth['user'], $auth['password'],
736 733
                             $requestUrl, self::$challenges[$key]
737 734
                         );
738
-                        $this->serverChallenge =& self::$challenges[$key];
735
+                        $this->serverChallenge = & self::$challenges[$key];
739 736
                         break;
740 737
                     }
741 738
                 }
@@ -781,7 +778,7 @@  discard block
 block discarded – undo
781 778
                         $user, $password,
782 779
                         $requestUrl, self::$challenges[$proxyUrl]
783 780
                     );
784
-                    $this->proxyChallenge =& self::$challenges[$proxyUrl];
781
+                    $this->proxyChallenge = & self::$challenges[$proxyUrl];
785 782
                 }
786 783
                 break;
787 784
 
@@ -807,9 +804,9 @@  discard block
 block discarded – undo
807 804
         $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
808 805
         $host    = $url->getHost();
809 806
 
810
-        $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
807
+        $defaultPort = 0 == strcasecmp($url->getScheme(), 'https') ? 443 : 80;
811 808
         if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
812
-            $host .= ':' . (empty($port)? $defaultPort: $port);
809
+            $host .= ':' . (empty($port) ? $defaultPort : $port);
813 810
         }
814 811
         // Do not overwrite explicitly set 'Host' header, see bug #16146
815 812
         if (!isset($headers['host'])) {
@@ -829,7 +826,7 @@  discard block
 block discarded – undo
829 826
             }
830 827
             $path        = $url->getPath();
831 828
             $query       = $url->getQuery();
832
-            $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
829
+            $requestUrl .= (empty($path) ? '/' : $path) . (empty($query) ? '' : '?' . $query);
833 830
         }
834 831
 
835 832
         if ('1.1' == $this->request->getConfig('protocol_version') &&
@@ -920,7 +917,7 @@  discard block
 block discarded – undo
920 917
             // 3. ... If a message is received with both a
921 918
             // Transfer-Encoding header field and a Content-Length header field,
922 919
             // the latter MUST be ignored.
923
-            $toRead = ($chunked || null === $length)? null: $length;
920
+            $toRead = ($chunked || null === $length) ? null : $length;
924 921
             $this->chunkLength = 0;
925 922
 
926 923
             while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
Please login to merge, or discard this patch.