First, require this library into your program source:
  require_once "Auth/Yadis/Yadis.php";
To perform Yadis discovery, first call the "discover" method statically with a URI parameter:
  $http_response = array();
 $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
 $yadis_object = Auth_Yadis_Yadis::discover($uri,
                                   $http_response, $fetcher);
If the discovery succeeds, $yadis_object will be an instance of {@link Auth_Yadis_Yadis}. If not, it will be null. The XRDS document found during discovery should have service descriptions, which can be accessed by calling
  $service_list = $yadis_object->services();
which returns an array of objects which describe each service. These objects are instances of Auth_Yadis_Service. Each object describes exactly one whole Service element, complete with all of its Types and URIs (no expansion is performed). The common use case for using the service objects returned by services() is to write one or more filter functions and pass those to services():
  $service_list = $yadis_object->services(
                              array("filterByURI",
                                    "filterByExtension"));
The filter functions (whose names appear in the array passed to services()) take the following form:
  function myFilter($service) {
Query $service object here.  Return true if the service
matches your query; false if not.
 }
This is an example of a filter which uses a regular expression to match the content of URI tags (note that the Auth_Yadis_Service class provides a getURIs() method which you should use instead of this contrived example):
 function URIMatcher($service) {
     foreach ($service->getElements('xrd:URI') as $uri) {
         if (preg_match("/some_pattern/",
                        $service->parser->content($uri))) {
             return true;
         }
     }
     return false;
 }
The filter functions you pass will be called for each service object to determine which ones match the criteria your filters specify. The default behavior is that if a given service object matches ANY of the filters specified in the services() call, it will be returned. You can specify that a given service object will be returned ONLY if it matches ALL specified filters by changing the match mode of services():
  $yadis_object->services(array("filter1", "filter2"),
                         SERVICES_YADIS_MATCH_ALL);
See {@link SERVICES_YADIS_MATCH_ALL} and {@link SERVICES_YADIS_MATCH_ANY}. Services described in an XRDS should have a library which you'll probably be using. Those libraries are responsible for defining filters that can be used with the "services()" call. If you need to write your own filter, see the documentation for {@link Auth_Yadis_Service}.
Ejemplo n.º 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';
 }
Ejemplo n.º 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;
}
Ejemplo n.º 3
0
 /**
  * Create an instance from URL
  *
  * Constructs an OMB_Yadis_XRDS object from a given URL. A full Yadis
  * discovery is performed on the URL and the XRDS is parsed.
  * Throws an OMB_InvalidYadisException when no Yadis is discovered or the
  * detected XRDS file is broken.
  *
  * @param string                 $url     The URL on which Yadis discovery
  *                                        should be performed on
  * @param Auth_Yadis_HTTPFetcher $fetcher A fetcher used to get HTTP
  *                                        resources
  *
  * @access public
  *
  * @return OMB_Yadis_XRDS The initialized object representing the given
  *                        resource
  */
 public static function fromYadisURL($url, $fetcher)
 {
     /* Perform a Yadis discovery. */
     $yadis = Auth_Yadis_Yadis::discover($url, $fetcher);
     if ($yadis->failed) {
         throw new OMB_InvalidYadisException($url);
     }
     /* Parse the XRDS file. */
     $xrds = OMB_Yadis_XRDS::parseXRDS($yadis->response_text);
     if ($xrds === null) {
         throw new OMB_InvalidYadisException($url);
     }
     $xrds->fetcher = $fetcher;
     return $xrds;
 }
Ejemplo n.º 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;
}
Ejemplo n.º 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];
         }
     }
 }
Ejemplo n.º 7
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();
 }
Ejemplo n.º 8
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>
Ejemplo n.º 9
0
/**
 * Perform XRDS discovery at the specified URI for any EAUT Services.
 */
