<?php
 namespace Facebook\HttpClients; use Facebook\FacebookSDKException; class FacebookStreamHttpClient implements FacebookHttpable { protected $requestHeaders = array(); protected $responseHeaders = array(); protected $responseHttpStatusCode = 0; protected static $facebookStream; public function __construct(?FacebookStream $facebookStream = null) { self::$facebookStream = $facebookStream ?: new FacebookStream(); } public function addRequestHeader($key, $value) { $this->requestHeaders[$key] = $value; } public function getResponseHeaders() { return $this->responseHeaders; } public function getResponseHttpStatusCode() { return $this->responseHttpStatusCode; } public function send($url, $method = 'GET', $parameters = array()) { $options = array( 'http' => array( 'method' => $method, 'timeout' => 60, 'ignore_errors' => true ), 'ssl' => array( 'verify_peer' => true, 'cafile' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fb_ca_chain_bundle.crt', ), ); if ($parameters) { $options['http']['content'] = http_build_query($parameters, null, '&'); $this->addRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } $options['http']['header'] = $this->compileHeader(); self::$facebookStream->streamContextCreate($options); $rawResponse = self::$facebookStream->fileGetContents($url); $rawHeaders = self::$facebookStream->getResponseHeaders(); if ($rawResponse === false || !$rawHeaders) { throw new FacebookSDKException('Stream returned an empty response', 660); } $this->responseHeaders = self::formatHeadersToArray($rawHeaders); $this->responseHttpStatusCode = self::getStatusCodeFromHeader($this->responseHeaders['http_code']); return $rawResponse; } public function compileHeader() { $header = []; foreach($this->requestHeaders as $k => $v) { $header[] = $k . ': ' . $v; } return implode("\r\n", $header); } public static function formatHeadersToArray(array $rawHeaders) { $headers = array(); foreach ($rawHeaders as $line) { if (strpos($line, ':') === false) { $headers['http_code'] = $line; } else { list ($key, $value) = explode(': ', $line); $headers[$key] = $value; } } return $headers; } public static function getStatusCodeFromHeader($header) { preg_match('|HTTP/\d\.\d\s+(\d+)\s+.*|', $header, $match); return (int) $match[1]; } } 