/** * {@inheritDoc} */ public function __construct() { $defaults = stream_context_get_options(stream_context_get_default()); $this->adapter = $defaults[Filesystem::PROTOCOL]['adapter']; $this->logger = $defaults[Filesystem::PROTOCOL]['logger']; $this->logger->debug(__METHOD__); }
function embedImageURL($url) { $url .= "/details/xs"; // PHP5 befigyel!!! $doc = new DOMDocument(); $opts = array('http' => array('max_redirects' => 100)); $resource = stream_context_get_default($opts); $context = stream_context_create($opts); libxml_set_streams_context($context); // Pattogna kulonben a cookie miatt, kenytelenek vagyunk curl-t hasznalni $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile"); curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile"); # SAME cookiefile if (@$doc->loadHTML(curl_exec($curl))) { if ($retnode = $doc->getElementById("textfield-url")) { echo "megy"; return "<img src=\"{$retnode->nodeValue}\">"; } else { return false; } } else { return false; } }
public static function applyInitPathHook($url, $context = 'core') { $params = []; $parts = AJXP_Utils::safeParseUrl($url); if (!($params = self::getLocalParams(self::CACHE_KEY . $url))) { // Nothing in cache $repositoryId = $parts["host"]; $repository = ConfService::getRepositoryById($parts["host"]); if ($repository == null) { throw new \Exception("Cannot find repository"); } $configHost = $repository->getOption('HOST'); $configPath = $repository->getOption('PATH'); $params['path'] = $parts['path']; $params['basepath'] = $configPath; $params['itemname'] = basename($params['path']); // Special case for root dir if (empty($params['path']) || $params['path'] == '/') { $params['path'] = '/'; } $params['path'] = dirname($params['path']); $params['fullpath'] = rtrim($params['path'], '/') . '/' . $params['itemname']; $params['base_url'] = $configHost; $params['keybase'] = $repositoryId . $params['fullpath']; $params['key'] = md5($params['keybase']); self::addLocalParams(self::CACHE_KEY . $url, $params); } $repoData = self::actualRepositoryWrapperData($parts["host"]); $repoProtocol = $repoData['protocol']; $default = stream_context_get_options(stream_context_get_default()); $default[$repoProtocol]['path'] = $params; $default[$repoProtocol]['client']->setDefaultUrl($configHost); stream_context_set_default($default); }
function choose_torrent_link($links) { $link_best = ""; $word_matches = 0; if (count($links) == 0) { return ""; } //Check how many links has ".torrent" in them foreach ($links as $link) { if (preg_match("/\\.torrent/", $link)) { $link_best = $link; $word_matches++; } } //If only one had ".torrent", use that, else check http content-type for each, //and use the first that returns the proper torrent type if ($word_matches != 1) { foreach ($links as $link) { $opts = array('http' => array('timeout' => 10)); stream_context_get_default($opts); $headers = get_headers($link, 1); if (isset($headers['Content-Disposition']) && preg_match('/filename=.+\\.torrent/i', $headers['Content-Disposition']) || isset($headers['Content-Type']) && $headers['Content-Type'] == 'application/x-bittorrent') { $link_best = $link; break; } } } //If still no match has been made, just select the first, and hope the html torrent parser can find it if (empty($link_best)) { $link_best = $links[0]; } return $link_best; }
function main() { global $ACCESS_TOKEN, $USER_AGENT; // Set the API sport, method, id, format, and any parameters $host = 'erikberg.com'; $sport = ''; $method = 'events'; $id = ''; $format = 'json'; $parameters = array('sport' => 'nba', 'date' => '20130414'); // Pass method, format, and parameters to build request url $url = buildURL($host, $sport, $method, $id, $format, $parameters); // Set the User Agent, Authorization header and allow gzip $default_opts = array('http' => array('user_agent' => $USER_AGENT, 'header' => array('Accept-Encoding: gzip', 'Authorization: Bearer ' . $ACCESS_TOKEN))); stream_context_get_default($default_opts); $file = 'compress.zlib://' . $url; $fh = fopen($file, 'rb'); if ($fh && strpos($http_response_header[0], "200 OK") !== false) { $content = stream_get_contents($fh); fclose($fh); printResult($content); } else { // handle error, check $http_response_header for HTTP status code, etc. if ($fh) { $xmlstats_error = json_decode(stream_get_contents($fh)); printf("Server returned %s error along with this message:\n%s\n", $xmlstats_error->error->code, $xmlstats_error->error->description); } else { print "A problem was encountered trying to connect to the server!\n"; print_r(error_get_last()); } } }
/** * Register the stream wrapper for s3 */ public function register_stream_wrapper() { if (defined('S3_UPLOADS_USE_LOCAL') && S3_UPLOADS_USE_LOCAL) { stream_wrapper_register('s3', 'S3_Uploads_Local_Stream_Wrapper', STREAM_IS_URL); } else { S3_Uploads_Stream_Wrapper::register($this->s3()); stream_context_set_option(stream_context_get_default(), 's3', 'ACL', 'public-read'); } stream_context_set_option(stream_context_get_default(), 's3', 'seekable', true); }
/** * Execute an HTTP Request * * @param Google_0814_HttpRequest $request the http request to be executed * @return Google_0814_HttpRequest http request with the response http code, * response headers and response body filled in * @throws Google_0814_IO_Exception on curl or IO error */ public function executeRequest(Google_0814_Http_Request $request) { $default_options = stream_context_get_options(stream_context_get_default()); $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : array(); if ($request->getPostBody()) { $requestHttpContext["content"] = $request->getPostBody(); } $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $headers = ""; foreach ($requestHeaders as $k => $v) { $headers .= "{$k}: {$v}\r\n"; } $requestHttpContext["header"] = $headers; } $requestHttpContext["method"] = $request->getRequestMethod(); $requestHttpContext["user_agent"] = $request->getUserAgent(); $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : array(); if (!array_key_exists("cafile", $requestSslContext)) { $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem'; } $options = array("http" => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext), "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext)); $context = stream_context_create($options); $url = $request->getUrl(); if ($request->canGzip()) { $url = self::ZLIB . $url; } // We are trapping any thrown errors in this method only and // throwing an exception. $this->trappedErrorNumber = null; $this->trappedErrorString = null; // START - error trap. set_error_handler(array($this, 'trapError')); $fh = fopen($url, 'r', false, $context); restore_error_handler(); // END - error trap. if ($this->trappedErrorNumber) { throw new Google_0814_IO_Exception(sprintf("HTTP Error: Unable to connect: '%s'", $this->trappedErrorString), $this->trappedErrorNumber); } $response_data = false; $respHttpCode = self::UNKNOWN_CODE; if ($fh) { if (isset($this->options[self::TIMEOUT])) { stream_set_timeout($fh, $this->options[self::TIMEOUT]); } $response_data = stream_get_contents($fh); fclose($fh); $respHttpCode = $this->getHttpResponseCode($http_response_header); } if (false === $response_data) { throw new Google_0814_IO_Exception(sprintf("HTTP Error: Unable to connect: '%s'", $respHttpCode), $respHttpCode); } $responseHeaders = $this->getHttpResponseHeaders($http_response_header); return array($response_data, $responseHeaders, $respHttpCode); }
/** * Execute a apiHttpRequest. * * @param Google_HttpRequest $request the http request to be executed * * @throws Google_IOException on curl or IO error * * @return Google_HttpRequest http request with the response http code, * response headers and response body filled in */ public function makeRequest(Google_Http_Request $request) { // First, check to see if we have a valid cached version. $cached = $this->getCachedRequest($request); if ($cached !== false) { if (!$this->checkMustRevalidateCachedRequest($cached, $request)) { return $cached; } } $default_options = stream_context_get_options(stream_context_get_default()); $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : []; if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) { $request = $this->processEntityRequest($request); } if ($request->getPostBody()) { $requestHttpContext['content'] = $request->getPostBody(); } $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $headers = ''; foreach ($requestHeaders as $k => $v) { $headers .= "{$k}: {$v}\n"; } $requestHttpContext['header'] = $headers; } $requestHttpContext['method'] = $request->getRequestMethod(); $requestHttpContext['user_agent'] = $request->getUserAgent(); $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : []; if (!array_key_exists('cafile', $requestSslContext)) { $requestSslContext['cafile'] = dirname(__FILE__) . '/cacerts.pem'; } $options = ['http' => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext), 'ssl' => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext)]; $context = stream_context_create($options); $response_data = file_get_contents($request->getUrl(), false, $context); if (false === $response_data) { throw new Google_IOException('HTTP Error: Unable to connect'); } $respHttpCode = $this->getHttpResponseCode($http_response_header); $responseHeaders = $this->getHttpResponseHeaders($http_response_header); if ($respHttpCode == 304 && $cached) { // If the server responded NOT_MODIFIED, return the cached request. $this->updateCachedRequest($cached, $responseHeaders); return $cached; } if (!isset($responseHeaders['Date']) && !isset($responseHeaders['date'])) { $responseHeaders['Date'] = date('r'); } $request->setResponseHttpCode($respHttpCode); $request->setResponseHeaders($responseHeaders); $request->setResponseBody($response_data); // Store the request in cache (the function checks to see if the request // can actually be cached) $this->setCachedRequest($request); return $request; }
public function access($code, $options = array()) { $type = isset($options['grant_type']) ? $options['grant_type'] : 'authorization_code'; $params = array('client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'redirect_uri' => isset($options['redirect_uri']) ? $options['redirect_uri'] : $this->redirect_uri); switch ($type) { case 'authorization_code': $params['code'] = $code; $params['grant_type'] = $type; break; case 'refresh_token': $params['refresh_token'] = $code; $params['response_type'] = 'refresh_token'; $params['UserID'] = $options['uid']; break; } $response = null; $url = $this->url_access_token(); switch ($this->method) { case 'GET': // Need to switch to Request library, but need to test it on one that works $url .= '?' . http_build_query($params); $response = file_get_contents($url); $return = json_decode($response, true); break; case 'POST': $postdata = http_build_query($params); $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata)); $_default_opts = stream_context_get_params(stream_context_get_default()); $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts)); $response = file_get_contents($url, false, $context); $return = json_decode($response, true); break; default: throw new Exception('Method \'' . $this->method . '\' must be either GET or POST'); } if (isset($return['Error'])) { throw new Exception($return['Error'], $return['ErrorCode']); } // Converts keys to the equivalent $return['access_token'] = $return['AccessToken']; $return['expires'] = $return['Expires']; $return['refresh_token'] = $return['RefreshToken']; $return['uid'] = $return['UserID']; // Unsets no longer used indexes unset($return['AccessToken'], $return['Expires'], $return['RefreshToken'], $return['UserID']); switch ($type) { case 'authorization_code': return Token::factory('access', $return); break; case 'refresh_token': return Token::factory('refresh', $return); break; } }
public function get_user_info(Access $token) { $opts = array('http' => array('method' => 'GET', 'header' => 'Authorization: OAuth ' . $token->access_token)); $_default_opts = stream_context_get_params(stream_context_get_default()); $opts = array_merge_recursive($_default_opts['options'], $opts); $context = stream_context_create($opts); $url = 'http://api-yaru.yandex.ru/me/?format=json'; $user = json_decode(file_get_contents($url, false, $context)); preg_match("/\\d+\$/", $user->id, $uid); return array('uid' => $uid[0], 'nickname' => isset($user->name) ? $user->name : null, 'name' => isset($user->name) ? $user->name : null, 'first_name' => isset($user->first_name) ? $user->first_name : null, 'last_name' => isset($user->last_name) ? $user->last_name : null, 'email' => isset($user->email) ? $user->email : null, 'location' => isset($user->hometown->name) ? $user->hometown->name : null, 'description' => isset($user->bio) ? $user->bio : null, 'image' => $user->links->userpic); }
/** * Register the stream wrapper for s3 */ public function register_stream_wrapper() { if (defined('S3_UPLOADS_USE_LOCAL') && S3_UPLOADS_USE_LOCAL) { require_once dirname(__FILE__) . '/class-s3-uploads-local-stream-wrapper.php'; stream_wrapper_register('s3', 'S3_Uploads_Local_Stream_Wrapper', STREAM_IS_URL); } else { $s3 = $this->s3(); S3_Uploads_Stream_Wrapper::register($s3); stream_context_set_option(stream_context_get_default(), 's3', 'ACL', 'public-read'); } stream_context_set_option(stream_context_get_default(), 's3', 'seekable', true); }
/** * @param string $prefix */ public function __construct(S3Client $client) { $protocol = 'dspace'; $this->client = $client; $default = stream_context_get_options(stream_context_get_default()); $default[$protocol]['client'] = $client; if (!isset($default[$protocol]['cache'])) { // Set a default cache adapter. $default[$protocol]['cache'] = new LruArrayCache(); } stream_context_set_default($default); }
public function testDefaultContextOptionsAreRemoved() { return; $this->markTestSkipped('Skipped until I find a way to remove eys from default context options'); stream_context_set_default(array('someContext' => array('a' => 'b'))); $fs = new FileSystem(); $scheme = $fs->scheme(); unset($fs); //provoking __destruct $options = stream_context_get_options(stream_context_get_default()); $this->assertArrayNotHasKey($scheme, $options, 'FS Context option present'); $this->assertArrayHasKey('someContext', $options, 'Previously existing context option present'); }
/** Load the page, parse for iconic links, and add them to icon list if they are valid. */ protected function links_from_site() { /* Quietly fetch the site contents into a DOM */ $dom = new DOMDocument(); $dom->recover = true; $dom->strictErrorChecking = false; $default_context = stream_context_get_default(); $stream_context = stream_context_create($this->stream_context_options); libxml_set_streams_context($stream_context); $libxml_err_state = libxml_use_internal_errors(true); $dom_result = @$dom->loadHTMLFile($this->site_url); libxml_clear_errors(); libxml_use_internal_errors($libxml_err_state); libxml_set_streams_context($default_context); if ($dom_result === false) { $status = self::header_findr($http_response_header, null); @(list(, $status, ) = explode(' ', $status, 3)); $status = (int) $status; trigger_error('site \'' . $this->site_url . '\' returned ' . $status, E_USER_NOTICE); return false; } /* If we followed any redirects, rewrite the site_url with the current location, so that relative urls may be correctly converted into their absolute form. */ $location = self::header_findr($http_response_header, 'Location'); if ($location !== null) { $this->site_url = $location; } /* check all the links which relate to icons */ foreach ($dom->getElementsByTagName('link') as $link) { $relations = explode(' ', $link->getAttribute('rel')); if (in_array('icon', array_map('strtolower', $relations))) { $href = $link->getAttribute('href'); $href_absolute = $this->absolutize_url($href); $icon = $this->validate_icon($href_absolute); if ($icon !== null) { if (empty($icon['type'])) { $icon['type'] = $link->getAttribute('type'); } if (empty($icon['sizes'])) { $icon['sizes'] = $link->getAttribute('sizes'); } $this->favicons[] = $icon; } } } }
public function get_user_info(OAuth2_Token_Access $token) { $url = 'https://api.renren.com/restserver.do'; $params = array('access_token' => $token->access_token, 'format' => 'JSON', 'v' => '1.0', 'call_id' => time(), 'method' => 'users.getInfo'); $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($params))); $_default_opts = stream_context_get_params(stream_context_get_default()); $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts)); $user = json_decode(file_get_contents($url, false, $context)); if (!is_array($user) or !isset($user[0]) or !($user = $user[0]) or array_key_exists("error_code", $user)) { throw new OAuth2_Exception((array) $user); } // Create a response from the request return array('via' => 'renren', 'uid' => $user->uid, 'screen_name' => $user->name, 'name' => '', 'location' => '', 'description' => '', 'image' => $user->tinyurl, 'access_token' => $token->access_token, 'expire_at' => $token->expires, 'refresh_token' => $token->refresh_token); }
/** * Registers the dspace scheme */ protected function register() { if (in_array(self::PROTOCOL, stream_get_wrappers())) { stream_wrapper_unregister(self::PROTOCOL); } stream_wrapper_register(self::PROTOCOL, '\\Dspacelabs\\Component\\Filesystem\\StreamWrapper', STREAM_IS_URL); $default = stream_context_get_options(stream_context_get_default()); $default[self::PROTOCOL]['adapter'] = $this->adapter; $default[self::PROTOCOL]['logger'] = $this->logger; /** * It might be worth putting a caching layer in */ //$default[self::PROTOCOL]['cache'] = $this->cache; stream_context_set_default($default); }
function __construct() { require_once 'constants.php'; if (PROXY) { // Define the default, system-wide context. $r_default_context = stream_context_get_default(array('http' => array('proxy' => PROXY_IP . ":" . PROXY_PORT, 'request_fulluri' => True, 'timeout' => 8))); // Though we said system wide, some extensions need a little coaxing. libxml_set_streams_context($r_default_context); } else { // Define the default, system-wide context. $r_default_context = stream_context_get_default(array('http' => array('timeout' => 8))); // Though we said system wide, some extensions need a little coaxing. libxml_set_streams_context($r_default_context); } }
/** * Execute an HTTP Request * * @param IWP_google_HttpRequest $request the http request to be executed * @return IWP_google_HttpRequest http request with the response http code, * response headers and response body filled in * @throws IWP_google_IO_Exception on curl or IO error */ public function executeRequest(IWP_google_Http_Request $request) { $default_options = stream_context_get_options(stream_context_get_default()); $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : array(); if ($request->getPostBody()) { $requestHttpContext["content"] = $request->getPostBody(); } $requestHeaders = $request->getRequestHeaders(); if ($requestHeaders && is_array($requestHeaders)) { $headers = ""; foreach ($requestHeaders as $k => $v) { $headers .= "{$k}: {$v}\r\n"; } $requestHttpContext["header"] = $headers; } $requestHttpContext["method"] = $request->getRequestMethod(); $requestHttpContext["user_agent"] = $request->getUserAgent(); $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : array(); if (!array_key_exists("cafile", $requestSslContext)) { $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem'; } $options = array("http" => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext), "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext)); $context = stream_context_create($options); $url = $request->getUrl(); if ($request->canGzip()) { $url = self::ZLIB . $url; } // Not entirely happy about this, but supressing the warning from the // fopen seems like the best situation here - we can't do anything // useful with it, and failure to connect is a legitimate run // time situation. @($fh = fopen($url, 'r', false, $context)); $response_data = false; $respHttpCode = self::UNKNOWN_CODE; if ($fh) { if (isset($this->options[self::TIMEOUT])) { stream_set_timeout($fh, $this->options[self::TIMEOUT]); } $response_data = stream_get_contents($fh); fclose($fh); $respHttpCode = $this->getHttpResponseCode($http_response_header); } if (false === $response_data) { throw new IWP_google_IO_Exception(sprintf("HTTP Error: Unable to connect: '%s'", $respHttpCode), $respHttpCode); } $responseHeaders = $this->getHttpResponseHeaders($http_response_header); return array($response_data, $responseHeaders, $respHttpCode); }
private function do_request($url, $options) { $options['http']['header'] = $this->build_headers(); stream_context_get_default($options); $data = file_get_contents($url); if ($http_response_header) { $response_headers = $this->parse_headers($http_response_header); if (isset($response_headers["Location"])) { #$response_headers["Location"]; if ($this->options['other']['follow_redirects']) { $data = $this->get($response_headers["Location"]); } } } return $data; }
public function url_stat($path, $flags) { static $modeMap = ['r' => 33060, 'r+' => 33206, 'w' => 33188]; $mode = 0; $stream = NULL; $params = stream_context_get_options(stream_context_get_default()); if (!empty($params[StreamWrapper::PROTOCOL]['stream'])) { $stream = $params[StreamWrapper::PROTOCOL]['stream']; if ($stream->isReadable()) { $mode = $stream->isWritable() ? $modeMap['r+'] : $modeMap['r']; } else { $mode = $modeMap['w']; } } return ['dev' => 0, 'ino' => 0, 'mode' => $mode, 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => $stream->getSize() ?: 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0]; }
public function __construct(array $options = []) { if (isset($options['host'])) { $this->host = $options['host']; $this->port = isset($options['port']) ? (int) $options['port'] : NULL; } else { $this->host = ini_get('SMTP'); $this->port = (int) ini_get('smtp_port'); } $this->username = isset($options['username']) ? $options['username'] : ''; $this->password = isset($options['password']) ? $options['password'] : ''; $this->secure = isset($options['secure']) ? $options['secure'] : ''; $this->timeout = isset($options['timeout']) ? (int) $options['timeout'] : 20; $this->context = isset($options['context']) ? stream_context_create($options['context']) : stream_context_get_default(); if (!$this->port) { $this->port = $this->secure === 'ssl' ? 465 : 25; } $this->persistent = !empty($options['persistent']); }
public function parseFromFilename($filename) { $this->_setLocalFileBaseUri($filename); stream_context_get_default(array('http' => array('header' => "Accept: application/rdf+xml"))); $fileHandle = fopen($filename, 'r'); stream_context_get_default(array('http' => array('header' => ""))); if ($fileHandle === false) { require_once 'Erfurt/Syntax/RdfParserException.php'; throw new Erfurt_Syntax_RdfParserException("Failed to open file with filename '{$filename}'"); } $xmlParser = $this->_getXmlParser(); // Let's parse. while ($data = fread($fileHandle, 4096)) { $this->_data = $data; xml_parse($xmlParser, $data, feof($fileHandle)); $this->_offset++; } fclose($fileHandle); return $this->_statements; }
public static function applyInitPathHook($url, $context = 'core') { $urlParts = AJXP_Utils::safeParseUrl($url); $repository = ConfService::getRepositoryById($urlParts["host"]); if ($repository == null) { throw new Exception("Cannot find repository"); } $credentials = AJXP_Safe::tryLoadingCredentialsFromSources($urlParts, $repository); $user = $credentials["user"]; $password = $credentials["password"]; if ($user == "") { throw new Exception("Cannot find user/pass for Remote Access!"); } $repoData = self::actualRepositoryWrapperData($urlParts["host"]); $repoProtocol = $repoData['protocol']; $default = stream_context_get_options(stream_context_get_default()); $auth = ['user' => $user, 'password' => $password]; $default[$repoProtocol]['auth'] = $auth; $default[$repoProtocol]['client']->setAuth($auth); stream_context_set_default($default); }
/** * Moves an uploaded file to a new location. * * @param string $filename * The filename of the uploaded file. * @param string $destination * The destination of the moved file. * @param array $context_options * An associative array of stream context options. The options will be * merged with defaults and passed to stream_context_create(). * * @see http://php.net/move_uploaded_file */ public static function move_uploaded_file($filename, $destination, array $context_options = null) { // move_uploaded_file() does not support moving a file between two different // stream wrappers. Other file handling functions like rename() have the // same problem, but copy() works since it explicitly sends the contents to // the new source. As such move_uploaded_file() is replaced by // is_uploaded_file(), copy(), and unlink() the old file. // // This also supports upload proxying during which the file may be remotely // located and referenced by a stream wrapper. In that case $filename may be // something like gs://... and $destination public://... which may end up on // the same remote filesystem, but PHP does not make the distinction. Of // course, this also means the file can be moved between two different file // systems. // // In the simple case gs:// to gs:// rename() will be called first and // invoke the more performant operation. if (is_uploaded_file($filename)) { // Either use the user provided context options, otherwise use the default // context with the Content-Type overridden. if ($context_options !== null) { $context = stream_context_create($context_options); } else { // Default to content type provided in $_FILES array. $context = stream_context_get_default(['gs' => ['Content-Type' => static::lookupContentType($filename)]]); } // Attempt rename() which is less expensive if the origin and destination // use the same stream wrapper, otherwise perform copy() and unlink(). if (@rename($filename, $destination, $context)) { static::removeUploadedFile($filename); return true; } if (copy($filename, $destination, $context) && unlink($filename, $context)) { static::removeUploadedFile($filename); return true; } } return false; }
private function request($url, $data = null, $method = 'post', $proxy = null, $headers = false, $useragent = null, $savepath = null) { $datapost = ''; if (is_array($data)) { foreach ($data as $key => $item) { $datapost .= ($datapost ? '&' : '?') . $key . '=' . @urlencode($item); } } $options = ['http' => ['method' => strtolower($method) == 'post' ? 'POST' : 'GET', 'user_agent' => is_null($useragent) ? 'PHP/Cana' : $useragent]]; stream_context_get_default($options); $this->r = fopen($url . $datapost, 'r'); if (!is_null($savepath)) { $this->write($savepath); } elseif ($savepath === false) { $this->read(); } else { $this->output = null; } if ($headers) { $this->_headersRaw = stream_get_meta_data($this->r); $this->_headersRaw = $this->_headersRaw['wrapper_data']; } }
public static function GetDraftDataForSeason($season) { // Set the API sport, method, id, format, and any parameters $host = 'erikberg.com'; $sport = 'nba'; $method = 'draft'; $id = ''; $format = 'json'; $parameters = array('season' => $season); // Pass method, format, and parameters to build request url $url = self::buildURL($host, $sport, $method, $id, $format, $parameters); // Set the User Agent, Authorization header and allow gzip $default_opts = array('http' => array('user_agent' => self::USER_AGENT, 'header' => array('Accept-Encoding: gzip', 'Authorization: Bearer ' . self::ACCESS_TOKEN))); stream_context_get_default($default_opts); $file = 'compress.zlib://' . $url; $fh = fopen($file, 'rb'); if ($fh && strpos($http_response_header[0], "200 OK") !== false) { $content = stream_get_contents($fh); fclose($fh); return json_decode($content); } else { return false; } }
protected function request_streams($url, $method = 'GET', $params = array()) { if (!$this->hostExists($url)) { throw new ErrorException('Invalid request.'); } $params = http_build_query($params, '', '&'); switch ($method) { case 'GET': $opts = array('http' => array('method' => 'GET', 'header' => 'Accept: application/xrds+xml, */*', 'ignore_errors' => true)); $url = $url . ($params ? '?' . $params : ''); break; case 'POST': $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $params, 'ignore_errors' => true)); break; case 'HEAD': // We want to send a HEAD request, // but since get_headers doesn't accept $context parameter, // we have to change the defaults. $default = stream_context_get_options(stream_context_get_default()); stream_context_get_default(array('http' => array('method' => 'HEAD', 'header' => 'Accept: application/xrds+xml, */*', 'ignore_errors' => true))); $url = $url . ($params ? '?' . $params : ''); $headers_tmp = get_headers($url); if (!$headers_tmp) { return array(); } // Parsing headers. $headers = array(); foreach ($headers_tmp as $header) { $pos = strpos($header, ':'); $name = strtolower(trim(substr($header, 0, $pos))); $headers[$name] = trim(substr($header, $pos + 1)); // Following possible redirections. The point is just to have // claimed_id change with them, because get_headers() will // follow redirections automatically. // We ignore redirections with relative paths. // If any known provider uses them, file a bug report. if ($name == 'location') { if (strpos($headers[$name], 'http') === 0) { $this->identity = $this->claimed_id = $headers[$name]; } elseif ($headers[$name][0] == '/') { $parsed_url = parse_url($this->claimed_id); $this->identity = $this->claimed_id = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $headers[$name]; } } } // And restore them. stream_context_get_default($default); return $headers; } if ($this->verify_peer) { $opts += array('ssl' => array('verify_peer' => true, 'capath' => $this->capath, 'cafile' => $this->cainfo)); } $context = stream_context_create($opts); return file_get_contents($url, false, $context); }
/** * Get the wsdl (download it). * * @param string $wsdlUri the wsdl URL * @param null|string $proxy the proxy string if required, null otherwise */ protected function loadWsdl($wsdlUri, $proxy = null) { // Set proxy. if ($proxy) { $opts = array('http' => array('proxy' => $proxy, 'request_fulluri' => true)); $context = stream_context_get_default($opts); libxml_set_streams_context($context); } $this->dom = new DOMDocument(); $this->dom->load($wsdlUri, LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NOENT | LIBXML_XINCLUDE); $this->serviceNamespace = $this->dom->documentElement->getAttribute('targetNamespace'); }
protected function request_streams($url, $method = 'GET', $params = array(), $update_claimed_id) { if (!$this->hostExists($url)) { throw new ErrorException("Could not connect to {$url}.", 404); } if (empty($this->cnmatch)) { $this->cnmatch = parse_url($url, PHP_URL_HOST); } $params = http_build_query($params, '', '&'); switch ($method) { case 'GET': $opts = array('http' => array('method' => 'GET', 'header' => 'Accept: application/xrds+xml, */*', 'user_agent' => $this->user_agent, 'ignore_errors' => true), 'ssl' => array('CN_match' => $this->cnmatch)); $url = $url . ($params ? '?' . $params : ''); if (!empty($this->proxy)) { $opts['http']['proxy'] = $this->proxy_url(); } break; case 'POST': $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'user_agent' => $this->user_agent, 'content' => $params, 'ignore_errors' => true), 'ssl' => array('CN_match' => $this->cnmatch)); if (!empty($this->proxy)) { $opts['http']['proxy'] = $this->proxy_url(); } break; case 'HEAD': // We want to send a HEAD request, but since get_headers() doesn't // accept $context parameter, we have to change the defaults. $default = stream_context_get_options(stream_context_get_default()); // PHP does not reset all options. Instead, it just sets the options // available in the passed array, therefore set the defaults manually. $default += array('http' => array(), 'ssl' => array()); $default['http'] += array('method' => 'GET', 'header' => '', 'user_agent' => '', 'ignore_errors' => false); $default['ssl'] += array('CN_match' => ''); $opts = array('http' => array('method' => 'HEAD', 'header' => 'Accept: application/xrds+xml, */*', 'user_agent' => $this->user_agent, 'ignore_errors' => true), 'ssl' => array('CN_match' => $this->cnmatch)); // Enable validation of the SSL certificates. if ($this->verify_peer) { $default['ssl'] += array('verify_peer' => false, 'capath' => '', 'cafile' => ''); $opts['ssl'] += array('verify_peer' => true, 'capath' => $this->capath, 'cafile' => $this->cainfo); } // Change the stream context options. stream_context_get_default($opts); $headers = get_headers($url . ($params ? '?' . $params : '')); // Restore the stream context options. stream_context_get_default($default); if (!empty($headers)) { if (intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) { // The server doesn't support HEAD - emulate it with a GET. $args = func_get_args(); $args[1] = 'GET'; call_user_func_array(array($this, 'request_streams'), $args); $headers = $this->headers; } else { $headers = $this->parse_header_array($headers, $update_claimed_id); } } else { $headers = array(); } return $headers; } if ($this->verify_peer) { $opts['ssl'] += array('verify_peer' => true, 'capath' => $this->capath, 'cafile' => $this->cainfo); } $context = stream_context_create($opts); $data = file_get_contents($url, false, $context); # This is a hack for providers who don't support HEAD requests. # It just creates the headers array for the last request in $this->headers. if (isset($http_response_header)) { $this->headers = $this->parse_header_array($http_response_header, $update_claimed_id); } return $data; }
/** * Get the stream context options available to the current stream * * @return array */ protected function getOptions() { $context = $this->context ?: stream_context_get_default(); $options = stream_context_get_options($context); return isset($options['s3']) ? $options['s3'] : array(); }