function Auth_Yadis_Email_getServices($uri, $fetcher)
{
    $uri = Auth_OpenID::normalizeUrl($uri);
    $response = Auth_Yadis_Yadis::discover($uri, $fetcher);
    if ($response->isXRDS()) {
        $xrds =& Auth_Yadis_XRDS::parseXRDS($response->response_text);
        if ($xrds) {
            return $xrds->services(array('filter_MatchesAnyEmailType'));
        }
    }
}
Ejemplo n.º 10
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);
        }
    }
}
Ejemplo n.º 11
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();
 }
Ejemplo n.º 12
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;
 }
Ejemplo n.º 13
0
 function returnToVerified()
 {
     $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
     return call_user_func_array($this->verifyReturnTo, array($this->trust_root, $this->return_to, $fetcher));
 }
Ejemplo n.º 14
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}'");
     }
 }
Ejemplo n.º 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();
 }
Ejemplo n.º 16
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;
                }
            }
        }
    }
}
Ejemplo n.º 17
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();
 }
Ejemplo n.º 18
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']);
 }
Ejemplo n.º 19
0
 function runTest()
 {
     if ($this->expected === null) {
         $result = Auth_Yadis_Yadis::discover($this->input_url, $this->fetcher);
         $this->assertTrue($result->isFailure());
     } else {
         $result = Auth_Yadis_Yadis::discover($this->input_url, $this->fetcher);
         if ($result === null) {
             $this->fail("Discovery result was null");
             return;
         }
         $this->assertEquals($this->input_url, $result->request_uri);
         $msg = 'Identity URL mismatch: actual = %s, expected = %s';
         $msg = sprintf($msg, $result->normalized_uri, $this->expected->uri);
         $this->assertEquals($this->expected->uri, $result->normalized_uri, $msg);
         $msg = 'Content mismatch: actual = %s, expected = %s';
         $msg = sprintf($msg, $result->response_text, $this->expected->body);
         $this->assertEquals($this->expected->body, $result->response_text, $msg);
         $this->assertEquals($this->expected->xrds_uri, $result->xrds_uri);
         $this->assertEquals($this->expected->content_type, $result->content_type);
     }
 }
Ejemplo n.º 20
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;
}
Ejemplo n.º 21
0
function Auth_OpenID_discoverWithYadis($uri, &$fetcher)
{
    // Discover OpenID services for a URI. Tries Yadis and falls back
    // on old-style <link rel='...'> discovery if Yadis fails.
    // Might raise a yadis.discover.DiscoveryFailure if no document
    // came back for that URI at all.  I don't think falling back to
    // OpenID 1.0 discovery on the same URL will help, so don't bother
    // to catch it.
    $openid_services = array();
    $response = Auth_Yadis_Yadis::discover($uri, $fetcher);
    $yadis_url = $response->normalized_uri;
    $yadis_services = array();
    if ($response->isFailure()) {
        return array($uri, array());
    }
    $xrds =& Auth_Yadis_XRDS::parseXRDS($response->response_text);
    if ($xrds) {
        $yadis_services = $xrds->services(array('filter_MatchesAnyOpenIDType'));
    }
    if (!$yadis_services) {
        if ($response->isXRDS()) {
            return Auth_OpenID_discoverWithoutYadis($uri, $fetcher);
        }
        // Try to parse the response as HTML to get OpenID 1.0/1.1
        // <link rel="...">
        $openid_services = Auth_OpenID_ServiceEndpoint::fromHTML($yadis_url, $response->response_text);
    } else {
        $openid_services = Auth_OpenID_makeOpenIDEndpoints($yadis_url, $yadis_services);
    }
    $openid_services = Auth_OpenID_getOPOrUserServices($openid_services);
    return array($yadis_url, $openid_services);
}
 function test_blank_content_type()
 {
     $fetcher = new BlankContentTypeFetcher();
     $result = Auth_Yadis_Yadis::discover("http://bogus", $fetcher);
     $this->assertEquals("", $result->content_type);
 }
 /**
  * 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;
 }
Ejemplo n.º 24
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;
}
Ejemplo n.º 25
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']);
 }
Ejemplo n.º 26
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;
 }
Ejemplo n.º 27
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
                }
            }
        }
    }
}