예제 #1
0
파일: salmon.php 프로젝트: Grasia/bolotweet
 /**
  * Sign and post the given Atom entry as a Salmon message.
  *
  * Side effects: may generate a keypair on-demand for the given user,
  * which can be very slow on some systems.
  *
  * @param string $endpoint_uri
  * @param string $xml string representation of payload
  * @param Profile $actor local user profile whose keys to sign with
  * @return boolean success
  */
 public function post($endpoint_uri, $xml, $actor)
 {
     if (empty($endpoint_uri)) {
         return false;
     }
     foreach ($this->formatClasses() as $class) {
         try {
             $envelope = $this->createMagicEnv($xml, $actor, $class);
         } catch (Exception $e) {
             common_log(LOG_ERR, "Salmon unable to sign: " . $e->getMessage());
             return false;
         }
         $headers = array('Content-Type: application/magic-envelope+xml');
         try {
             $client = new HTTPClient();
             $client->setBody($envelope);
             $response = $client->post($endpoint_uri, $headers);
         } catch (HTTP_Request2_Exception $e) {
             common_log(LOG_ERR, "Salmon ({$class}) post to {$endpoint_uri} failed: " . $e->getMessage());
             continue;
         }
         if ($response->getStatus() != 200) {
             common_log(LOG_ERR, "Salmon ({$class}) at {$endpoint_uri} returned status " . $response->getStatus() . ': ' . $response->getBody());
             continue;
         }
         // Success!
         return true;
     }
     return false;
 }
 function handle_start(&$event, $param)
 {
     if (!isset($_FILES['imageshack_file'])) {
         return;
     }
     if ($_FILES['imageshack_file']['error'] || !is_uploaded_file($_FILES['imageshack_file']['tmp_name'])) {
         msg(sprintf('The was a problem receiving the file from you (error %d)', $_FILES['imageshack_file']['error']), -1);
         return;
     }
     require_once DOKU_INC . '/inc/HTTPClient.php';
     $http = new HTTPClient();
     $http->timeout = 60;
     $http->headers['Content-Type'] = 'multipart/form-data';
     $data = array('xml' => 'yes', 'fileupload' => array('filename' => $_FILES['imageshack_file']['name'], 'mimetype' => $_FILES['imageshack_file']['type'], 'body' => file_get_contents($_FILES['imageshack_file']['tmp_name'])));
     $xml = $http->post('http://imageshack.us/index.php', $data);
     if (!$xml) {
         msg('There was a problem with uploading your file to imageshack: ' . $http->error, -1);
         return;
     }
     $xml = new SimpleXMLElement($xml);
     if (!$xml) {
         msg('ImageShack did not accept your upload', -1);
         return;
     }
     list($w, $h) = explode('x', (string) $xml->resolution[0]);
     $_SESSION['imageshack'][] = array('link' => (string) $xml->image_link[0], 'adlink' => (string) $xml->ad_link[0], 'name' => (string) $xml->image_name[0], 'width' => $w, 'height' => $h, 'size' => (string) $xml->filesize[0]);
 }
예제 #3
0
 /**
  * Set up an HTTPClient with auth for our resource.
  *
  * @param string $method
  * @return HTTPClient
  */
 private function httpClient($method = 'GET')
 {
     $client = new HTTPClient($this->url);
     $client->setMethod($method);
     $client->setAuth($this->user, $this->pass);
     return $client;
 }
