function initialize() { if (!$this->fetched) { $config =& get_config(); $assetUrl = $config['asset_service'] . $this->node['AssetID']; $curl = new Curl(); $curl->create($assetUrl); $curl->option(CURLOPT_HEADER, true); $curl->option(CURLOPT_NOBODY, true); $response = $curl->execute(); if ($response) { $headers = http_parse_headers($response); $this->size = $headers['Content-Length']; $this->contentType = $headers['Content-Type']; if (isset($headers['ETag'])) { $this->etag = $headers['ETag']; } else { if (isset($headers['Etag'])) { $this->etag = $headers['Etag']; } else { $this->etag = ''; } } } else { log_message('error', "InventoryFile: Failed to fetch headers from {$assetUrl}"); } $this->fetched = true; } }
/** * if PECL_HTTP is not available use a fall back function * * thanks to ricardovermeltfoort@gmail.com * http://php.net/manual/en/function.http-parse-headers.php#112986 * @param string $raw_headers raw headers * @return array */ private function parseHeaders($raw_headers) { if (function_exists('http_parse_headers')) { return http_parse_headers($raw_headers); } else { $key = ''; $headers = array(); foreach (explode("\n", $raw_headers) as $i => $h) { $h = explode(':', $h, 2); if (isset($h[1])) { if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } $key = $h[0]; } else { if (substr($h[0], 0, 1) == "\t") { $headers[$key] .= "\r\n\t" . trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); } } } return $headers; } }
/** * Parses a HTTP header string into an associative array * * @param string $header_string Header string to parse * @return HTTP_Header */ public static function parse_header_string($header_string) { // If the PECL HTTP extension is loaded if (extension_loaded('http')) { // Use the fast method to parse header string return new HTTP_Header(http_parse_headers($header_string)); } // Otherwise we use the slower PHP parsing $headers = array(); // Match all HTTP headers if (preg_match_all('/(\\w[^\\s:]*):[ ]*([^\\r\\n]*(?:\\r\\n[ \\t][^\\r\\n]*)*)/', $header_string, $matches)) { // Parse each matched header foreach ($matches[0] as $key => $value) { // If the header has not already been set if (!isset($headers[$matches[1][$key]])) { // Apply the header directly $headers[$matches[1][$key]] = $matches[2][$key]; } else { // If the entry is an array if (is_array($headers[$matches[1][$key]])) { // Apply the new entry to the array $headers[$matches[1][$key]][] = $matches[2][$key]; } else { $headers[$matches[1][$key]] = array($headers[$matches[1][$key]], $matches[2][$key]); } } } } // Return the headers return new HTTP_Header($headers); }
/** * Executes a curl request. * * @param resource $request * @return \Frlnc\Slack\Contracts\Http\Response */ public function executeMultiRequest($multiRequest, $singleRequests) { $responses = []; $infos = []; $active = null; do { $status = curl_multi_exec($multiRequest, $active); $infos[] = curl_multi_info_read($multiRequest); } while ($status === CURLM_CALL_MULTI_PERFORM || $active); foreach ($singleRequests as $index => $singleRequest) { $body = curl_multi_getcontent($singleRequest); curl_multi_remove_handle($multiRequest, $singleRequest); curl_close($singleRequest); $info = $infos[$index]; $statusCode = $info['http_code']; $headers = $info['request_header']; if (function_exists('http_parse_headers')) { $headers = http_parse_headers($headers); } else { $header_text = substr($headers, 0, strpos($headers, "\r\n\r\n")); $headers = []; foreach (explode("\r\n", $header_text) as $i => $line) { if ($i !== 0) { list($key, $value) = explode(': ', $line); $headers[$key] = $value; } } } $responses[] = $this->factory->build($body, $headers, $statusCode); } curl_multi_close($multiRequest); return $responses; }
/** * @param $raw * @return array */ public static function parseHeaders($raw) { if (!$raw) { return []; } if (function_exists('http_parse_headers')) { return http_parse_headers($raw); } $headers = []; $key = ''; foreach (explode("\n", $raw) as $h) { $h = explode(':', $h, 2); if (isset($h[1])) { if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), [trim($h[1])]); } $key = $h[0]; } else { if (substr($h[0], 0, 1) == "\t") { $headers[$key] .= "\r\n\t" . trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); } } } return $headers; }
function message($cookie, $id, $subject = 'None', $body = 'None', $save = '../Private/mxcsrf.txt') { $xcsrf = file_exists($save) ? file_get_contents($save) : ''; $curl = curl_init('http://www.roblox.com/messages/send'); $send = array('subject' => $subject, 'body' => $body, 'recipientid' => $id, 'cacheBuster' => time()); curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array("X-CSRF-TOKEN: {$xcsrf}"), CURLOPT_POST => true, CURLOPT_POSTFIELDS => $send, CURLOPT_COOKIEFILE => $cookie, CURLOPT_COOKIEJAR => $cookie, CURLOPT_RETURNTRANSFER => true)); $response = curl_exec($curl); $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { if ($responseCode == 403) { // 403 XCSRF Token Validation Failed $header = http_parse_headers(substr($response, 0, $headerSize)); $xcsrf = $header['X-CSRF-TOKEN']; file_put_contents($save, $xcsrf); return message($cookie, $id, $subject, $body, $save); } } $json = json_decode(substr($response, $headerSize), true); if ($json['success']) { return "Sent message {$subject} to {$id}."; } else { $error = $json['shortMessage']; return "Error sending message {$subject} to {$id}: {$error}"; } }
protected function loadFromURL($url) { $image = file_get_contents($url); $headers = http_parse_headers(implode("\r\n", $http_response_header)); $ext = array_search($headers['Content-Type'], $mimeExtensions); return array($image, $ext); }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection(); // add your code here $blogs = Doctrine::getTable('Blog'); $blogs_to_process = $blogs->findByIsThumbnail(0); foreach ($blogs_to_process as $blog) { $thumbalizr_url = 'http://api.thumbalizr.com?'; $params = array('url' => $blog->url, 'width' => 300); $api_url = $thumbalizr_url . http_build_query($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $res = curl_exec($ch); curl_close($ch); $res_tab = http_parse_headers($res); if (!empty($res_tab['X-Thumbalizr-Status']) && $res_tab['X-Thumbalizr-Status'] == 'OK') { // Image is ready let's store the URL! $image_data = file_get_contents($api_url); $path = sfConfig::get('app_image_path'); $url = sfConfig::get('app_image_url'); $image_name = md5($blog->url); echo $path . $image_name . "\n"; file_put_contents($path . $image_name . '.jpg', $image_data); $blog->thumbnail_url = $image_name . '.jpg'; $blog->is_thumbnail = 1; $blog->save(); // Send mail to notify the blo will get into the game! try { // Create the mailer and message objects //$mailer = new Swift(new Swift_Connection_NativeMail()); //$connection = new Swift_Connection_SMTP('smtp.free.fr'); $connection = new Swift_Connection_NativeMail(); $mailer = new Swift($connection); $message = new Swift_Message('Welcome!'); // Render message parts $mailContext = array('admin_hash' => $blog->getAdmin_hash(), 'blog_url' => $blog->getUrl()); $v = $this->getPartial('newBlogMailHtmlBody', $mailContext); $htmlPart = new Swift_Message_Part($v, 'text/html'); $message->attach($htmlPart); $message->attach(new Swift_Message_Part($this->getPartial('newBlogMailTextBody', $mailContext), 'text/plain')); $mailTo = $blog->getEmail(); $mailFrom = sfConfig::get('app_mail_webmaster'); $mailer->send($message, $mailTo, $mailFrom); $mailer->disconnect(); } catch (Exception $e) { $this->logMessage($e); } } else { //print_r($res_tab); } } }
function header_fetch($url, $check_against) { $data = get_url($url, true); $headers = http_parse_headers($data); foreach ($headers as $key => $value) { if ($key == $check_against->header_option) { echo $key . ': ' . $value; } } }
public static function getPingbackServerURL($url) { (new Chainable(new cURL($url)))->setopt(CURLOPT_HEADER, true)->setopt(CURLOPT_NOBODY, true)->setopt(CURLOPT_RETURNTRANSFER, true)->exec()->_get_return($curldata)->close(); $headers = http_parse_headers($curldata); if (isset($headers['X-Pingback']) && !empty($headers['X-Pingback'])) { return $headers['X-Pingback']; } $response = file_get_contents($url); return preg_match(self::REGEXP_PINGBACK_LINK, $response, $match) ? $match[1] : false; }
function parseHeader($header) { $head = http_parse_headers($header); if ($head === false) { return false; } else { $head[0]['protocol'] = "HTTP/1.1"; $head[0]['uri'] = $head["Request Url"]; $head[0]['method'] = $head["Request Method"]; } return $head; }
/** * Return the headers as associative array or return the given header. * @param string $key * @return string|string[] */ public function getHeaders($key = null) { if (!$this->headers) { $this->headers = http_parse_headers($this->rawHeaders); } if ($key) { if (isset($this->headers[$key])) { return $this->headers[$key]; } } return $this->headers; }
function updateRank($group, $userId, $rank, $cookie, $ranks, $roles, $rankLimit = 255, $save = '../Private/gxcsrf.txt') { // OH MY GOD SO MANY ARGUMENTS! $xcsrf = file_exists($save) ? file_get_contents($save) : ''; /* If you want to increase performance do this: Move the following line (currentRank) into the rankLimit if statement. Change the success return to something simpler (does not return user's previous rank) This doesn't actually slow it down that much at all, but when changing ranks **IN BULK** you will be making a lot of requests. */ $currentRank = getRankInGroup($userId, $group); if ($rankLimit && $rankLimit < 255) { if ($rank > $rankLimit || $currentRank > $rankLimit) { // Check if the rank you are trying to change them to and their rank abide to the rank limit return "Settings restrict the system from changing any rank over {$rankLimit}."; } } $url = "http://www.roblox.com/groups/api/change-member-rank?groupId={$group}&newRoleSetId=" . getRoleSet($ranks, $rank) . "&targetUserId={$userId}"; // Get rank URL $curl = curl_init($url); curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array("X-CSRF-TOKEN: {$xcsrf}", 'Content-Length: 0'), CURLOPT_POST => true, CURLOPT_COOKIEFILE => $cookie, CURLOPT_COOKIEJAR => $cookie, CURLOPT_RETURNTRANSFER => true)); $response = curl_exec($curl); $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { // BELOW 302 DOES NOT WORK AND IS DEPRACATED FOR NOW /*if ($responseCode == 302) { // 302 Moved temporarily - User is not logged in: Redirect to error page login($cookie,$username,$password); return updateRank($username,$password,$group,$userId,$rank,$cookie,$ranks,$roles,$rankLimit,$save); // Would appreciate if someone showed me a better way to do this (not repassing every argument manually). } else */ if ($responseCode == 403) { // 403 XCSRF Token Validation Failed - CONVENIENCE! $header = http_parse_headers(substr($response, 0, $headerSize)); $xcsrf = $header['X-CSRF-TOKEN']; file_put_contents($save, $xcsrf); return updateRank($group, $userId, $rank, $cookie, $ranks, $roles, $rankLimit, $save); } } $response = substr($response, $headerSize); curl_close($curl); if (json_decode($response, true)['success'] == false) { return 'Invalid promoting permissions.'; } else { $current = getRoleSet($ranks, $currentRank); $new = getRoleSet($ranks, $rank); return "Successfully changed rank of user {$userId} from " . $roles[$current] . ' to ' . $roles[$new] . '.'; // Details! } }
public static function getPingbackServerURL($url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $headers = http_parse_headers(curl_exec($curl)); curl_close($curl); if (isset($headers['X-Pingback']) && !empty($headers['X-Pingback'])) { return $headers['X-Pingback']; } $response = file_get_contents($url); return preg_match(self::REGEXP_PINGBACK_LINK, $response, $match) ? $match[1] : false; }
function handleJoinRequest($cookie, $group, $username, $choice, $save = 'hxcsrf.txt', $requestId = -1) { $xcsrf = file_exists($save) ? file_get_contents($save) : ''; $url = "http://www.roblox.com/My/GroupAdmin.aspx?gid={$group}"; switch ($choice) { case 'Accept': $choiceNumber = 1; break; case 'Decline': $choiceNumber = 2; break; default: die('Invalid choice.'); } if ($requestId === -1) { // This is so that if the function is being re called with the request ID already received you don't go through the whole process again (because it takes up a lot of time) $curl = curl_init($url); curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEFILE => $cookie, CURLOPT_COOKIEJAR => $cookie)); $response = curl_exec($curl); $nextPost = getPostArray(substr($response, curl_getinfo($curl, CURLINFO_HEADER_SIZE)), array('ctl00$ctl00$cphRoblox$cphMyRobloxContent$JoinRequestsSearchBox' => $username, 'ctl00$ctl00$cphRoblox$cphMyRobloxContent$JoinRequestsSearchButton' => 'Search')); curl_close($curl); $curl = curl_init($url); curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $nextPost, CURLOPT_COOKIEFILE => $cookie, CURLOPT_COOKIEJAR => $cookie)); $response = curl_exec($curl); $doc = new DOMDocument(); $doc->loadHTML($response); $find = new DomXPath($doc); $nodes = $find->query("//span[contains(@class,'btn-control btn-control-medium accept-join-request')][1]"); foreach ($nodes as $node) { $requestId = $node->getAttribute('data-rbx-join-request'); } } $curl = curl_init('http://www.roblox.com/group/handle-join-request'); $post = array('groupJoinRequestId' => $requestId, 'accept' => $choiceNumber == 1 ? true : false); curl_setopt_array($curl, array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($post), CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array("X-CSRF-TOKEN: {$xcsrf}", 'Content-Length: ' . strlen(json_encode($post)), 'Content-Type: application/json; charset=UTF-8'), CURLOPT_COOKIEFILE => $cookie, CURLOPT_COOKIEJAR => $cookie, CURLOPT_RETURNTRANSFER => true)); $response = curl_exec($curl); $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { if ($responseCode == 403) { // 403 XCSRF Token Validation Failed $header = http_parse_headers(substr($response, 0, $headerSize)); $xcsrf = $header['X-CSRF-TOKEN']; file_put_contents($save, $xcsrf); return handleJoinRequest($cookie, $group, $username, $choice, $save, $requestId); } } $text = $choiceNumber == 1 ? 'ed' : 'd'; return "{$choice}{$text} {$username}'s join request."; }
function minify($code) { $ch = curl_init('http://refresh-sf.com/yui/'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('compresstext' => $code, 'semi' => 'on', 'redirect' => '1')); curl_setopt($ch, CURLOPT_HEADER, true); // curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $result = http_parse_headers($result); $location = 'http://refresh-sf.com' . str_replace('.min.js.gz', '.min.js', $result['Location']); curl_close($ch); $result = file_get_contents($location); return strpos($result, '[ERROR]') ? $code : $result; }
protected static function fetch_tarball_via_oauth($key, $secret, $uri) { try { $oauth = new OAuth($key, $secret); $oauth->fetch($uri); WP_CLI::debug($oauth->getLastResponseHeaders()); $headers = http_parse_headers($oauth->getLastResponseHeaders()); $mime_type = self::parse_content_type_header($headers['Content-Type']); $content_disposition = self::parse_content_disposition_header($headers['Content-Disposition']); $filename = empty($content_disposition['filename']) ? $filename = tmpfile() : sys_get_temp_dir() . DIRECTORY_SEPARATOR . $content_disposition['filename']; file_put_contents($filename, $oauth->getLastResponse()); return $filename; } catch (OAuthException $e) { WP_CLI::error_multi_line($e->getMessage(), true); } WP_CLI::error('Unknown error', true); }
public function send($body = null) { if (isset($body)) { $this->curlSetOpt(CURLOPT_POSTFIELDS, $body); } $response = new \stdClass(); try { $response->body = $this->curlExec(); $header_size = $this->curlGetinfo(CURLINFO_HEADER_SIZE); $response->headers = http_parse_headers(substr($response->body, 0, $header_size)); $body = substr($response->body, $header_size); if ($this->parse_response and array_key_exists('Content-Type', $response->headers)) { switch ($response->headers['Content-Type']) { case 'application/json': $response->body = json_decode($body); break; case 'application/xml': $response->body = simplexml_load_string($body); break; case 'application/x-www-form-urlencoded': parse_str($body, $response->body); break; case 'application/vnd.php.serialized': $response->body = unserialize($body); break; case 'text/plain': $response->body = $body; break; default: $response->body = $body; break; } unset($body); } else { $response->body = $body; } $response->errno = $this->curlErrno(); $response->error = $this->curlError(); return $response; } catch (\Exception $e) { exit($e); } }
function curlGet($url) { global $token; $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $_SESSION['canvasURL'] . '/api/v1/' . $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $GLOBALS['tokenHeader']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // ask for results to be returned curl_setopt($ch, CURLOPT_VERBOSE, 1); //Requires to load headers curl_setopt($ch, CURLOPT_HEADER, 1); //Requires to load headers $result = curl_exec($ch); // var_dump($result); #Parse header information from body response $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($result, 0, $header_size); $body = substr($result, $header_size); $data = json_decode($body); curl_close($ch); #Parse Link Information $header_info = http_parse_headers($header); if (isset($header_info['Link'])) { $links = explode(',', $header_info['Link']); foreach ($links as $value) { if (preg_match('/^\\s*<(.*?)>;\\s*rel="(.*?)"/', $value, $match)) { $links[$match[2]] = $match[1]; } } } #Check for Pagination if (isset($links['next'])) { // Remove the API url so it is not added again in the get call $next_link = str_replace($_SESSION['canvasURL'] . '/api/v1/', '', $links['next']); $next_data = curlGet($next_link); $data = array_merge($data, $next_data); return $data; } else { return $data; } }
function exile($cookie, $group, $senderRoleSetId, $userId, $deletePosts = false, $save = '../Private/excsrf.txt') { $xcsrf = file_exists($save) ? file_get_contents($save) : ''; $curl = curl_init('http://www.roblox.com/My/Groups.aspx/ExileUserAndDeletePosts'); $post = array('userId' => $userId, 'deleteAllPostsOption' => $deletePosts, 'rolesetId' => $senderRoleSetId, 'selectedGroupId' => $group); curl_setopt_array($curl, array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($post), CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array("X-CSRF-TOKEN: {$xcsrf}", 'Content-Length: ' . strlen(json_encode($post)), 'Content-Type: application/json; charset=utf-8'), CURLOPT_COOKIEFILE => $cookie, CURLOPT_COOKIEJAR => $cookie, CURLOPT_RETURNTRANSFER => true)); $response = curl_exec($curl); $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { if ($responseCode == 403) { // 403 XCSRF Token Validation Failed $header = http_parse_headers(substr($response, 0, $headerSize)); $xcsrf = $header['X-CSRF-TOKEN']; file_put_contents($save, $xcsrf); return exile($cookie, $group, $senderRoleSetId, $userId, $deletePosts, $save); } } $delete = $deletePosts ? 'deleted' : 'did not delete'; return "Exiled user {$userId}, {$delete} posts."; }
/** * Returns array of parsed HTTP headers from string * * @param string * @param bool if true, all header keys are converted to lower case * * @return array */ public static function parseHeaders($str, $keyCaseConvert = false) { // PECL_HTTP // http://php.net/manual/en/function.http-parse-headers.php if (function_exists('http_parse_headers')) { return !$keyCaseConvert ? http_parse_headers($str) : array_change_key_case(http_parse_headers($str)); } // Otherwise $retVal = array(); $fields = explode("\r\n", preg_replace('/\\x0D\\x0A[\\x09\\x20]+/', ' ', $str)); foreach ($fields as $field) { if (preg_match('/([^:]+): (.+)/m', $field, $match)) { $match[1] = preg_replace('/(?<=^|[\\x09\\x20\\x2D])./e', 'strtoupper("\\0")', strtolower(trim($match[1]))); if (isset($retVal[$match[1]])) { $retVal[$match[1]] = array($retVal[$match[1]], $match[2]); } else { $retVal[$match[1]] = trim($match[2]); } } } return !$keyCaseConvert ? $retVal : array_change_key_case($retVal, CASE_LOWER); }
public static function parse_header_string($header_string) { if (extension_loaded("http")) { $headers = version_compare(phpversion("http"), "2.0.0", ">=") ? \http\Header::parse($header_string) : http_parse_headers($header_string); return new HTTP_Header($headers); } $headers = array(); if (preg_match_all('/(\\w[^\\s:]*):[ ]*([^\\r\\n]*(?:\\r\\n[ \\t][^\\r\\n]*)*)/', $header_string, $matches)) { foreach ($matches[0] as $key => $value) { if (!isset($headers[$matches[1][$key]])) { $headers[$matches[1][$key]] = $matches[2][$key]; } else { if (is_array($headers[$matches[1][$key]])) { $headers[$matches[1][$key]][] = $matches[2][$key]; } else { $headers[$matches[1][$key]] = array($headers[$matches[1][$key]], $matches[2][$key]); } } } } return new HTTP_Header($headers); }
/** * Executes a curl request. * * @param resource $request * @return \Frlnc\Slack\Contracts\Http\Response */ public function executeRequest($request) { $body = curl_exec($request); $info = curl_getinfo($request); curl_close($request); $statusCode = $info['http_code']; $headers = $info['request_header']; if (function_exists('http_parse_headers')) { $headers = http_parse_headers($headers); } else { $header_text = substr($headers, 0, strpos($headers, "\r\n\r\n")); $headers = []; foreach (explode("\r\n", $header_text) as $i => $line) { if ($i === 0) { continue; } else { list($key, $value) = explode(': ', $line); $headers[$key] = $value; } } } return $this->factory->build($body, $headers, $statusCode); }
function curl_head_shim($url, $follow_redirect = true, $tmp_dir = '') { $info = array(); $ch = curl_init(); $output = fopen('/dev/null', 'w'); $header_dir = $tmp_dir . '/curl_header'; $headerfile = fopen($header_dir, 'w+'); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FILE, $output); curl_setopt($ch, CURLOPT_WRITEHEADER, $headerfile); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Data.gov data.json crawler'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $follow_redirect); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_exec($ch); fclose($headerfile); $http_heading = file_get_contents($header_dir); unset($header_dir); $info['info'] = curl_getinfo($ch); curl_close($ch); $info['header'] = http_parse_headers($http_heading); return $info; }
public function setToken() { $headers = http_parse_headers($this->curContent); $this->authToken = $headers["X-Api-Token"]; }
function get_pgn() { global $pgnText, $pgnTextbox, $pgnUrl, $pgnFileName, $pgnFileSize, $pgnStatus, $forceEncodingFrom, $tmpDir, $debugHelpText, $pgnDebugInfo; global $fileUploadLimitIniText, $fileUploadLimitText, $fileUploadLimitBytes, $startPosition, $goToView, $zipSupported; global $http_response_header_status, $http_response_header_last_modified; $pgnDebugInfo = $pgnDebugInfo . get_param("debug", "d", ""); $pgnText = get_param("pgnText", "pt", ""); $pgnUrl = get_param("pgnData", "pd", ""); if ($pgnUrl == "") { $pgnUrl = get_param("pgnUrl", "pu", ""); } if ($pgnText) { $pgnStatus = "info: games from textbox input"; $pgnTextbox = $pgnText = str_replace("\\\"", "\"", $pgnText); $pgnText = preg_replace("/\\[/", "\n\n[", $pgnText); $pgnText = preg_replace("/\\]/", "]\n\n", $pgnText); $pgnText = preg_replace("/([012\\*])(\\s*)(\\[)/", "\$1\n\n\$3", $pgnText); $pgnText = preg_replace("/\\]\\s*\\[/", "]\n[", $pgnText); $pgnText = preg_replace("/^\\s*\\[/", "[", $pgnText); $pgnText = preg_replace("/\n[\\s*\n]+/", "\n\n", $pgnText); $pgnTextbox = $pgnText; return TRUE; } else { if ($pgnUrl) { $pgnStatus = "info: games from {$pgnUrl}"; $isPgn = preg_match("/\\.(pgn|txt)\$/i", preg_replace("/[?#].*\$/", "", $pgnUrl)); $isZip = preg_match("/\\.zip\$/i", preg_replace("/[?#].*\$/", "", $pgnUrl)); if ($isZip) { if (!$zipSupported) { $pgnStatus = "error: zipfile support unavailable, unable to open {$pgnUrl}"; return FALSE; } else { $tempZipName = tempnam($tmpDir, "pgn4webViewer_"); // $pgnUrlOpts tries forcing following location redirects // depending on server configuration, the script might still fail if the ZIP URL is redirected $pgnUrlOpts = array("http" => array("follow_location" => TRUE, "max_redirects" => 20)); $pgnUrlHandle = @fopen($pgnUrl, "rb", false, stream_context_create($pgnUrlOpts)); if (!$pgnUrlHandle) { $pgnStatus = "error: failed to get {$pgnUrl}: file not found or server error"; if (isset($tempZipName) && $tempZipName && file_exists($tempZipName)) { unlink($tempZipName); } return FALSE; } else { $tempZipHandle = fopen($tempZipName, "wb"); $copiedBytes = stream_copy_to_stream($pgnUrlHandle, $tempZipHandle, $fileUploadLimitBytes + 1, 0); fclose($pgnUrlHandle); fclose($tempZipHandle); if (isset($http_response_header)) { http_parse_headers($http_response_header); } if ($copiedBytes > 0 && $copiedBytes <= $fileUploadLimitBytes && !http_response_header_isInvalid()) { $pgnSource = $tempZipName; } else { $pgnStatus = "error: failed to get {$pgnUrl}: " . (http_response_header_isInvalid() ? "server error: {$http_response_header_status}" : "file not found, file size exceeds {$fileUploadLimitText} form limit, {$fileUploadLimitIniText} server limit or server error"); if (isset($tempZipName) && $tempZipName && file_exists($tempZipName)) { unlink($tempZipName); } return FALSE; } } } } else { $pgnSource = $pgnUrl; } } elseif (count($_FILES) == 0) { $pgnStatus = "info: no games supplied"; return FALSE; } elseif ($_FILES['pgnFile']['error'] === UPLOAD_ERR_OK) { $pgnFileName = $_FILES['pgnFile']['name']; $pgnStatus = "info: games from file {$pgnFileName}"; $pgnFileSize = $_FILES['pgnFile']['size']; if ($pgnFileSize == 0) { $pgnStatus = "info: failed uploading games: file not found, file empty or upload error"; return FALSE; } elseif ($pgnFileSize > $fileUploadLimitBytes) { $pgnStatus = "error: failed uploading games: file size exceeds {$fileUploadLimitText} limit"; return FALSE; } else { $isPgn = preg_match("/\\.(pgn|txt)\$/i", $pgnFileName); $isZip = preg_match("/\\.zip\$/i", $pgnFileName); $pgnSource = $_FILES['pgnFile']['tmp_name']; } } else { $pgnStatus = "error: failed uploading games: "; switch ($_FILES['pgnFile']['error']) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $pgnStatus = $pgnStatus . "file size exceeds {$fileUploadLimitText} form limit or {$fileUploadLimitIniText} server limit"; break; case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: $pgnStatus = $pgnStatus . "file missing or truncated"; break; case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: $pgnStatus = $pgnStatus . "server error"; break; default: $pgnStatus = $pgnStatus . "unknown upload error"; break; } return FALSE; } } if ($isZip) { if ($zipSupported) { if ($pgnUrl) { $zipFileString = $pgnUrl; } else { $zipFileString = "zip file"; } $pgnZip = zip_open($pgnSource); if (is_resource($pgnZip)) { while (is_resource($zipEntry = zip_read($pgnZip))) { if (zip_entry_open($pgnZip, $zipEntry)) { if (preg_match("/\\.pgn\$/i", zip_entry_name($zipEntry))) { $pgnText = $pgnText . zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)) . "\n\n\n"; } zip_entry_close($zipEntry); } else { $pgnStatus = "error: failed reading {$zipFileString} content"; zip_close($pgnZip); if (isset($tempZipName) && $tempZipName && file_exists($tempZipName)) { unlink($tempZipName); } return FALSE; } } zip_close($pgnZip); if (isset($tempZipName) && $tempZipName && file_exists($tempZipName)) { unlink($tempZipName); } if (!$pgnText) { $pgnStatus = "error: games not found in {$zipFileString}"; return FALSE; } } else { if (isset($tempZipName) && $tempZipName && file_exists($tempZipName)) { unlink($tempZipName); } $pgnStatus = "error: failed opening {$zipFileString}"; return FALSE; } } else { $pgnStatus = "error: ZIP support unavailable from this server, only PGN files are supported"; return FALSE; } } elseif ($isPgn) { if ($pgnUrl) { $pgnFileString = $pgnUrl; } else { $pgnFileString = "pgn file"; } $pgnText = @file_get_contents($pgnSource, NULL, NULL, 0, $fileUploadLimitBytes + 1); if (isset($http_response_header)) { http_parse_headers($http_response_header); } if (!$pgnText || $pgnUrl && http_response_header_isInvalid()) { $pgnStatus = "error: failed reading {$pgnFileString}: " . (http_response_header_isInvalid() ? "server error: {$http_response_header_status}" : "file not found or server error"); return FALSE; } if (strlen($pgnText) == 0 || strlen($pgnText) > $fileUploadLimitBytes) { $pgnStatus = "error: failed reading {$pgnFileString}: file size exceeds {$fileUploadLimitText} form limit, {$fileUploadLimitIniText} server limit or server error"; return FALSE; } } elseif ($pgnSource) { if ($zipSupported) { $pgnStatus = "error: only PGN and ZIP (zipped pgn) files are supported"; } else { $pgnStatus = "error: only PGN files are supported, ZIP support unavailable from this server"; } return FALSE; } $assumedEncoding = $forceEncodingFrom; if ($assumedEncoding == "") { // DeploymentCheck: conversion for given URLs // end DeploymentCheck } if ($assumedEncoding != "" && strtoupper($assumedEncoding) != "NONE") { // convert text encoding to UNICODE, for example from windows WINDOWS-1252 files $pgnText = html_entity_decode(htmlentities($pgnText, ENT_QUOTES, $assumedEncoding), ENT_QUOTES, "UNICODE"); } return TRUE; }
/** * Send xml data to * @param string $remote_url * @param string $xml * @param string $username * @param string $password * @param int $debug when 1 (or 2) will enable debugging of the underlying xmlrpc call (defaults to 0) * @return xmlrpcresp obj instance */ private static function _xmlrpc_j2xml_send($remote_url, $xml, $username, $password, $debug = 0) { $protocol = ''; $GLOBALS['xmlrpc_internalencoding'] = 'UTF-8'; $client = new xmlrpc_client($remote_url); $client->return_type = 'xmlrpcvals'; $client->request_charset_encoding = 'UTF-8'; $client->user_agent = J2XMLVersion::$PRODUCT . ' ' . J2XMLVersion::getFullVersion(); $client->setDebug($debug); $msg = new xmlrpcmsg('j2xml.import'); $p1 = new xmlrpcval(base64_encode($xml), 'base64'); $msg->addparam($p1); $p2 = new xmlrpcval($username, 'string'); $msg->addparam($p2); $p3 = new xmlrpcval($password, 'string'); $msg->addparam($p3); $res = $client->send($msg, 0); if (!$res->faultcode()) { return $res; } if ($res->faultString() == "Didn't receive 200 OK from remote server. (HTTP/1.1 301 Foun)") { $res = $client->send($msg, 0, $protocol = 'http11'); if (!$res->faultcode()) { return $res; } } if ($res->faultString() == "Didn't receive 200 OK from remote server. (HTTP/1.1 303 See other)") { $headers = http_parse_headers($res->raw_data); $client = new xmlrpc_client($headers['Location']); $client->return_type = 'xmlrpcvals'; $client->request_charset_encoding = 'UTF-8'; $client->user_agent = J2XMLVersion::$PRODUCT . ' ' . J2XMLVersion::getFullVersion(); $client->setDebug($debug); $res = $client->send($msg, 0, $protocol); } return $res; }
/** * Replacement for file_get_contents for retrieving remote files. * Essentially a wrapper for self::get() * @param type $url */ static function file_get_contents($url) { $result = self::get($url); // Checking for redirects (HTTP codes 301 and 302) $redirect_count = 0; while ($result['response'] == 302 || $result['response'] == 301) { $redirect_count += 1; if ($redirect_count >= 3) { // We have followed 3 redirections already… // This may be a redirect loop so we'd better drop it already. return false; } // The redirection URL is the "location" field of the header $result = self::get(http_parse_headers($result['header'])["location"]); } if ($result['error'] == "") { return $result['content']; } return false; }
public function setToken() { $headers = http_parse_headers($this->curContent); $this->authToken = $headers["X-Api-Token"]; $_SESSSION["NANDA3-API-TOKEN"] = $this->authToken; }
do { //Принимаем соединение с сокетом if (($Message = socket_accept($Socket)) < 0) { F::Log('Error accepting connection', LOG_ERR); } else { F::Log('Socket ready to connect', LOG_INFO); $Request = ''; $Output = 'HTTP/1.1 200 OK'; do { if (false === ($Buffer = socket_read($Message, 1024))) { F::Log('Error reading socket', LOG_ERR); } else { $Request .= $Buffer; if (empty(trim($Buffer))) { F::Log('Message received', LOG_INFO); $Headers = http_parse_headers($Request); print_r($Headers); print_r($Request); /* $Call['UA'] = $Headers['User-Agent']; $Call['HTTP']['URL'] = $Headers['Request Url'];*/ /* $Call = F::Run('Code.Flow.Front', 'Run', $Call);*/ socket_write($Socket, $Output . chr(0), 64); break; } } } while (true); } } while (true); if (isset($Scoket)) { socket_close($Socket); F::Log('Socket closed', LOG_INFO);