/** * Send an HTTP GET to the notification handler with a * challenge string to see if it repsonds correctly. * * @param string $endpoint URL of the notification handler * @param string $feed the feed being subscribed to * * @return boolean success */ function challenge($endpoint, $feed) { $code = common_confirmation_code(128); $params = array('url' => $feed, 'challenge' => $code); $url = $endpoint . '?' . http_build_query($params); try { $client = new HTTPClient(); $response = $client->get($url); } catch (HTTP_Request2_Exception $e) { common_log(LOG_INFO, 'RSSCloud plugin - failure testing notify handler ' . $endpoint . ' - ' . $e->getMessage()); return false; } // Check response is betweet 200 and 299 and body contains challenge data $status = $response->getStatus(); $body = $response->getBody(); if ($status >= 200 && $status < 300) { // NOTE: the spec says that the body must contain the string // challenge. It doesn't say that the body must contain the // challenge string ONLY, although that seems to be the way // the other implementors have interpreted it. if (strpos($body, $code) !== false) { common_log(LOG_INFO, 'RSSCloud plugin - ' . "success testing notify handler: {$endpoint}"); return true; } else { common_log(LOG_INFO, 'RSSCloud plugin - ' . 'challenge/repsonse failed for notify handler ' . $endpoint); common_debug('body = ' . var_export($body, true)); return false; } } else { common_log(LOG_INFO, 'RSSCloud plugin - ' . "failure testing notify handler: {$endpoint} " . ' - got HTTP ' . $status); common_debug('body = ' . var_export($body, true)); return false; } }
function testGetRequestIsUnsuccessful() { \VCR\VCR::insertCassette('gathercontent_get_me_failure.yml'); $subject = new HTTPClient('*****@*****.**', 'bogus-api-key'); $response = $subject->get('https://api.gathercontent.com/me', [], ['Accept: application/vnd.gathercontent.v0.5+json']); $this->assertNotEquals(200, $response->status); $this->assertEquals('Invalid credentials.', $response->body); }
public function checkUpdates(FeedSub $feedsub) { $request = new HTTPClient(); $feed = $request->get($feedsub->uri); if (!$feed->isOk()) { throw new ServerException('FeedSub could not fetch id=' . $feedsub->id . ' (Error ' . $feed->getStatus() . ': ' . $feed->getBody()); } $feedsub->receive($feed->getBody(), null); }
static function fromHcardUrl($url) { $client = new HTTPClient(); $client->setHeader('Accept', 'text/html,application/xhtml+xml'); $response = $client->get($url); if (!$response->isOk()) { return null; } return self::hcardHints($response->getBody(), $response->getUrl()); }
private function _parseSvcDoc() { $client = new HTTPClient(); $response = $client->get($this->svcDocUrl); if ($response->getStatus() != 200) { throw new Exception("Can't get {$this->svcDocUrl}; response status " . $response->getStatus()); } $xml = $response->getBody(); $dom = new DOMDocument(); // We don't want to bother with white spaces $dom->preserveWhiteSpace = false; // Don't spew XML warnings to output $old = error_reporting(); error_reporting($old & ~E_WARNING); $ok = $dom->loadXML($xml); error_reporting($old); $path = new DOMXPath($dom); $path->registerNamespace('atom', 'http://www.w3.org/2005/Atom'); $path->registerNamespace('app', 'http://www.w3.org/2007/app'); $path->registerNamespace('activity', 'http://activitystrea.ms/spec/1.0/'); $collections = $path->query('//app:collection'); for ($i = 0; $i < $collections->length; $i++) { $collection = $collections->item($i); $url = $collection->getAttribute('href'); $takesEntries = false; $accepts = $path->query('app:accept', $collection); for ($j = 0; $j < $accepts->length; $j++) { $accept = $accepts->item($j); $acceptValue = $accept->nodeValue; if (preg_match('#application/atom\\+xml(;\\s*type=entry)?#', $acceptValue)) { $takesEntries = true; break; } } if (!$takesEntries) { continue; } $verbs = $path->query('activity:verb', $collection); if ($verbs->length == 0) { $this->_addCollection(ActivityVerb::POST, $url); } else { for ($k = 0; $k < $verbs->length; $k++) { $verb = $verbs->item($k); $this->_addCollection($verb->nodeValue, $url); } } } }
/** * Look up and if necessary create an Ostatus_profile for the remote entity * with the given profile page URL. This should never return null -- you * will either get an object or an exception will be thrown. * * @param string $profile_url * @return Ostatus_profile * @throws Exception on various error conditions * @throws OStatusShadowException if this reference would obscure a local user/group */ public static function updateProfileURL($profile_url, $hints = array()) { $oprofile = null; $hints['profileurl'] = $profile_url; // Fetch the URL // XXX: HTTP caching $client = new HTTPClient(); $client->setHeader('Accept', 'text/html,application/xhtml+xml'); $response = $client->get($profile_url); if (!$response->isOk()) { // TRANS: Exception. %s is a profile URL. throw new Exception(sprintf(_('Could not reach profile page %s.'), $profile_url)); } // Check if we have a non-canonical URL $finalUrl = $response->getUrl(); if ($finalUrl != $profile_url) { $hints['profileurl'] = $finalUrl; } // Try to get some hCard data $body = $response->getBody(); $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl); if (!empty($hcardHints)) { $hints = array_merge($hints, $hcardHints); } // Check if they've got an LRDD header $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml'); try { $xrd = new XML_XRD(); $xrd->loadFile($lrdd); $xrdHints = DiscoveryHints::fromXRD($xrd); $hints = array_merge($hints, $xrdHints); } catch (Exception $e) { // No hints available from XRD } // If discovery found a feedurl (probably from LRDD), use it. if (array_key_exists('feedurl', $hints)) { return self::ensureFeedURL($hints['feedurl'], $hints); } // Get the feed URL from HTML $discover = new FeedDiscovery(); $feedurl = $discover->discoverFromHTML($finalUrl, $body); if (!empty($feedurl)) { $hints['feedurl'] = $feedurl; return self::ensureFeedURL($feedurl, $hints); } // TRANS: Exception. %s is a URL. throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'), $finalUrl)); }
function getTweetHtml($url) { try { $client = new HTTPClient(); $response = $client->get($url); } catch (HTTP_Request2_Exception $e) { print "ERROR: HTTP response " . $e->getMessage() . "\n"; return false; } if (!$response->isOk()) { print "ERROR: HTTP response " . $response->getCode() . "\n"; return false; } $body = $response->getBody(); return tweetHtmlFromBody($body); }
protected function fetchUrl($url, $method = HTTPClient::METHOD_GET) { $client = new HTTPClient(); // GAAHHH, this method sucks! How about we make a better HTTPClient interface? switch ($method) { case HTTPClient::METHOD_GET: $response = $client->get($url); break; case HTTPClient::METHOD_HEAD: $response = $client->head($url); break; default: throw new Exception('Bad HTTP method.'); } if ($response->getStatus() != 200) { throw new Exception('Unexpected HTTP status code.'); } return $response; }
/** * @param string $url * @param bool $htmlOk pass false here if you don't want to follow web pages. * @return string with validated URL * @throws FeedSubBadURLException * @throws FeedSubBadHtmlException * @throws FeedSubNoFeedException * @throws FeedSubEmptyException * @throws FeedSubUnrecognizedTypeException */ function discoverFromURL($url, $htmlOk = true) { try { $client = new HTTPClient(); $response = $client->get($url); } catch (HTTP_Request2_Exception $e) { common_log(LOG_ERR, __METHOD__ . " Failure for {$url} - " . $e->getMessage()); throw new FeedSubBadURLException($e->getMessage()); } if ($htmlOk) { $type = $response->getHeader('Content-Type'); $isHtml = preg_match('!^(text/html|application/xhtml\\+xml)!i', $type); if ($isHtml) { $target = $this->discoverFromHTML($response->getUrl(), $response->getBody()); if (!$target) { throw new FeedSubNoFeedException($url); } return $this->discoverFromURL($target, false); } } return $this->initFromResponse($response); }
function pageCount() { $http = new HTTPClient(); $ret = $http->get($this->index_url . '/text/_count'); if ($ret !== false) { if (empty($this->json)) { $this->json = new Services_JSON(); } $json = $this->json->decode($ret); return $json->count; } return false; }
public static function sendRegistration($domain, $email, $access_key = '', $errors = '') { // Send data $link = SITEGUARDING_SERVER . '?action=register&type=json&data='; $data = array('domain' => $domain, 'email' => $email, 'access_key' => $access_key, 'errors' => $errors); $link .= base64_encode(json_encode($data)); //$msg = trim(file_get_contents($link)); include_once dirname(__FILE__) . '/HttpClient.class.php'; $HTTPClient = new HTTPClient(); $msg = $HTTPClient->get($link); if ($msg == '') { return true; } else { return $msg; } }
function setAvatar($user) { $picUrl = sprintf('http://graph.facebook.com/%s/picture?type=large', $this->fbuid); // fetch the picture from Facebook $client = new HTTPClient(); // fetch the actual picture $response = $client->get($picUrl); if ($response->isOk()) { $finalUrl = $client->getUrl(); // Make sure the filename is unique becuase it's possible for a user // to deauthorize our app, and then come back in as a new user but // have the same Facebook picture (avatar URLs have a unique index // and their URLs are based on the filenames). $filename = 'facebook-' . common_good_rand(4) . '-' . substr(strrchr($finalUrl, '/'), 1); $ok = file_put_contents(Avatar::path($filename), $response->getBody()); if (!$ok) { common_log(LOG_WARNING, sprintf('Couldn\'t save Facebook avatar %s', $tmp), __FILE__); } else { // save it as an avatar $profile = $user->getProfile(); if ($profile->setOriginal($filename)) { common_log(LOG_INFO, sprintf('Saved avatar for %s (%d) from Facebook picture for ' . '%s (fbuid %d), filename = %s', $user->nickname, $user->id, $this->fbuser['name'], $this->fbuid, $filename), __FILE__); } } } }
/** * Send a verification ping to subscriber, and if confirmed apply the changes. * This may create, update, or delete the database record. * * @param string $mode 'subscribe' or 'unsubscribe' * @param string $token hub.verify_token value, if provided by client * @throws ClientException on failure */ function verify($mode, $token = null) { assert($mode == 'subscribe' || $mode == 'unsubscribe'); $challenge = common_random_hexstr(32); $params = array('hub.mode' => $mode, 'hub.topic' => $this->topic, 'hub.challenge' => $challenge); if ($mode == 'subscribe') { $params['hub.lease_seconds'] = $this->lease; } if ($token !== null) { // TODO: deprecated in PuSH 0.4 $params['hub.verify_token'] = $token; // let's put it in there if remote uses PuSH <0.4 } // Any existing query string parameters must be preserved $url = $this->callback; if (strpos($url, '?') !== false) { $url .= '&'; } else { $url .= '?'; } $url .= http_build_query($params, '', '&'); $request = new HTTPClient(); $response = $request->get($url); $status = $response->getStatus(); if ($status >= 200 && $status < 300) { common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->topic}"); } else { // TRANS: Client exception. %s is a HTTP status code. throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'), $status)); } $old = HubSub::getByHashkey($this->topic, $this->callback); if ($mode == 'subscribe') { if ($old instanceof HubSub) { $this->update($old); } else { $ok = $this->insert(); } } else { if ($mode == 'unsubscribe') { if ($old instanceof HubSub) { $old->delete(); } else { // That's ok, we're already unsubscribed. } } } }
function setAvatar($user) { try { $picUrl = sprintf('http://graph.facebook.com/%d/picture?type=large', $this->fbuser->id); // fetch the picture from Facebook $client = new HTTPClient(); // fetch the actual picture $response = $client->get($picUrl); if ($response->isOk()) { // seems to always be jpeg, but not sure $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4); $ok = file_put_contents(Avatar::path($tmpname), $response->getBody()); if (!$ok) { common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__); } else { // save it as an avatar $imagefile = new ImageFile(null, Avatar::path($tmpname)); $filename = Avatar::filename($user->id, image_type_to_extension($imagefile->preferredType()), 180, common_timestamp()); // Previous docs said 180 is the "biggest img we get from Facebook" $imagefile->resizeTo(Avatar::path($filename, array('width' => 180, 'height' => 180))); // No need to keep the temporary file around... @unlink(Avatar::path($tmpname)); $profile = $user->getProfile(); if ($profile->setOriginal($filename)) { common_log(LOG_INFO, sprintf('Saved avatar for %s (%d) from Facebook picture for ' . '%s (fbuid %d), filename = %s', $user->nickname, $user->id, $this->fbuser->name, $this->fbuid, $filename), __FILE__); // clean up tmp file } } } } catch (Exception $e) { common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__); // error isn't fatal, continue } }
/** * Look up and if necessary create an Ostatus_profile for the remote entity * with the given profile page URL. This should never return null -- you * will either get an object or an exception will be thrown. * * @param string $profile_url * @return Ostatus_profile * @throws Exception on various error conditions * @throws OStatusShadowException if this reference would obscure a local user/group */ public static function ensureProfileURL($profile_url, $hints = array()) { $oprofile = self::getFromProfileURL($profile_url); if (!empty($oprofile)) { return $oprofile; } $hints['profileurl'] = $profile_url; // Fetch the URL // XXX: HTTP caching $client = new HTTPClient(); $client->setHeader('Accept', 'text/html,application/xhtml+xml'); $response = $client->get($profile_url); if (!$response->isOk()) { throw new Exception("Could not reach profile page: " . $profile_url); } // Check if we have a non-canonical URL $finalUrl = $response->getUrl(); if ($finalUrl != $profile_url) { $hints['profileurl'] = $finalUrl; $oprofile = self::getFromProfileURL($finalUrl); if (!empty($oprofile)) { return $oprofile; } } // Try to get some hCard data $body = $response->getBody(); $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl); if (!empty($hcardHints)) { $hints = array_merge($hints, $hcardHints); } // Check if they've got an LRDD header $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml'); if (!empty($lrdd)) { $xrd = Discovery::fetchXrd($lrdd); $xrdHints = DiscoveryHints::fromXRD($xrd); $hints = array_merge($hints, $xrdHints); } // If discovery found a feedurl (probably from LRDD), use it. if (array_key_exists('feedurl', $hints)) { return self::ensureFeedURL($hints['feedurl'], $hints); } // Get the feed URL from HTML $discover = new FeedDiscovery(); $feedurl = $discover->discoverFromHTML($finalUrl, $body); if (!empty($feedurl)) { $hints['feedurl'] = $feedurl; return self::ensureFeedURL($feedurl, $hints); } throw new Exception("Could not find a feed URL for profile page " . $finalUrl); }
/** * Quick static function to GET a URL */ public static function quickGet($url, $accept = null) { $client = new HTTPClient(); if (!is_null($accept)) { $client->setHeader('Accept', $accept); } $response = $client->get($url); if (!$response->isOk()) { // TRANS: Exception. %s is a profile URL. throw new Exception(sprintf(_m('Could not GET URL %s.'), $url), $response->getStatus()); } return $response->getBody(); }
/** * Quick static function to GET a URL */ public static function quickGet($url, $accept = null, $params = array()) { if (!empty($params)) { $params = http_build_query($params, null, '&'); if (strpos($url, '?') === false) { $url .= '?' . $params; } else { $url .= '&' . $params; } } $client = new HTTPClient(); if (!is_null($accept)) { $client->setHeader('Accept', $accept); } $response = $client->get($url); if (!$response->isOk()) { // TRANS: Exception. %s is a profile URL. throw new Exception(sprintf(_m('Could not GET URL %s.'), $url), $response->getStatus()); } return $response->getBody(); }
function step2() { global $DOWNLOAD; global $INSTALL_DIR; global $TGZ; say('Downloading <a href="' . $DOWNLOAD . '">DokuWiki archive</a>...'); @set_time_limit(120); @ignore_user_abort(); $http = new HTTPClient(); $http->timeout = 120; $data = $http->get($DOWNLOAD); if (!$data) { say($http->error); say("Download failed. Try to upload {$TGZ} yourself."); html_footer(); } $fp = @fopen($TGZ, "w"); if (!$fp) { say("Failed to save {$TGZ}. Try to upload it yourself."); html_footer(); } fwrite($fp, $data); fclose($fp); unset($data); say("<p>Download completed successfully. Please continue to next step</p>\n <form method=\"get\" action=\"\">\n <input type=\"hidden\" name=\"go\" value=\"3\" />\n <input type=\"submit\" value=\"Okay, proceed to file extraction\" />\n </form>"); html_footer(); }
/** * Send a verification ping to subscriber, and if confirmed apply the changes. * This may create, update, or delete the database record. * * @param string $mode 'subscribe' or 'unsubscribe' * @param string $token hub.verify_token value, if provided by client * @throws ClientException on failure */ function verify($mode, $token = null) { assert($mode == 'subscribe' || $mode == 'unsubscribe'); $challenge = common_good_rand(32); $params = array('hub.mode' => $mode, 'hub.topic' => $this->topic, 'hub.challenge' => $challenge); if ($mode == 'subscribe') { $params['hub.lease_seconds'] = $this->lease; } if ($token !== null) { $params['hub.verify_token'] = $token; } // Any existing query string parameters must be preserved $url = $this->callback; if (strpos($url, '?') !== false) { $url .= '&'; } else { $url .= '?'; } $url .= http_build_query($params, '', '&'); $request = new HTTPClient(); $response = $request->get($url); $status = $response->getStatus(); if ($status >= 200 && $status < 300) { common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->topic}"); } else { throw new ClientException("Hub subscriber verification returned HTTP {$status}"); } $old = HubSub::staticGet($this->topic, $this->callback); if ($mode == 'subscribe') { if ($old) { $this->update($old); } else { $ok = $this->insert(); } } else { if ($mode == 'unsubscribe') { if ($old) { $old->delete(); } else { // That's ok, we're already unsubscribed. } } } }
/** * Get profile from external instance * * @return null or profile object */ function getProfileFromExternalInstance($instance_url, $user_id_or_nickname) { $apicall = $instance_url . '/api/users/show.json?id=' . $user_id_or_nickname; $client = new HTTPClient(); $response = $client->get($apicall); // json_decode returns null if it fails to decode return $response->isOk() ? json_decode($response->getBody()) : null; }
/** * @group internet */ function test_chunked() { $http = new HTTPClient(); $data = $http->get('http://whoopdedo.org/cgi-bin/chunked/2550'); $this->assertFalse($data === false, 'HTTP response'); $this->assertEquals(2550, strlen($data)); }
function getFacebookUser($id) { $key = Cache::key(sprintf("FacebookBridgePlugin:userdata:%s", $id)); $c = Cache::instance(); if ($c) { $obj = $c->get($key); if ($obj) { return $obj; } } $url = sprintf("https://graph.facebook.com/%s", $id); $client = new HTTPClient(); $resp = $client->get($url); if (!$resp->isOK()) { return null; } $user = json_decode($resp->getBody()); if ($user->error) { return null; } if ($c) { $c->set($key, $user); } return $user; }
/** * Given a user ID, return the first available resource descriptor * * @param string $id User ID URI * * @return XML_XRD object for the resource descriptor of the id */ public function lookup($id) { // Normalize the incoming $id to make sure we have a uri $uri = self::normalize($id); foreach ($this->methods as $class) { try { $xrd = new XML_XRD(); common_debug("LRDD discovery method for '{$uri}': {$class}"); $lrdd = new $class(); $links = call_user_func(array($lrdd, 'discover'), $uri); $link = Discovery::getService($links, Discovery::LRDD_REL); // Load the LRDD XRD if (!empty($link->template)) { $xrd_uri = Discovery::applyTemplate($link->template, $uri); } elseif (!empty($link->href)) { $xrd_uri = $link->href; } else { throw new Exception('No resource descriptor URI in link.'); } $client = new HTTPClient(); $headers = array(); if (!is_null($link->type)) { $headers[] = "Accept: {$link->type}"; } $response = $client->get($xrd_uri, $headers); if ($response->getStatus() != 200) { throw new Exception('Unexpected HTTP status code.'); } $xrd->loadString($response->getBody()); return $xrd; } catch (Exception $e) { continue; } } // TRANS: Exception. %s is an ID. throw new Exception(sprintf(_('Unable to find services for %s.'), $id)); }
public function discover($uri) { try { $client = new HTTPClient(); $response = $client->get($uri); } catch (HTTP_Request2_Exception $e) { return false; } if ($response->getStatus() != 200) { return false; } return Discovery_LRDD_Link_HTML::parse($response->getBody()); }
function setAvatar($user) { try { $picUrl = sprintf('http://graph.facebook.com/%d/picture?type=large', $this->fbuser->id); // fetch the picture from Facebook $client = new HTTPClient(); // fetch the actual picture $response = $client->get($picUrl); if ($response->isOk()) { // seems to always be jpeg, but not sure $tmpname = "facebook-avatar-tmp-" . common_good_rand(4); $ok = file_put_contents(Avatar::path($tmpname), $response->getBody()); if (!$ok) { common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__); } else { // save it as an avatar $file = new ImageFile($user->id, Avatar::path($tmpname)); $filename = $file->resize(180); // size of the biggest img we get from Facebook $profile = $user->getProfile(); if ($profile->setOriginal($filename)) { common_log(LOG_INFO, sprintf('Saved avatar for %s (%d) from Facebook picture for ' . '%s (fbuid %d), filename = %s', $user->nickname, $user->id, $this->fbuser->name, $this->fbuid, $filename), __FILE__); // clean up tmp file @unlink(Avatar::path($tmpname)); } } } } catch (Exception $e) { common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__); // error isn't fatal, continue } }
function formatLink($match) { global $CONF; $url = $match[1]; str_replace("\\\\'", "'", $url); // resolve short url if ($CONF['longurl']) { $http = new HTTPClient(); $xml = $http->get('http://api.longurl.org/v2/expand?format=php&url=' . urlencode($url)); if ($xml != false) { $xml = unserialize($xml); $long = $xml['long-url']; } } if (!$long) { $long = $url; } $link = '<a href="' . $url . '" title="' . $long . '">' . $url . '</a>'; return $link; }