예제 #4
0
 function onStartNoticeSave($notice)
 {
     $args = $this->testArgs($notice);
     common_debug("Blogspamnet args = " . print_r($args, TRUE));
     $requestBody = xmlrpc_encode_request('testComment', array($args));
     $request = new HTTPClient($this->baseUrl, HTTPClient::METHOD_POST);
     $request->setHeader('Content-Type', 'text/xml');
     $request->setBody($requestBody);
     $httpResponse = $request->send();
     $response = xmlrpc_decode($httpResponse->getBody());
     if (xmlrpc_is_fault($response)) {
         throw new ServerException("{$response['faultString']} ({$response['faultCode']})", 500);
     } else {
         common_debug("Blogspamnet results = " . $response);
         if (preg_match('/^ERROR(:(.*))?$/', $response, $match)) {
             throw new ServerException(sprintf(_("Error from %s: %s"), $this->baseUrl, $match[2]), 500);
         } else {
             if (preg_match('/^SPAM(:(.*))?$/', $response, $match)) {
                 throw new ClientException(sprintf(_("Spam checker results: %s"), $match[2]), 400);
             } else {
                 if (preg_match('/^OK$/', $response)) {
                     // don't do anything
                 } else {
                     throw new ServerException(sprintf(_("Unexpected response from %s: %s"), $this->baseUrl, $response), 500);
                 }
             }
         }
     }
     return true;
 }
 function extract_posts($arg_url)
 {
     $httpclient = new HTTPClient();
     $json_data = $httpclient->send($arg_url, 'get');
     if (empty($json_data)) {
         $this->message = 'Empty content returned';
         return false;
     }
     // convert json to php array
     $array_data = json_decode($json_data, true);
     // get data
     $facebook_posts = $array_data['data'];
     if (count($facebook_posts) > 0) {
         foreach ($facebook_posts as $facebook_post) {
             $post_content = $facebook_post['message'];
             $post_title = $facebook_post['name'];
             $post_author = $this->author_id;
             $post_status = $this->status_id;
             $post_date_gmt = gmdate('Y-m-d H:i:s', strtotime($facebook_post['created_time']));
             $post_date = get_date_from_gmt($post_date_gmt);
             $facebook_id = $facebook_post['id'];
             // build the post array
             $this->posts[] = compact('post_content', 'post_title', 'post_author', 'post_status', 'post_date', 'post_date_gmt', 'facebook_id');
         }
         // end of foreach
     }
     // end of if
     return true;
 }
예제 #6
0
파일: tests.php 프로젝트: jasherai/libwebta
 function testNET_HTTP_HTTPClient()
 {
     $robot = new HTTPClient();
     // connect to url
     $res = $robot->Fetch("http://webta.net");
     $this->assertTrue($res, "Can't fetch url");
     /* end of tests */
 }
 function testPostRequestIsUnsuccessful()
 {
     \VCR\VCR::insertCassette('gathercontent_post_projects_failure.yml');
     $subject = new HTTPClient('*****@*****.**', 'bogus-api-key');
     $response = $subject->post('https://api.gathercontent.com/projects', ['account_id' => '20225', 'name' => 'Project Name'], ['Accept: application/vnd.gathercontent.v0.5+json']);
     $this->assertNotEquals(200, $response->status);
     $this->assertEquals('Invalid credentials.', $response->body);
 }
예제 #8
0
 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);
 }
예제 #9
0
 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());
 }
예제 #10
0
 function load_page($URL, $ispost = false, $postparams = "")
 {
     //echo "LOAAAAAAAAAAAAADING $URL<br /><br />";
     $return = false;
     $snoopy = new HTTPClient();
     if ($snoopy->loadPage($URL)) {
         $return = $snoopy->getData();
     }
     unset($snoopy);
     return $return;
 }
