getHTTPFetcher() static public method

If Auth_Yadis_CURL_OVERRIDE is defined, this method will always return a {@link Auth_Yadis_PlainHTTPFetcher}.
static public getHTTPFetcher ( $timeout = 20 )
Example #1
0
 function setUp()
 {
     $this->proxy_url = 'http://xri.example.com/';
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->proxy = new Auth_Yadis_ProxyResolver($fetcher, $this->proxy_url);
     $this->servicetype = 'xri://+i-service*(+forwarding)*($v*1.0)';
     $this->servicetype_enc = 'xri%3A%2F%2F%2Bi-service%2A%28%2Bforwarding%29%2A%28%24v%2A1.0%29';
 }
Example #2
0
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;
}
Example #3
0
/**
 * Function for performaing email addresss to ID translation.
 */
function Auth_Yadis_Email_getID($email, $site_name = '')
{
    list($user, $domain) = split('@', $email, 2);
    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    $services = Auth_Yadis_Email_getServices('http://' . $domain, $fetcher);
    if (empty($services)) {
        $services = Auth_Yadis_Email_getServices('http://www.' . $domain, $fetcher);
        if (empty($services)) {
            $services = Auth_Yadis_Email_getServices(Auth_Yadis_Default_Email_Mapper, $fetcher);
        }
    }
    return Auth_Yadis_Email_resolve($services, $email);
}
Example #4
0
function ping_broadcast_notice($notice)
{
    if (!$notice->is_local) {
        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));
                $context = stream_context_create(array('http' => array('method' => "POST", 'header' => "Content-Type: text/xml\r\n" . "User-Agent: Laconica/" . LACONICA_VERSION . "\r\n", 'content' => $req)));
                $file = file_get_contents($notify_url, false, $context);
                if ($file === false || mb_strlen($file) == 0) {
                    common_log(LOG_WARNING, "XML-RPC empty results for ping ({$notify_url}, {$notice->id}) ");
                    continue;
                }
                $response = xmlrpc_decode($file);
                if (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: Laconica/' . LACONICA_VERSION));
                } else {
                    $result = $fetcher->post($notify_url, http_build_query($args), array('User-Agent: Laconica/' . LACONICA_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;
}
Example #5
0
 function runTest()
 {
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $y = Auth_Yadis_Yadis::discover($this->input_url, $fetcher);
     $this->assertTrue($y !== null);
     // Compare parts of returned Yadis object to expected URLs.
     $this->assertEquals($this->redir_uri, $y->normalized_uri, "tried {$this->input_url}");
     if ($this->xrds_uri) {
         $this->assertEquals($this->xrds_uri, $y->xrds_uri);
         // Compare contents of actual HTTP GET with that of Yadis
         // response.
         $f = Auth_Yadis_Yadis::getHTTPFetcher();
         $http_response = $f->get($this->xrds_uri);
         $this->assertEquals($http_response->body, $y->response_text);
     } else {
         $this->assertTrue($y->xrds_uri === null);
     }
 }
 /**
  * Constructor for OMB_Service_Consumer
  *
  * Initializes an OMB_Service_Consumer object representing the OMB service
  * specified by $service_url. Performs a complete service discovery using
  * Yadis.
  * Throws OMB_UnsupportedServiceException if XRDS file does not specify a
  * complete OMB service.
  *
  * @param string        $service_url  The URL of the service
  * @param string        $consumer_url An URL representing the consumer
  * @param OMB_Datastore $datastore    An instance of a class implementing
  *                                    OMB_Datastore
  *
  * @access public
  **/
 public function __construct($service_url, $consumer_url, $datastore)
 {
     $this->url = $service_url;
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->datastore = $datastore;
     $this->oauth_consumer = new OAuthConsumer($consumer_url, '');
     $xrds = OMB_Yadis_XRDS::fromYadisURL($service_url, $this->fetcher);
     /* Detect our services. This performs a validation as well, since
        getService und getXRD throw exceptions on failure. */
     $this->services = array();
     foreach (array(OAUTH_DISCOVERY => OMB_Helper::$OAUTH_SERVICES, OMB_VERSION => OMB_Helper::$OMB_SERVICES) as $service_root => $targetservices) {
         $uris = $xrds->getService($service_root)->getURIs();
         $xrd = $xrds->getXRD($uris[0]);
         foreach ($targetservices as $targetservice) {
             $yadis_service = $xrd->getService($targetservice);
             if ($targetservice == OAUTH_ENDPOINT_REQUEST) {
                 $localid = $yadis_service->getElements('xrd:LocalID');
                 $this->listener_uri = $yadis_service->parser->content($localid[0]);
             }
             $uris = $yadis_service->getURIs();
             $this->services[$targetservice] = $uris[0];
         }
     }
 }
<html>
<head>
<title>OpenID discovery</title>
</head>
<body>
  <h2>OpenID discovery tool</h2>
  <p>
    Enter an OpenID URL to begin discovery:
  </p>
  <form>
  <input type="text" name="openid_identifier" size="40" />
  <input type="submit" value="Begin" />
  </form>
<?php 
if ($identifier) {
    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    list($normalized_identifier, $endpoints) = Auth_OpenID_discover($identifier, $fetcher);
    ?>
  <h3>Discovery Results for <?php 
    echo escape($identifier);
    ?>
</h3>

  <table cellpadding="7" cellspacing="0">
    <tbody>
      <tr>
        <th>Claimed Identifier</th>
        <td><?php 
    echo escape($normalized_identifier);
    ?>
</td>
Example #8
0
 /**
  * This should be called statically and will build a Yadis
  * instance if the discovery process succeeds.  This implements
  * Yadis discovery as specified in the Yadis specification.
  *
  * @param string $uri The URI on which to perform Yadis discovery.
  *
  * @param array $http_response An array reference where the HTTP
  * response object will be stored (see {@link
  * Auth_Yadis_HTTPResponse}.
  *
  * @param Auth_Yadis_HTTPFetcher $fetcher An instance of a
  * Auth_Yadis_HTTPFetcher subclass.
  *
  * @param array $extra_ns_map An array which maps namespace names
  * to namespace URIs to be used when parsing the Yadis XRDS
  * document.
  *
  * @param integer $timeout An optional fetcher timeout, in seconds.
  *
  * @return mixed $obj Either null or an instance of
  * Auth_Yadis_Yadis, depending on whether the discovery
  * succeeded.
  */
 function discover($uri, &$fetcher, $extra_ns_map = null, $timeout = 20)
 {
     $result = new Auth_Yadis_DiscoveryResult($uri);
     $request_uri = $uri;
     $headers = array("Accept: " . Auth_Yadis_CONTENT_TYPE . ', text/html; q=0.3, application/xhtml+xml; q=0.5');
     if ($fetcher === null) {
         $fetcher = Auth_Yadis_Yadis::getHTTPFetcher($timeout);
     }
     $response = $fetcher->get($uri, $headers);
     if (!$response || ($response->status != 200 and $response->status != 206)) {
         $result->fail();
         return $result;
     }
     $result->normalized_uri = $response->final_url;
     $result->content_type = Auth_Yadis_Yadis::_getHeader($response->headers, array('content-type'));
     if ($result->content_type && Auth_Yadis_Yadis::_getContentType($result->content_type) == Auth_Yadis_CONTENT_TYPE) {
         $result->xrds_uri = $result->normalized_uri;
     } else {
         $yadis_location = Auth_Yadis_Yadis::_getHeader($response->headers, array(Auth_Yadis_HEADER_NAME));
         if (!$yadis_location) {
             $parser = new Auth_Yadis_ParseHTML();
             $yadis_location = $parser->getHTTPEquiv($response->body);
         }
         if ($yadis_location) {
             $result->xrds_uri = $yadis_location;
             $response = $fetcher->get($yadis_location);
             if (!$response || ($response->status != 200 and $response->status != 206)) {
                 $result->fail();
                 return $result;
             }
             $result->content_type = Auth_Yadis_Yadis::_getHeader($response->headers, array('content-type'));
         }
     }
     $result->response_text = $response->body;
     return $result;
 }
Example #9
0
 /**
  * This method initializes a new {@link Auth_OpenID_Consumer}
  * instance to access the library.
  *
  * @param Auth_OpenID_OpenIDStore $store This must be an object
  * that implements the interface in {@link Auth_OpenID_OpenIDStore}.
  * Several concrete implementations are provided, to cover most common use
  * cases.  For stores backed by MySQL, PostgreSQL, or SQLite, see
  * the {@link Auth_OpenID_SQLStore} class and its sublcasses.  For a
  * filesystem-backed store, see the {@link Auth_OpenID_FileStore} module.
  * As a last resort, if it isn't possible for the server to store
  * state at all, an instance of {@link Auth_OpenID_DumbStore} can be used.
  *
  * @param bool $immediate This is an optional boolean value.  It
  * controls whether the library uses immediate mode, as explained
  * in the module description.  The default value is False, which
  * disables immediate mode.
  */
 function Auth_OpenID_GenericConsumer($store)
 {
     $this->store = $store;
     $this->negotiator = Auth_OpenID_getDefaultNegotiator();
     $this->_use_assocs = is_null($this->store) ? false : true;
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->session_types = Auth_OpenID_getAvailableSessionTypes();
 }
Example #10
0
function detect_fetcher($r, &$out)
{
    $out .= $r->h2('HTTP Fetching');
    $result = @(include 'Auth/Yadis/Yadis.php');
    if (!$result) {
        $out .= $r->p('Yadis code unavailable; could not test fetcher support.');
        return false;
    }
    if (Auth_Yadis_Yadis::curlPresent()) {
        $out .= $r->p('This PHP installation has support for libcurl. Good.');
    } else {
        $out .= $r->p('This PHP installation does not have support for ' . 'libcurl. CURL is not required but is recommended. ' . 'The OpenID library will use an fsockopen()-based fetcher.');
        $lnk = $r->link('http://us3.php.net/manual/en/ref.curl.php');
        $out .= $r->p('See ' . $lnk . ' about enabling the libcurl support ' . 'for PHP.');
    }
    $ok = true;
    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    $fetch_url = 'http://www.openidenabled.com/resources/php-fetch-test';
    $expected_url = $fetch_url . '.txt';
    $result = $fetcher->get($fetch_url);
    if (isset($result)) {
        $parts = array('An HTTP request was completed.');
        // list ($code, $url, $data) = $result;
        if ($result->status != '200') {
            $ok = false;
            $parts[] = $r->b(sprintf('Got %s instead of the expected HTTP status code ' . '(200).', $result->status));
        }
        $url = $result->final_url;
        if ($url != $expected_url) {
            $ok = false;
            if ($url == $fetch_url) {
                $msg = 'The redirected URL was not returned.';
            } else {
                $msg = 'An unexpected URL was returned: <' . $url . '>.';
            }
            $parts[] = $r->b($msg);
        }
        $data = $result->body;
        if ($data != 'Hello World!') {
            $ok = false;
            $parts[] = $r->b('Unexpected data was returned.');
        }
        $out .= $r->p(implode(' ', $parts));
    } else {
        $ok = false;
        $out .= $r->p('Fetching URL ' . $lnk . ' failed!');
    }
    if ($fetcher->supportsSSL()) {
        $out .= $r->p('Your PHP installation appears to support SSL, so it ' . 'will be able to process HTTPS identity URLs and server URLs.');
    } else {
        $out .= $r->p('Your PHP installation does not support SSL, so it ' . 'will NOT be able to process HTTPS identity URLs and server URLs.');
    }
    return $ok;
}
Example #11
0
 /**
  * This method initializes a new {@link Auth_OpenID_Consumer}
  * instance to access the library.
  *
  * @param Auth_OpenID_Store_OpenIDStore $store This must be an object
  * that implements the interface in {@link Auth_OpenID_Store_OpenIDStore}.
  * Several concrete implementations are provided, to cover most common use
  * cases.  For stores backed by MySQL, PostgreSQL, or SQLite, see
  * the {@link Auth_OpenID_Store_SQLStore} class and its sublcasses.  For a
  * filesystem-backed store, see the {@link Auth_OpenID_Store_FileStore} module.
  * As a last resort, if it isn't possible for the server to store
  * state at all, an instance of {@link Auth_OpenID_Store_DumbStore} can be used.
  *
  * @param bool $immediate This is an optional boolean value.  It
  * controls whether the library uses immediate mode, as explained
  * in the module description.  The default value is False, which
  * disables immediate mode.
  */
 function Auth_OpenID_GenericConsumer($store)
 {
     $this->store = $store;
     $this->negotiator = Auth_OpenID_getDefaultNegotiator();
     $this->_use_assocs = true;
     if (is_null($this->store) || is_a($this->store, 'Auth_OpenID_Store_DumbStore')) {
         $this->_use_assocs = false;
     }
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->session_types = Auth_OpenID_getAvailableSessionTypes();
 }
Example #12
0
function omb_update_profile($profile, $remote_profile, $subscription)
{
    $user = User::staticGet($profile->id);
    $con = omb_oauth_consumer();
    $token = new OAuthToken($subscription->token, $subscription->secret);
    $url = $remote_profile->updateprofileurl;
    $parsed = parse_url($url);
    $params = array();
    parse_str($parsed['query'], $params);
    $req = OAuthRequest::from_consumer_and_token($con, $token, "POST", $url, $params);
    $req->set_parameter('omb_version', OMB_VERSION_01);
    $req->set_parameter('omb_listenee', $user->uri);
    $req->set_parameter('omb_listenee_profile', common_profile_url($profile->nickname));
    $req->set_parameter('omb_listenee_nickname', $profile->nickname);
    # We use blanks to force emptying any existing values in these optional fields
    $req->set_parameter('omb_listenee_fullname', $profile->fullname ? $profile->fullname : '');
    $req->set_parameter('omb_listenee_homepage', $profile->homepage ? $profile->homepage : '');
    $req->set_parameter('omb_listenee_bio', $profile->bio ? $profile->bio : '');
    $req->set_parameter('omb_listenee_location', $profile->location ? $profile->location : '');
    $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
    $req->set_parameter('omb_listenee_avatar', $avatar ? $avatar->url : '');
    $req->sign_request(omb_hmac_sha1(), $con, $token);
    # We re-use this tool's fetcher, since it's pretty good
    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    common_debug('request URL = ' . $req->get_normalized_http_url(), __FILE__);
    common_debug('postdata = ' . $req->to_postdata(), __FILE__);
    $result = $fetcher->post($req->get_normalized_http_url(), $req->to_postdata(), array('User-Agent: Laconica/' . LACONICA_VERSION));
    common_debug('Got HTTP result "' . print_r($result, true) . '"', __FILE__);
    if (empty($result) || !$result) {
        common_debug("Unable to contact " . $req->get_normalized_http_url());
    } else {
        if ($result->status == 403) {
            # not authorized, don't send again
            common_debug('403 result, deleting subscription', __FILE__);
            $subscription->delete();
            return false;
        } else {
            if ($result->status != 200) {
                common_debug('Error status ' . $result->status, __FILE__);
                return false;
            } else {
                # success!
                parse_str($result->body, $return);
                if (isset($return['omb_version']) && $return['omb_version'] === OMB_VERSION_01) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }
}
Example #13
0
 function access_token($omb)
 {
     common_debug('starting request for access token', __FILE__);
     $con = omb_oauth_consumer();
     $tok = new OAuthToken($omb['token'], $omb['secret']);
     common_debug('using request token "' . $tok . '"', __FILE__);
     $url = $omb['access_token_url'];
     common_debug('using access token url "' . $url . '"', __FILE__);
     # XXX: Is this the right thing to do? Strip off GET params and make them
     # POST params? Seems wrong to me.
     $parsed = parse_url($url);
     $params = array();
     parse_str($parsed['query'], $params);
     $req = OAuthRequest::from_consumer_and_token($con, $tok, "POST", $url, $params);
     $req->set_parameter('omb_version', OMB_VERSION_01);
     # XXX: test to see if endpoint accepts this signature method
     $req->sign_request(omb_hmac_sha1(), $con, $tok);
     # We re-use this tool's fetcher, since it's pretty good
     common_debug('posting to access token url "' . $req->get_normalized_http_url() . '"', __FILE__);
     common_debug('posting request data "' . $req->to_postdata() . '"', __FILE__);
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $result = $fetcher->post($req->get_normalized_http_url(), $req->to_postdata(), array('User-Agent: Laconica/' . LACONICA_VERSION));
     common_debug('got result: "' . print_r($result, true) . '"', __FILE__);
     if ($result->status != 200) {
         return null;
     }
     parse_str($result->body, $return);
     return array($return['oauth_token'], $return['oauth_token_secret']);
 }
Example #14
0
 /**
  * This method initializes a new {@link Auth_OpenID_Consumer}
  * instance to access the library.
  *
  * @param Auth_OpenID_OpenIDStore $store This must be an object
  * that implements the interface in {@link Auth_OpenID_OpenIDStore}.
  * Several concrete implementations are provided, to cover most common use
  * cases.  For stores backed by MySQL, PostgreSQL, or SQLite, see
  * the {@link Auth_OpenID_SQLStore} class and its sublcasses.  For a
  * filesystem-backed store, see the {@link Auth_OpenID_FileStore} module.
  * As a last resort, if it isn't possible for the server to store
  * state at all, an instance of {@link Auth_OpenID_DumbStore} can be used.
  *
  * @param bool $immediate This is an optional boolean value.  It
  * controls whether the library uses immediate mode, as explained
  * in the module description.  The default value is False, which
  * disables immediate mode.
  */
 function __construct(&$store)
 {
     $this->store =& $store;
     $this->negotiator =& Auth_OpenID_getDefaultNegotiator();
     $this->_use_assocs = $this->store ? true : false;
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->session_types = Auth_OpenID_getAvailableSessionTypes();
 }
Example #15
0
 /**
  * This method initializes a new {@link Auth_OpenID_Consumer}
  * instance to access the library.
  *
  * @param Auth_OpenID_OpenIDStore $store This must be an object
  * that implements the interface in {@link Auth_OpenID_OpenIDStore}.
  * Several concrete implementations are provided, to cover most common use
  * cases.  For stores backed by MySQL, PostgreSQL, or SQLite, see
  * the {@link Auth_OpenID_SQLStore} class and its sublcasses.  For a
  * filesystem-backed store, see the {@link Auth_OpenID_FileStore} module.
  * As a last resort, if it isn't possible for the server to store
  * state at all, an instance of {@link Auth_OpenID_DumbStore} can be used.
  *
  * @param bool $immediate This is an optional boolean value.  It
  * controls whether the library uses immediate mode, as explained
  * in the module description.  The default value is False, which
  * disables immediate mode.
  */
 public function __construct($store)
 {
     $this->store = $store;
     $this->negotiator = Auth_OpenID_getDefaultNegotiator();
     $this->_use_assocs = is_null($this->store) ? false : true;
     if (get_class($this->store) == "Auth_OpenID_DumbStore") {
         $this->_use_assocs = false;
     }
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->session_types = Auth_OpenID_getAvailableSessionTypes();
 }
Example #16
0
 function returnToVerified()
 {
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     return call_user_func_array($this->verifyReturnTo, array($this->trust_root, $this->return_to, $fetcher));
 }
 /**
  * Check if user supplied URL is a valid OpenID and
  * get the URL provider from it.
  * 
  * @param string $identifier user supplied OpenID identifier
  * @return string
  */
 public function validate($identifier)
 {
     $oldIdentifier = get_option('openid_delegation_url');
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $response = Auth_Yadis_Yadis::discover($identifier, $fetcher);
     list($normalized_identifier, $endpoints) = Auth_OpenID_discover($identifier, $fetcher);
     if (!empty($identifier) && empty($endpoints)) {
         add_settings_error('openid_delegation_url', 'error', sprintf(__('No OpenID services discovered for %s.', 'openid-delegation'), $identifier));
         return $oldIdentifier;
     }
     update_option('openid_delegation_provider', $endpoints[0]->server_url);
     if (!empty($response->xrds_uri)) {
         update_option('openid_delegation_xrds_location', $response->xrds_uri);
     }
     return $normalized_identifier;
 }
Example #18
0
 function trackback($url, $endpoint)
 {
     $profile = $this->notice->getProfile();
     $args = array('title' => sprintf(_('%1$s\'s status on %2$s'), $profile->nickname, common_exact_date($this->notice->created)), 'excerpt' => $this->notice->content, 'url' => $this->notice->uri, 'blog_name' => $profile->nickname);
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $result = $fetcher->post($endpoint, http_build_query($args), array('User-Agent: ' . $this->userAgent()));
     if ($result->status != '200') {
         common_log(LOG_WARNING, "Trackback error for '{$url}' ({$endpoint}): " . "{$result->body}");
     } else {
         common_log(LOG_INFO, "Trackback success for '{$url}' ({$endpoint}): " . "'{$result->body}'");
     }
 }
Example #19
0
 function requestToken($omb)
 {
     $con = omb_oauth_consumer();
     $url = omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]);
     # XXX: Is this the right thing to do? Strip off GET params and make them
     # POST params? Seems wrong to me.
     $parsed = parse_url($url);
     $params = array();
     parse_str($parsed['query'], $params);
     $req = OAuthRequest::from_consumer_and_token($con, null, "POST", $url, $params);
     $listener = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]);
     if (!$listener) {
         return null;
     }
     $req->set_parameter('omb_listener', $listener);
     $req->set_parameter('omb_version', OMB_VERSION_01);
     # XXX: test to see if endpoint accepts this signature method
     $req->sign_request(omb_hmac_sha1(), $con, null);
     # We re-use this tool's fetcher, since it's pretty good
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $result = $fetcher->post($req->get_normalized_http_url(), $req->to_postdata(), array('User-Agent: Laconica/' . LACONICA_VERSION));
     if ($result->status != 200) {
         return null;
     }
     parse_str($result->body, $return);
     return array($return['oauth_token'], $return['oauth_token_secret']);
 }
Example #20
0
/**
 * Discover and cache OpenID services for a user's delegate OpenID.
 *
 * @param int $userid user ID
 * @url string URL to discover.  If not provided, user's current delegate will be used
 * @return bool true if successful
 */
function openid_server_update_delegation_info($userid, $url = null)
{
    if (empty($url)) {
        $url = get_usermeta($userid, 'openid_delegate');
    }
    if (empty($url)) {
        return false;
    }
    $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
    $discoveryResult = Auth_Yadis_Yadis::discover($url, $fetcher);
    $endpoints = Auth_OpenID_ServiceEndpoint::fromDiscoveryResult($discoveryResult);
    $services = array();
    if (!empty($endpoints)) {
        foreach ($endpoints as $endpoint) {
            $service = array('Type' => array(), 'URI' => $endpoint->server_url);
            foreach ($endpoint->type_uris as $type) {
                $service['Type'][] = array('content' => $type);
                if ($type == Auth_OpenID_TYPE_2_0_IDP) {
                    $service['LocalID'] = Auth_OpenID_IDENTIFIER_SELECT;
                } else {
                    if ($type == Auth_OpenID_TYPE_2_0) {
                        $service['LocalID'] = $endpoint->local_id;
                    } else {
                        if (in_array($type, array(Auth_OpenID_TYPE_1_0, Auth_OpenID_TYPE_1_1, Auth_OpenID_TYPE_1_2))) {
                            $service['openid:Delegate'] = $endpoint->local_id;
                        }
                    }
                }
            }
            $services[] = $service;
        }
    }
    if (empty($services)) {
        // resort to checking for HTML links
        $response = $fetcher->get($url);
        $html_content = $response->body;
        $p = new Auth_OpenID_Parse();
        $link_attrs = $p->parseLinkAttrs($html_content);
        // check HTML for OpenID2
        $server_url = $p->findFirstHref($link_attrs, 'openid2.provider');
        if ($server_url !== null) {
            $openid_url = $p->findFirstHref($link_attrs, 'openid2.local_id');
            if ($openid_url == null) {
                $openid_url = $url;
            }
            $services[] = array('Type' => array(array('content' => Auth_OpenID_Type_1_1)), 'URI' => $server_url, 'LocalID' => $openid_url);
        }
        // check HTML for OpenID1
        $server_url = $p->findFirstHref($link_attrs, 'openid.server');
        if ($server_url !== null) {
            $openid_url = $p->findFirstHref($link_attrs, 'openid.delegate');
            if ($openid_url == null) {
                $openid_url = $url;
            }
            $services[] = array('Type' => array(array('content' => Auth_OpenID_Type_2_0)), 'URI' => $server_url, 'openid:Delegate' => $openid_url);
        }
    }
    if (empty($services)) {
        return false;
    }
    update_usermeta($userid, 'openid_delegate', $url);
    update_usermeta($userid, 'openid_delegate_services', $services);
    return true;
}
Example #21
0
function broadcast_omb_notice(&$model, &$rec)
{
    if (!isset($rec->title) || !isset($rec->uri)) {
        return;
    }
    global $request, $db;
    if (empty($rec->uri)) {
        $rec->set_value('uri', $request->url_for(array('resource' => '__' . $rec->id)));
        $rec->save_changes();
    }
    wp_plugin_include(array('wp-oauth'));
    $i = owner_of($rec);
    $listenee_uri = $i->profile;
    $notice_uri = $rec->uri;
    $notice_content = substr($rec->title, 0, 140);
    $notice_url = $notice_uri;
    $license = $i->license;
    $sent_to = array();
    $Subscription = $db->model('Subscription');
    $Subscription->has_one('subscriber:identity');
    $where = array('subscriptions.subscribed' => $i->id);
    $Subscription->set_param('find_by', $where);
    $Subscription->find();
    while ($sub = $Subscription->MoveNext()) {
        $sub_token = trim($sub->token);
        $sub_secret = trim($sub->secret);
        $sid = $sub->FirstChild('identities');
        $url = $sid->post_notice;
        if (!in_array($url, $sent_to) && !empty($url) && !strstr($url, $request->base)) {
            $sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
            $wp_plugins = "wp-plugins" . DIRECTORY_SEPARATOR . "plugins" . DIRECTORY_SEPARATOR . "enabled";
            $path = plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . 'wp-openid' . DIRECTORY_SEPARATOR;
            add_include_path($path);
            require_once "Auth/Yadis/Yadis.php";
            $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
            //for ($i=0;$i<5;$i++) {
            $consumer = new OAuthConsumer($request->base, '');
            $token = new OAuthToken($sub_token, $sub_secret);
            $parsed = parse_url($url);
            $params = array();
            parse_str($parsed['query'], $params);
            $req = OAuthRequest::from_consumer_and_token($consumer, $token, "POST", $url, $params);
            $req->set_parameter('omb_version', OMB_VERSION);
            $req->set_parameter('omb_listenee', $listenee_uri);
            $req->set_parameter('omb_notice', $notice_uri);
            $req->set_parameter('omb_notice_content', $notice_content);
            $req->set_parameter('omb_notice_url', $notice_url);
            $req->set_parameter('omb_notice_license', $license);
            $req->sign_request($sha1_method, $consumer, $token);
            $result = $fetcher->post($req->get_normalized_http_url(), $req->to_postdata());
            if ($result->status == 403) {
                $db->delete_record($sub);
            } else {
                parse_str($result->body, $return);
                if (is_array($return) && $return['omb_version'] == OMB_VERSION) {
                    $sent_to[] = $url;
                } else {
                    admin_alert('failed to post' . "\n\n" . $url . "\n\n" . $result->body . "\n\n" . $notice_content);
                }
            }
            //}
            // this is the old CURL version of omb_notice
            //$curl = curl_init($url);
            //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            //curl_setopt($curl, CURLOPT_HEADER, false);
            //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            //curl_setopt($curl, CURLOPT_POST, true);
            //curl_setopt($curl, CURLOPT_POSTFIELDS, $req->to_postdata());
            //curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            //$result = curl_exec($curl);
            //curl_close($curl);
        }
    }
}
Example #22
0
 public function __construct($urls, $listener_uri = null)
 {
     $this->services = $urls;
     $this->datastore = omb_oauth_datastore();
     $this->oauth_consumer = omb_oauth_consumer();
     $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     $this->fetcher->timeout = intval(common_config('omb', 'timeout'));
     $this->listener_uri = $listener_uri;
 }
Example #23
0
function broadcast_omb_profile_update()
{
    global $request, $db;
    wp_plugin_include(array('wp-oauth'));
    $i = get_profile();
    $listenee_uri = $i->profile;
    $license = $i->license;
    $sent_to = array();
    $Subscription = $db->model('Subscription');
    $Subscription->has_one('subscriber:identity');
    $where = array('subscriptions.subscribed' => $i->id);
    $Subscription->set_param('find_by', $where);
    $Subscription->find();
    while ($sub = $Subscription->MoveNext()) {
        $sub_token = trim($sub->token);
        $sub_secret = trim($sub->secret);
        $sid = $sub->FirstChild('identities');
        $url = $sid->update_profile;
        if (!in_array($url, $sent_to) && !empty($url) && !strstr($url, $request->base)) {
            $sent_to[] = $url;
            $sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
            $wp_plugins = "wp-plugins" . DIRECTORY_SEPARATOR . "plugins" . DIRECTORY_SEPARATOR . "enabled";
            $path = plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . 'wp-openid' . DIRECTORY_SEPARATOR;
            add_include_path($path);
            require_once "Auth/Yadis/Yadis.php";
            $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
            $consumer = new OAuthConsumer($request->base, '');
            $token = new OAuthToken($sub_token, $sub_secret);
            $parsed = parse_url($url);
            $params = array();
            parse_str($parsed['query'], $params);
            $req = OAuthRequest::from_consumer_and_token($consumer, $token, "POST", $url, $params);
            $req->set_parameter('omb_version', OMB_VERSION);
            $req->set_parameter('omb_listenee', $listenee_uri);
            $listenee_params = array('omb_listenee_profile' => $i->profile, 'omb_listenee_nickname' => $i->nickname, 'omb_listenee_license' => $i->license, 'omb_listenee_fullname' => $i->fullname, 'omb_listenee_homepage' => $i->homepage, 'omb_listenee_bio' => $i->bio, 'omb_listenee_location' => $i->locality, 'omb_listenee_avatar' => $i->avatar);
            foreach ($listenee_params as $k => $v) {
                $req->set_parameter($k, $v);
            }
            $req->sign_request($sha1_method, $consumer, $token);
            $result = $fetcher->post($req->get_normalized_http_url(), $req->to_postdata());
            if ($result->status == 403) {
                // not so much
            } else {
                parse_str($result->body, $return);
                if (is_array($return) && $return['omb_version'] == OMB_VERSION) {
                    // nice
                } else {
                    // could be better
                }
            }
        }
    }
}