function http($method = "GET", $url, $argArray = null) { require_once "HTTP/Client.php"; $agent = new HTTP_Client(); if ($method == "POST") { $code = $agent->post($url, $argArray); } else { if ($argArray) { // build query string from $argArray if (strpos("?", $url)) { $query = "&"; } else { $query = "?"; } $url .= $query . http_build_query($argArray); } $code = $agent->get($url); } if (PEAR::isError($code)) { $error = $code->getMessage(); Logger::log(basename(__FILE__) . " {$method} {$url} failed: {$error}"); return false; } else { $responseArray = $agent->currentResponse(); return $responseArray['body']; } }
public function get_attendees($event_id) { $url = "http://www.eventbrite.com/myattendeestext/" . $event_id . "/attendees-" . $event_id . ".txt?sortby=&show=gross,type,status,prefix,last_name,first_name,email,job_title,company,work,work_phone,survey,actions&filterby=all,attending,all,all"; $client = new HTTP_Client(); // log in $ret = $client->post("http://www.eventbrite.com/signin", array("submitted" => "1", "referrer" => "", "email" => $this->email, "passwd" => $this->password, "remember_me" => "0")); $response = $client->currentResponse(); // var_dump($client->currentResponse()); $dom = new DOMDocument(); @$dom->loadHTML($response['body']); $xp = new DOMXPath($dom); // echo "----------- generated xml ----------------\n"; // echo $dom->saveXML(); $errors = $xp->query("//div[@id='error']"); if ($errors->length) { // an error occurred - most likely $error_text = trim($xp->query("text()", $errors->item(0))->item(0)->nodeValue); throw new PAException(USER_NOT_FOUND, "Error from EventBrite: " . $error_text); } // now fetch the attendee list CSV $ret = $client->get($url); $response = $client->currentResponse(); $mime_type = $response['headers']['content-type']; if ($mime_type != 'text/plain') { throw new PAException(GENERAL_SOME_ERROR, "Invalid MIME type received from EventBrite (expected text/plain, received {$mime_type})"); } return $this->parse_attendee_list($response['body']); }
function can_download($url) { echo "<li>Trying to download <code>{$url}</code> ... "; flush(); $client = new HTTP_Client(); $e = $client->get($url); if (PEAR::isError($e)) { echo "error " . $e->getCode() . " (" . htmlspecialchars($e->getMessage()) . ")<br>"; return FALSE; } $resp = $client->currentResponse(); $code = $resp['code']; if ($code !== 200) { echo "bad status: {$code}</li>"; flush(); return FALSE; } $body = $resp['body']; echo strlen($body) . " bytes</li>"; flush(); return $body; }
public function get_and_parse($url, $c = NULL, $method = "GET", $data = NULL) { if (empty($c)) { $c = new HTTP_Client(); } $t_start = microtime(TRUE); switch ($method) { case "POST": // $c->setDefaultHeader("Content-Type", "application/x-www-form-urlencoded"); $code = $c->post($url, $data); break; default: $code = $c->get($url); break; } $t_retrieved = microtime(TRUE); $this->assertEquals(200, $code, "Error {$code} retrieving {$url}"); $resp = $c->currentResponse(); list($dom, $xp) = Test::parse_html($resp['body']); $t_finish = microtime(TRUE); echo sprintf("Downloaded %s in %.1f s\n", $url, $t_retrieved - $t_start); return array($dom, $xp, $t_retrieved - $t_start, $c); }
/** * Get user information from pear.php.net * * This function uses the given username and password to authenticate * against the pear.php.net website * * @param string Username * @param string Password * @return mixed Error object or boolean */ function fetchData($username, $password) { $this->log('Auth_Container_PEAR::fetchData() called.', AUTH_LOG_DEBUG); $client = new HTTP_Client(); $this->log('Auth_Container_PEAR::fetchData() getting salt.', AUTH_LOG_DEBUG); $code = $client->get('https://pear.php.net/rest-login.php/getsalt'); if ($code != 200) { return PEAR::raiseError('Bad response to salt request.', $code); } $resp = $client->currentResponse(); $salt = $resp['body']; $this->log('Auth_Container_PEAR::fetchData() calling validate.', AUTH_LOG_DEBUG); $code = $client->post('https://pear.php.net/rest-login.php/validate', array('username' => $username, 'password' => md5($salt . md5($password)))); if ($code != 200) { return PEAR::raiseError('Bad response to validate request.', $code); } $resp = $client->currentResponse(); list($code, $message) = explode(' ', $resp['body'], 1); if ($code != 8) { return PEAR::raiseError($message, $code); } return true; }
$pattern = '/' . $pattern . '/i'; if (preg_match($pattern, $pURL['host'])) { $send_referer = true; } } if ($send_referer) { $referer = $uri . '.html'; } } if (is_string($referer)) { $client->setDefaultHeader('Referer', $referer); } // }}} // {{{ get // ダウンロード $code = $client->get($uri); if (PEAR::isError($code)) { ic2_error('x02', $code->getMessage()); } $response = $client->currentResponse(); // 304 Not Modified のとき if ($filepath && $force && $time && $code == 304) { ic2_finish($filepath, $thumb, $params, false); } // 200以外のときは失敗とみなす if ($code != 200) { ic2_error($code); } // Content-Type検証 if (isset($response['headers']['content-type'])) { $conent_type = $response['headers']['content-type'];
public function _request($site, $func_name, $request_method, $data, $auth = FALSE) { $headers = array("User-Agent" => "PeopleAggregator/" . PA_VERSION); global $fortythree_api_key; $data['api_key'] = $fortythree_api_key; if ($auth) { switch ($this->pw_type) { case 'raw': $data['username'] = $this->login; $data['password'] = $this->password; break; case 'wsse': $headers['Authorization'] = 'WSSE profile="UsernameToken"'; $headers['X-WSSE'] = $this->_make_wsse($this->login, $this->password); var_dump($headers); break; default: throw new PAException(0, "Invalid password type {$this->pw_type}"); } } $url = "http://www.{$site}.com/service/{$func_name}"; $c = new HTTP_Client(null, $headers); switch ($request_method) { case 'GET': $ret = $c->get($url, $data); break; case 'POST': $preEncoded = gettype($data) == "string"; $ret = $c->post($url, $data, $preEncoded); break; default: throw new PAException("invalid request method: {$request_method}"); } $r = $c->currentResponse(); echo "did http request to {$url} with data "; var_dump($data); echo ", returned {$ret}.<br>"; $xml = $r["body"]; echo "xml = <pre>" . htmlspecialchars($xml) . "</pre><hr>"; $dom = DomDocument::loadXML($xml); $xp = new DOMXPath($dom); $xp->registerNamespace("dc", "http://purl.org/dc/elements/1.1/"); $xp->registerNamespace("th", "http://43things.com/xml/2005/rc#"); $xp->registerNamespace("pl", "http://43places.com/xml/2005/rc#"); $xp->registerNamespace("pe", "http://43people.com/xml/2005/rc#"); return array("xml" => $xml, "dom" => $dom, "xpath" => $xp); }
/** * Download the remote file and save it to disk, create a thumbnail for it, * and create a database entry for the file. * * @param string $p_url * The remote location of the file. ("http://..."); * * @param array $p_attributes * Optional attributes which are stored in the database. * Indexes can be the following: 'Description', 'Photographer', 'Place', 'Date' * * @param int $p_userId * The user ID of the user who uploaded the image. * * @param int $p_id * If you are updating an image, specify its ID here. * * @return mixed * Return an Image object on success, return a PEAR_Error otherwise. */ public static function OnAddRemoteImage($p_url, $p_attributes, $p_userId = null, $p_id = null) { global $Campsite; if (function_exists("camp_load_translation_strings")) { camp_load_translation_strings("api"); } // Check if thumbnail directory is writable. $imageDir = $Campsite['IMAGE_DIRECTORY']; $thumbDir = $Campsite['THUMBNAIL_DIRECTORY']; if (!file_exists($imageDir) || !is_writable($imageDir)) { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $imageDir), CAMP_ERROR_WRITE_DIR); } if (!file_exists($thumbDir) || !is_writable($thumbDir)) { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $thumbDir), CAMP_ERROR_WRITE_DIR); } $client = new HTTP_Client(); $client->get($p_url); $response = $client->currentResponse(); if ($response['code'] != 200) { return new PEAR_Error(getGS("Unable to fetch image from remote server.")); } foreach ($response['headers'] as $headerName => $value) { if (strtolower($headerName) == "content-type") { $ContentType = $value; break; } } // Check content type if (!preg_match('/image/', $ContentType)) { // wrong URL return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url)); } // Save the file $tmpname = $Campsite['TMP_DIRECTORY'].'img'.md5(rand()); if (is_writable($Campsite['TMP_DIRECTORY'])) { if ($tmphandle = fopen($tmpname, 'w')) { fwrite($tmphandle, $response['body']); fclose($tmphandle); } } else { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE); } // Check if it is really an image file $imageInfo = getimagesize($tmpname); if ($imageInfo === false) { unlink($tmpname); return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL)); } // content-type = image if (!is_null($p_id)) { // Updating the image $image = new Image($p_id); $image->update($p_attributes); // Remove the old image & thumbnail because // the new file might have a different file extension. if (file_exists($image->getImageStorageLocation())) { if (is_writable(dirname($image->getImageStorageLocation()))) { unlink($image->getImageStorageLocation()); } else { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE); } } if (file_exists($image->getThumbnailStorageLocation())) { if (is_writable(dirname($image->getThumbnailStorageLocation()))) { unlink($image->getThumbnailStorageLocation()); } else { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE); } } } else { // Creating the image $image = new Image(); $image->create($p_attributes); $image->setProperty('TimeCreated', 'NULL', true, true); $image->setProperty('LastModified', 'NULL', true, true); } if (!isset($p_attributes['Date'])) { $image->setProperty('Date', 'NOW()', true, true); } $image->setProperty('Location', 'remote', false); $image->setProperty('URL', $p_url, false); if (isset($imageInfo['mime'])) { $image->setProperty('ContentType', $imageInfo['mime'], false); } // Remember who uploaded the image if (!is_null($p_userId)) { $image->setProperty('UploadedByUser', $p_userId, false); } if ($Campsite['IMAGEMAGICK_INSTALLED']) { // Set thumbnail file name $extension = Image::__ImageTypeToExtension($imageInfo[2]); $thumbnail = $image->generateThumbnailStorageLocation($extension); $image->setProperty('ThumbnailFileName', basename($thumbnail), false); if (!is_writable(dirname($image->getThumbnailStorageLocation()))) { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE); } // Create the thumbnail $cmd = $Campsite['THUMBNAIL_COMMAND'].' ' . $tmpname . ' ' . $image->getThumbnailStorageLocation(); system($cmd); if (file_exists($image->getThumbnailStorageLocation())) { chmod($image->getThumbnailStorageLocation(), 0644); } } unlink($tmpname); $image->commit(); $logtext = getGS('The image $1 has been added.', $image->m_data['Description']." (".$image->m_data['Id'].")"); Log::Message($logtext, null, 41); return $image; } // fn OnAddRemoteImage
function tgrep_search($query) { global $_conf; $client = new HTTP_Client(); $client->setDefaultHeader('User-Agent', 'p2-tgrep-client'); $code = $client->get($_conf['expack.tgrep_url'] . '?' . $query); if (PEAR::isError($code)) { p2die($code->getMessage()); } elseif ($code != 200) { p2die("HTTP Error - {$code}"); } $response = $client->currentResponse(); $result = unserialize($response['body']); if (!$result) { p2die('Error: 検索結果の展開に失敗しました。'); } return $result; }
--TEST-- core.get_post default --FILE-- <?php require_once 'HTTP/Client.php'; $http = new HTTP_Client(); $http->get('http://wordpress.test/?json=core.get_post&slug=about-us&dev=1'); $response = $http->currentResponse(); $response = json_decode($response['body']); echo "Response status: {$response->status}\n"; echo "post title: {$response->post->title}\n"; ?> --EXPECT-- Response status: ok post title: Markup: HTML Tags and Formatting
private function can_download($url, &$res) { $client = new HTTP_Client(); $e = $client->get($url); if (PEAR::isError($e)) { $res = $e->getCode() . '(' . htmlspecialchars($e->getMessage()) . ')'; return FALSE; } $resp = $client->currentResponse(); $code = $resp['code']; if ($code !== 200) { $res = "bad status - {$code}"; return FALSE; } else { $res = '200 OK'; } $body = $resp['body']; return $body; }
/** * HTTP_Client::get() のラッパーメソッド * * @param string $uri * @param mixed $data * @param bool $preEncoded * @param array $headers * @return array HTTPレスポンス * @throws P2Exception */ protected function httpGet($uri, $data = null, $preEncoded = false, $headers = array()) { $code = $this->_httpClient->get($uri, $data, $preEncoded, $headers); P2Exception::pearErrorToP2Exception($code); if ($code != 200) { throw new P2Exception('HTTP ' . $code); } return $this->_httpClient->currentResponse(); }
/** * Get user information from pear.php.net * * This function uses the given username and password to authenticate * against the pear.php.net website * * @param string Username * @param string Password * @return mixed Error object or boolean */ function fetchData($username, $password) { $this->log('Auth_Container_PEAR::fetchData() called.', AUTH_LOG_DEBUG); $client = new HTTP_Client(); $this->log('Auth_Container_PEAR::fetchData() getting salt.', AUTH_LOG_DEBUG); $code = $client->get($this->url . '/getsalt'); if ($code instanceof PEAR_Error) { return $code; } if ($code != 200) { return PEAR::raiseError('Bad response to salt request.', $code); } $resp = $client->currentResponse(); $salt = $resp['body']; $this->log('Auth_Container_PEAR::fetchData() calling validate.', AUTH_LOG_DEBUG); $postOptions = array('username' => $username, 'password' => md5($salt . md5($password))); if (is_array($this->karma) && count($this->karma) > 0) { $postOptions['karma'] = implode(',', $this->karma); } $code = $client->post($this->url . '/validate', $postOptions); if ($code instanceof PEAR_Error) { return $code; } if ($code != 200) { return PEAR::raiseError('Bad response to validate request.', $code); } $resp = $client->currentResponse(); list($code, $message) = explode(' ', $resp['body'], 2); if ($code != 8) { return PEAR::raiseError($message, $code); } return true; }
/** * Confirms that the server is online. * * @return boolean * True if the server is up, else false. */ public function pingServer() { // --- if ping status is false, return true without making the call --- if (isset ($this->m_disablePing) && ($this->m_disablePing == true)) { return true; } $client = new HTTP_Client(); $code = $client->get ($this->__ping); $response = $client->currentResponse(); $this->__responseHeader = $response['headers']; $this->__responseBody = $response['body']; $this->__responseCode = $code; if (preg_match ("/pong/", $this->__responseBody) && ($code == 200)) { return true; } else { return false; } } // fn pingServer
$cache = new Cache_Lite($options); // del http cache parameter _dc=12334234 $route = preg_replace('/&_dc=(\\d+)$/i', '', substr($_SERVER["QUERY_STRING"], 6)); if ($data = $cache->get($route)) { header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); echo $data; } else { $parsed_url = parse_url($route); if ($parsed_url) { if (array_key_exists("host", $parsed_url)) { $url = $route; } else { $url = 'http://api.worldbank.org' . $route; } } else { $url = 'http://api.worldbank.org' . $route; } $hc = new HTTP_Client(); $hc->setMaxRedirects(1); $hc->get($url); $response = $hc->currentResponse(); $headers = $response['headers']; $data = $response['body']; foreach ($headers as $k => $v) { header($k . ': ' . $v); } echo $data; $cache->save($data, $route); }