예제 #11
0
파일: tests.php 프로젝트: rchicoria/epp-drs
 function testData_XML_RSS_RSSReader()
 {
     $http = new HTTPClient();
     // rss 2.0
     $url = 'http://aggressiva.livejournal.com/data/rss';
     $http->SetTimeouts(30, 15);
     $xml = $http->Fetch($url);
     $Reader = new RSSReader();
     $Reader->Parse($xml);
     $data = $Reader->GetData();
     $this->assertTrue($data['channel'], "No channel found");
     $this->assertTrue($data['item']['pubdate'], "No items found");
 }
 /**
  * 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));
 }
예제 #13
0
 function onStartShowSections($action)
 {
     $name = $action->trimmed('action');
     if ($name == 'tag') {
         $taginput = $action->trimmed('tag');
         $tag = common_canonical_tag($taginput);
         if (!empty($tag)) {
             $url = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=render', urlencode($tag));
             $editurl = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=edit', urlencode($tag));
             $request = HTTPClient::start();
             $response = $request->get($url);
             $html = $response->getBody();
             $action->elementStart('div', array('id' => 'wikihashtags', 'class' => 'section'));
             if ($response->isOk() && !empty($html)) {
                 $action->element('style', null, "span.editsection { display: none }\n" . "table.toc { display: none }");
                 $action->raw($html);
                 $action->elementStart('p');
                 $action->element('a', array('href' => $editurl, 'title' => sprintf(_m('Edit the article for #%s on WikiHashtags'), $tag)), _m('Edit'));
                 $action->element('a', array('href' => 'http://www.gnu.org/copyleft/fdl.html', 'title' => _m('Shared under the terms of the GNU Free Documentation License'), 'rel' => 'license'), _m('GNU FDL'));
                 $action->elementEnd('p');
             } else {
                 $action->element('a', array('href' => $editurl), sprintf(_m('Start the article for #%s on WikiHashtags'), $tag));
             }
             $action->elementEnd('div');
         }
     }
     return true;
 }
예제 #14
0
function linkback_get_target($target)
{
    // Resolve target (https://github.com/converspace/webmention/issues/43)
    $request = HTTPClient::start();
    try {
        $response = $request->head($target);
    } catch (Exception $ex) {
        return NULL;
    }
    try {
        $notice = Notice::fromUri($response->getEffectiveUrl());
    } catch (UnknownUriException $ex) {
        preg_match('/\\/notice\\/(\\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
        $notice = Notice::getKV('id', $match[1]);
    }
    if ($notice instanceof Notice && $notice->isLocal()) {
        return $notice;
    } else {
        $user = User::getKV('uri', $response->getEffectiveUrl());
        if (!$user) {
            preg_match('/\\/user\\/(\\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
            $user = User::getKV('id', $match[1]);
        }
        if (!$user) {
            preg_match('/\\/([^\\/\\?#]+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
            if (linkback_lenient_target_match(common_profile_url($match[1]), $response->getEffectiveUrl())) {
                $user = User::getKV('nickname', $match[1]);
            }
        }
        if ($user instanceof User) {
            return $user;
        }
    }
    return NULL;
}
예제 #15
0
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);
}
예제 #16
0
function httpRequest($endpoint, $poststr)
{
    $request = HTTPClient::start();
    $request->setConfig(array('follow_redirects' => true, 'connect_timeout' => 120, 'timeout' => 120, 'ssl_verify_peer' => false, 'ssl_verify_host' => false));
    // Turn signed request query string back into an array
    parse_str($poststr, $postdata);
    return $request->post($endpoint, null, $postdata);
}
예제 #17
0
 /**
  * RPC Client Constructor
  * 
  * @param string hostname
  * @param string xml rpc username (optional)
  * @param string xml rpc password (optional)
  */
 function __construct($host, $user = "", $pass = "")
 {
     parent::__construct();
     $host = str_replace("http://", "", $host);
     if ($user) {
         $host = "{$user}:{$pass}@{$host}";
     }
     $this->Host = "http://{$host}";
 }
예제 #18
0
		function __construct($accountid, $curl = null)
		{
			parent::__construct($curl);
			
			$ProfileURL = sprintf(self::PROFILE_URL_TEMPLATE, $accountid);

			$this->Fetch($ProfileURL);
			$this->AccountID = $accountid;
		}
예제 #19
0
 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;
 }
