magestudy /lib/Mage/HTTP/Client/Socket.php

Language PHP Lines 537
MD5 Hash 7a889fed729d92eba849d6fdfa32d7d6 Estimated Cost $6,461 (why?)
Repository https://bitbucket.org/andrewjleavitt/magestudy View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Connect
 * @copyright   Copyright (c) 2009 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Class to work with HTTP protocol using sockets
 *
 * @category    Mage
 * @package     Mage_Connect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_HTTP_Client_Socket
    implements Mage_HTTP_IClient
{
	/**
	 * Hostname
	 * @var string
	 */
	private $_host = 'localhost';

	/**
	 * Port
	 * @var int
	 */
	private $_port = 80;

	/**
	 * Stream resource 
	 * @var object
	 */
	private $_sock = null;
	
	/**
	 * Request headers
	 * @var array
	 */
	private $_headers = array();
	
	
	/**
	 * Fields for POST method - hash
	 * @var array
	 */
	private $_postFields = array();
	
	/**
	 * Request cookies 
	 * @var array
	 */
	private $_cookies = array();
	
	/**
	 * Response headers
	 * @var array
	 */
	private $_responseHeaders = array();
	
	/**
	 * Response body
	 * @var string
	 */
	private $_responseBody = '';
	
	/**
	 * Response status
	 * @var int
	 */
	private $_responseStatus = 0;
	
	
	/**
	 * Request timeout
	 * @var int
	 */
	private $_timeout = 300;
	
	/**
	 * TODO
	 * @var int
	 */
	private $_redirectCount = 0;


	/**
	 * Set request timeout, msec
	 * 
	 * @param int $value 
	 */
	public function setTimeout($value)
	{
		$this->_timeout = (int) $value;
	}

	/**
	 * Constructor 
	 * @param string $host 
	 * @param int $port
	 */
	public function __construct($host = null, $port = 80)
	{
		if($host) {
			$this->connect($host, (int) $port);
		}
	}

	/**
	 * Set connection params
	 *
     * @param string $host 
     * @param int $port
	 */
	public function connect($host, $port = 80)
	{
		$this->_host = $host;
		$this->_port = (int) $port;

	}
	
	/**
	 * Disconnect
	 */
	public function disconnect()
	{
		@fclose($this->_sock);
	}

	/**
	 * Set headers from hash
	 
	 * @param array $headers
	 */	
	public function setHeaders($headers)
	{
		$this->_headers = $headers;

	}
	
	/**
	 * Add header
	 * 
	 * @param $name name, ex. "Location"
	 * @param $value value ex. "http://google.com"
	 */
	public function addHeader($name, $value)
	{
		$this->_headers[$name] = $value;

	}
	
	/**
	 * Remove specified header
	 * 
	 * @param string $name
	 */
	public function removeHeader($name)
	{
		unset($this->_headers[$name]);

	}

	/**
	 * Authorization: Basic header
	 * Login credentials support
	 * 
	 * @param string $login username
	 * @param string $pass password
	 */
	public function setCredentials($login, $pass)
	{
		$val= base64_encode( "$login:$pass" );
		$this->addHeader( "Authorization", "Basic $val" );
	}

	/**
	 * Add cookie
	 * 
	 * @param string $name
	 * @param string $value 	 
	 */
	public function addCookie($name, $value)
	{
		$this->_cookies[$name] = $value;
	}

	/**
	 * Remove cookie 
	 * 
	 * @param string $name
	 */	
	public function removeCookie($name)
	{
		unset($this->_cookies[$name]);
	}

	/**
	 * Set cookies array
	 * 	 
	 * @param array $cookies
	 */
	public function setCookies($cookies)
	{
		$this->_cookies = $cookies;
	}

	/**
	 * Clear cookies
	 */
	public function removeCookies()
	{
		$this->setCookies(array());
	}

	
	/**
	 * Make GET request
	 * 
	 * @param string $uri full uri path
	 */
	public function get($uri)
	{	
        $this->makeRequest("GET",$this->parseUrl($uri));		
	}

	/**
	 * Set host, port from full url
	 * and return relative url 
	 * 
	 * @param string $uri ex. http://google.com/index.php?a=b
	 * @return string ex. /index.php?a=b
	 */
	protected function parseUrl($uri) 
	{
		$parts = parse_url($uri);
		if(!empty($parts['user']) && !empty($parts['pass'])) {
			$this->setCredentials($parts['user'], $parts['pass']);
		}
		if(!empty($parts['port'])) {
			$this->_port = (int) $parts['port'];
		}
		
		if(!empty($parts['host'])) {
			$this->_host = $parts['host'];
		} else {
			throw new InvalidArgumentException("Uri doesn't contain host part"); 
		}
		
		
		if(!empty($parts['path'])) {
			$requestUri = $parts['path'];
		} else {
			throw new InvalidArgumentException("Uri doesn't contain path part");
		}
		if(!empty($parts['query'])) {
			$requestUri .= "?".$parts['query'];
		}
		return $requestUri;
	}
	
	/**
	 * Make POST request
	 */
	public function post($uri, $params)
	{
		$this->makeRequest("POST", $this->parseUrl($uri), $params);
	}


	/**
	 * Get response headers
	 * 
	 * @return array	 
	 */
	public function getHeaders()
	{
		return $this->_responseHeaders;
	}
	

	/**
	 * Get response body
	 * 
	 * @return string	
	 */
	public function getBody()
	{
		return $this->_responseBody;
	}

	/**
	 * Get cookies response hash 
	 *
	 * @return array	 
	 */
	public function getCookies()
	{
		if(empty($this->_responseHeaders['Set-Cookie'])) {
			return array();
		}
		$out = array();
		foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
			$values = explode("; ", $row);
			$c = count($values);
			if(!$c) {
				continue;
			}
			list($key, $val) = explode("=", $values[0]);
			if(is_null($val)) {
				continue;
			}
			$out[trim($key)] = trim($val);
		}
		return $out;
	}


	/**
	 * Get cookies array with details
	 * (domain, expire time etc)
	 * @return array
	 */
	public function getCookiesFull()
	{
		if(empty($this->_responseHeaders['Set-Cookie'])) {
			return array();
		}
		$out = array();
		foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
			$values = explode("; ", $row);
			$c = count($values);
			if(!$c) {
				continue;
			}
			list($key, $val) = explode("=", $values[0]);
			if(is_null($val)) {
				continue;
			}
			$out[trim($key)] = array('value'=>trim($val));
			array_shift($values);
			$c--;
			if(!$c) {
				continue;
			}
			for($i = 0; $i<$c; $i++) {
				list($subkey, $val) = explode("=", $values[$i]);
				$out[trim($key)][trim($subkey)] = trim($val);
			}
		}
		return $out;
	}

	/**
	 * Process response headers
	 */
	protected function processResponseHeaders()
	{
		$crlf = "\r\n";
		$this->_responseHeaders = array();
		while (!feof($this->_sock)) {
			$line = fgets($this->_sock, 1024);
			if($line === $crlf) {
				return;
			}
			$name = $value = '';
			$out = explode(": ", trim($line), 2);
			if(count($out) == 2) {
				$name = $out[0];
				$value = $out[1];
			}		
    		if(!empty($value)) {
				if($name == "Set-Cookie") {
				    if(!isset($this->_responseHeaders[$name])) {
                        $this->_responseHeaders[$name] = array();
                    }
					$this->_responseHeaders[$name][] = $value;
				} else {
					$this->_responseHeaders[$name] = $value;
				}
			}
		}
	}

	/**
	 * Process response body
	 */
	protected function processResponseBody()
	{
		$this->_responseBody = '';

		while (!feof($this->_sock)) {
			$this->_responseBody .= @fread($this->_sock, 1024);
		}
	}

	/**
	 * Process response	  
	 */
	protected function processResponse()
	{
		$response = '';
		$responseLine = trim(fgets($this->_sock, 1024));

		$line = explode(" ", $responseLine, 3);
		if(count($line) != 3) {
			return $this->doError("Invalid response line returned from server: ".$responseLine);
		}
		$this->_responseStatus = intval($line[1]);
		$this->processResponseHeaders();

		$this->processRedirect();

		$this->processResponseBody();
	}


	/**
	 * Process redirect
	 */
	protected function processRedirect()
	{
		// TODO: implement redircets support
	}

	
	/**
	 * Get response status code
	 * @see lib/Mage/HTTP/Mage_HTTP_Client#getStatus()
	 */
	public function getStatus()
	{
		return $this->_responseStatus;
	}

	/**
	 * Make request
	 * @param string $method 
	 * @param string $uri
	 * @param array $params
	 * @return null
	 */
	protected function makeRequest($method, $uri, $params = array())
	{
		$errno = $errstr = '';
		$this->_sock = @fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout);
		if(!$this->_sock) {
			return $this->doError(sprintf("[errno: %d] %s", $errno, $errstr));
		}

		$crlf = "\r\n";
		$isPost = $method == "POST";

		$appendHeaders = array();
		$paramsStr = false;
		if($isPost && count($params)) {
			$paramsStr = http_build_query($params);
			$appendHeaders['Content-type'] = 'application/x-www-form-urlencoded';
			$appendHeaders['Content-length'] = strlen($paramsStr);
		}

		$out = "{$method} {$uri} HTTP/1.1{$crlf}";
		$out .= $this->headersToString($appendHeaders);
		$out .= $crlf;
		if($paramsStr) {
			$out .= $paramsStr.$crlf;
		}
		
		fwrite($this->_sock, $out);
		$this->processResponse();
	}
	
	/**
	 * Throw error excpetion
	 * @param $string
	 * @throws Exception
	 */
	public function doError($string)
	{
		throw new Exception($string);
	}

	/**
	 * Convert headers hash to string 
	 * @param $delimiter
	 * @param $append
	 * @return string
	 */
	protected function headersToString($append = array())
	{
		$headers = array();
		$headers["Host"] = $this->_host;
		$headers['Connection'] = "close";
		$headers = array_merge($headers, $this->_headers, $append);
		$str = array();
		foreach ($headers as $k=>$v) {
			$str []= "$k: $v\r\n";
		}
		return implode($str);
	}

	/**
	 * TODO
	 */
	public function setOptions($arr)
	{
		// Stub
	}
	
	/**
	 * TODO
	 */
	public function setOption($name, $value)
	{
		// Stub
	}

}
Back to Top