예제 #20
0
파일: ping.php 프로젝트: Br3nda/StatusNet
function ping_broadcast_notice($notice)
{
    if ($notice->is_local != Notice::LOCAL_PUBLIC && $notice->is_local != Notice::LOCAL_NONPUBLIC) {
        return true;
    }
    # Array of servers, URL => type
    $notify = common_config('ping', 'notify');
    $profile = $notice->getProfile();
    $tags = ping_notice_tags($notice);
    foreach ($notify as $notify_url => $type) {
        switch ($type) {
            case 'xmlrpc':
            case 'extended':
                $req = xmlrpc_encode_request('weblogUpdates.ping', array($profile->nickname, common_local_url('showstream', array('nickname' => $profile->nickname)), common_local_url('shownotice', array('notice' => $notice->id)), common_local_url('userrss', array('nickname' => $profile->nickname)), $tags));
                $request = HTTPClient::start();
                $request->setConfig('connect_timeout', common_config('ping', 'timeout'));
                $request->setConfig('timeout', common_config('ping', 'timeout'));
                try {
                    $httpResponse = $request->post($notify_url, array('Content-Type: text/xml'), $req);
                } catch (Exception $e) {
                    common_log(LOG_ERR, "Exception pinging {$notify_url}: " . $e->getMessage());
                    continue;
                }
                if (!$httpResponse || mb_strlen($httpResponse->getBody()) == 0) {
                    common_log(LOG_WARNING, "XML-RPC empty results for ping ({$notify_url}, {$notice->id}) ");
                    continue;
                }
                $response = xmlrpc_decode($httpResponse->getBody());
                if (is_array($response) && xmlrpc_is_fault($response)) {
                    common_log(LOG_WARNING, "XML-RPC error for ping ({$notify_url}, {$notice->id}) " . "{$response['faultString']} ({$response['faultCode']})");
                } else {
                    common_log(LOG_INFO, "Ping success for {$notify_url} {$notice->id}");
                }
                break;
            case 'get':
            case 'post':
                $args = array('name' => $profile->nickname, 'url' => common_local_url('showstream', array('nickname' => $profile->nickname)), 'changesURL' => common_local_url('userrss', array('nickname' => $profile->nickname)));
                $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
                if ($type === 'get') {
                    $result = $fetcher->get($notify_url . '?' . http_build_query($args), array('User-Agent: StatusNet/' . STATUSNET_VERSION));
                } else {
                    $result = $fetcher->post($notify_url, http_build_query($args), array('User-Agent: StatusNet/' . STATUSNET_VERSION));
                }
                if ($result->status != '200') {
                    common_log(LOG_WARNING, "Ping error for '{$notify_url}' ({$notice->id}): " . "{$result->body}");
                } else {
                    common_log(LOG_INFO, "Ping success for '{$notify_url}' ({$notice->id}): " . "'{$result->body}'");
                }
                break;
            default:
                common_log(LOG_WARNING, 'Unknown notify type for ' . $notify_url . ': ' . $type);
        }
    }
    return true;
}
예제 #21
0
		/**
		 * Constructor
		 * 
		 * @var int account ID
		 * @var resource CURL handler
		 */
		function __construct($accountid, $curl = null)
		{
			parent::__construct($curl);
			
			$ProfileURL = sprintf(self::PROFILE_URL_TEMPLATE, $accountid);
			
			$this->SetHeaders(array('Accept-Language: en-us,en;q=0.5'));
			
			$this->SetTimeouts(60, 30);
			$this->Fetch($ProfileURL);
			$this->AccountID = $accountid;
		}
예제 #22
0
 /**
  * Constructor.
  *
  * @author Andreas Gohr <*****@*****.**>
  */
 function __construct()
 {
     global $conf;
     // call parent constructor
     parent::__construct();
     // set some values from the config
     $this->proxy_host = $conf['proxy']['host'];
     $this->proxy_port = $conf['proxy']['port'];
     $this->proxy_user = $conf['proxy']['user'];
     $this->proxy_pass = $conf['proxy']['pass'];
     $this->proxy_ssl = $conf['proxy']['ssl'];
 }
 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media = null)
 {
     // If we are on a private node, we won't do any remote calls (just as a precaution until
     // we can configure this from config.php for the private nodes)
     if (common_config('site', 'private')) {
         return true;
     }
     if ($media !== 'image') {
         return true;
     }
     // If there is a local filename, it is either a local file already or has already been downloaded.
     if (!empty($file->filename)) {
         return true;
     }
     $this->checkWhitelist($file->getUrl());
     // First we download the file to memory and test whether it's actually an image file
     $imgData = HTTPClient::quickGet($file->getUrl());
     common_debug(sprintf('Downloading remote file id==%u with URL: %s', $file->id, $file->getUrl()));
     $info = @getimagesizefromstring($imgData);
     if ($info === false) {
         throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $file->getUrl());
     } elseif (!$info[0] || !$info[1]) {
         throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
     }
     $filehash = hash(File::FILEHASH_ALG, $imgData);
     try {
         // Exception will be thrown before $file is set to anything, so old $file value will be kept
         $file = File::getByHash($filehash);
         //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
     } catch (NoResultException $e) {
         $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
         $fullpath = File::path($filename);
         // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
             throw new ServerException(_('Could not write downloaded file to disk.'));
         }
         // Updated our database for the file record
         $orig = clone $file;
         $file->filehash = $filehash;
         $file->filename = $filename;
         $file->width = $info[0];
         // array indexes documented on php.net:
         $file->height = $info[1];
         // https://php.net/manual/en/function.getimagesize.php
         // Throws exception on failure.
         $file->updateWithKeys($orig, 'id');
     }
     // Get rid of the file from memory
     unset($imgData);
     $imgPath = $file->getPath();
     return false;
 }
예제 #24
0
function doSpotifyLookup($uri, $isArtist)
{
    $request = HTTPClient::start();
    $response = $request->get('http://ws.spotify.com/lookup/1/?uri=' . $uri);
    if ($response->isOk()) {
        $xml = simplexml_load_string($response->getBody());
        if ($isArtist) {
            return $xml->name;
        } else {
            return $xml->artist->name . ' - ' . $xml->name;
        }
    }
}
예제 #25
0
 /**
  * Wraps an event around the parent function
  *
  * @triggers HTTPCLIENT_REQUEST_SEND
  * @author   Andreas Gohr <*****@*****.**>
  */
 function sendRequest($url, $data = '', $method = 'GET')
 {
     $httpdata = array('url' => $url, 'data' => $data, 'method' => $method);
     $evt = new Doku_Event('HTTPCLIENT_REQUEST_SEND', $httpdata);
     if ($evt->advise_before()) {
         $url = $httpdata['url'];
         $data = $httpdata['data'];
         $method = $httpdata['method'];
     }
     $evt->advise_after();
     unset($evt);
     return parent::sendRequest($url, $data, $method);
 }
예제 #26
0
 /**
  * Sign and post the given Atom entry as a Salmon message.
  *
  * Side effects: may generate a keypair on-demand for the given user,
  * which can be very slow on some systems (like those without php5-gmp).
  *
  * @param string $endpoint_uri
  * @param string $xml string representation of payload
  * @param User $user local user profile whose keys we sign with
  * @return boolean success
  */
 public static function post($endpoint_uri, $xml, User $user)
 {
     if (empty($endpoint_uri)) {
         common_debug('No endpoint URI for Salmon post to ' . $user->getUri());
         return false;
     }
     try {
         $magic_env = MagicEnvelope::signAsUser($xml, $user);
         $envxml = $magic_env->toXML();
     } catch (Exception $e) {
         common_log(LOG_ERR, "Salmon unable to sign: " . $e->getMessage());
         return false;
     }
     $headers = array('Content-Type: application/magic-envelope+xml');
     try {
         $client = new HTTPClient();
         $client->setBody($envxml);
         $response = $client->post($endpoint_uri, $headers);
     } catch (HTTP_Request2_Exception $e) {
         common_log(LOG_ERR, "Salmon post to {$endpoint_uri} failed: " . $e->getMessage());
         return false;
     }
     // Diaspora wants a slightly different formatting on the POST (other Content-type, so body needs "xml=")
     if ($response->getStatus() === 422) {
         common_debug(sprintf('Salmon (from profile %d) endpoint %s returned status %s. Diaspora? Will try again! Body: %s', $user->id, $endpoint_uri, $response->getStatus(), $response->getBody()));
         $headers = array('Content-Type: application/x-www-form-urlencoded');
         $client->setBody('xml=' . Magicsig::base64_url_encode($envxml));
         $response = $client->post($endpoint_uri, $headers);
     }
     // 200 OK is the best response
     // 202 Accepted is what we get from Diaspora for example
     if (!in_array($response->getStatus(), array(200, 202))) {
         common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s', $user->id, $endpoint_uri, $response->getStatus(), $response->getBody()));
         return false;
     }
     // Success!
     return true;
 }
예제 #27
0
 /**
  * Retries sending the request multiple times
  *
  * @param string $url
  * @param string $data
  * @param string $method
  * @return bool
  */
 function sendRequest($url, $data = '', $method = 'GET')
 {
     $this->tries = 2;
     // configures the number of retries
     $return = false;
     while ($this->tries) {
         $return = parent::sendRequest($url, $data, $method);
         if ($this->status != -100) {
             break;
         }
         $this->tries--;
     }
     return $return;
 }
예제 #28
0
 function onStartNoticeSave($notice)
 {
     $args = $this->testArgs($notice);
     common_debug("Blogspamnet args = " . print_r($args, TRUE));
     $requestBody = xmlrpc_encode_request('testComment', array($args));
     $request = new HTTPClient($this->baseUrl, HTTPClient::METHOD_POST);
     $request->setHeader('Content-Type', 'text/xml');
     $request->setBody($requestBody);
     $httpResponse = $request->send();
     $response = xmlrpc_decode($httpResponse->getBody());
     if (xmlrpc_is_fault($response)) {
         throw new ServerException("{$response['faultString']} ({$response['faultCode']})", 500);
     } else {
         common_debug("Blogspamnet results = " . $response);
         if (preg_match('/^ERROR(:(.*))?$/', $response, $match)) {
             // TRANS: Server exception thrown when blogspam.net returns error status.
             // TRANS: %1$s is the base URL, %2$s is the error (unknown contents; no period).
             throw new ServerException(sprintf(_m('Error from %1$s: %2$s'), $this->baseUrl, $match[2]), 500);
         } else {
             if (preg_match('/^SPAM(:(.*))?$/', $response, $match)) {
                 // TRANS: Server exception thrown when blogspam.net returns spam status.
                 // TRANS: Does not end with period because of unknown contents for %s (spam match).
                 throw new ClientException(sprintf(_m('Spam checker results: %s'), $match[2]), 400);
             } else {
                 if (preg_match('/^OK$/', $response)) {
                     // don't do anything
                 } else {
                     // TRANS: Server exception thrown when blogspam.net returns an unexpected status.
                     // TRANS: %1$s is the base URL, %2$s is the response (unknown contents; no period).
                     throw new ServerException(sprintf(_m('Unexpected response from %1$s: %2$s'), $this->baseUrl, $response), 500);
                 }
             }
         }
     }
     return true;
 }
예제 #29
0
function mention_url_representative_hcard($url, $fn = null, $mf2 = null)
{
    if (!$mf2) {
        $request = HTTPClient::start();
        try {
            $response = $request->get($url);
        } catch (Exception $ex) {
            return null;
        }
        $url = $response->getEffectiveUrl();
        $mf2 = new Mf2\Parser($response->getBody(), $url);
        $mf2 = $mf2->parse();
    }
    $hcard = null;
    if (!empty($mf2['items'])) {
        $hcards = array();
        foreach ($mf2['items'] as $item) {
            if (!in_array('h-card', $item['type'])) {
                continue;
            }
            // We found a match, return it immediately
            if (isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
                $hcard = $item['properties'];
                break;
            }
            // Let's keep all the hcards for later, to return one of them at least
            $hcards[] = $item['properties'];
        }
        // No match immediately for the url we expected, but there were h-cards found
        if (count($hcards) > 0) {
            $hcard = $hcards[0];
        }
    }
    if (!$hcard && $fn) {
        $hcard = array('name' => array($fn));
    }
    if (!$hcard && $response) {
        preg_match('/<title>([^<]+)/', $response->getBody(), $match);
        $hcard = array('name' => array($match[1]));
    }
    if ($hcard && !$hcard['url']) {
        $hcard['url'] = array($url);
    }
    return $hcard;
}
예제 #30
0
 /**
  * Constructor.
  * @return void
  */
 public function init()
 {
     $req = $this;
     $job = $this->job = new ComplexJob(function () use($req) {
         // called when job is done
         $req->wakeup();
         // wake up the request immediately
     });
     $job('request', function ($name, $job) {
         // registering job named 'showvar'
         $httpclient = HTTPClient::getInstance();
         $cb = function ($conn, $success) use($name, $job) {
             $job->setResult($name, $conn->body);
         };
         //$httpclient->get(['http://phpdaemon.net/Example/', 'foo' => 'bar'], $cb);
         $httpclient->post(['http://phpdaemon.net/Example/', 'foo' => 'bar'], ['postField' => 'value'], $cb);
     });
     $job();
     // let the fun begin
     $this->sleep(5, true);
     // setting timeout
 }