Esempio n. 1
0
/**
 * Returns the atom feed only requires oauth3/OAuthRequester.php
 * TODO: will need to throw execptions for if user has no token, or if token no longer works... :/
 */
function oauth3_obtain_feed($user_id, $request_uri = 'https://mail.google.com/mail/feed/atom')
{
    // Do we have a token for this user???
    // if not return error print "no token found for" exit();
    // if this is a curl call you can't use global user here
    //$user_id= 5;
    //$request_uri = 'https://mail.google.com/mail/feed/atom';
    try {
        $req = new OAuthRequester($request_uri, 'GET', $params = null);
        $result = $req->doRequest($user_id);
        //throws OAuthException exception on an error
        // $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
        $feed = $result['body'];
    } catch (OAuthException $e) {
        //print "Error: $e";
    }
    // TODO: how to return whatever error it says
    // should return feed body Output while still testing
    if (empty($feed) or !empty($e)) {
        return "FALSE Error Message: {$e}";
        // print "reasons for false or error info"; // or just log the error info
    } else {
        return $feed;
    }
}
Esempio n. 2
0
function douban_callback()
{
    OAuthRequester::requestAccessToken(DOUBAN_KEY, $_SESSION['oauth_token'], 0, 'POST', $options = array('oauth_verifier' => $_SESSION['oauth_token']));
    $req = new OAuthRequester('http://api.douban.com/people/' . urlencode('@me'), 'get');
    $res = $req->doRequest();
    $user_data = new SimpleXMLElement($res['body']);
    $uid = array_pop(explode('/', $user_data->id));
    $auth_type = 'douban';
    $auth = R::findOne('oauth', "uid=? AND type=?", array($uid, $auth_type));
    if (!$auth) {
        $auth = R::dispense('oauth');
        $auth->uid = $uid;
        $auth->type = $auth_type;
        $encrypt_key = rand(100000, 999999);
        $auth->secret = $encrypt_key;
    } else {
        $encrypt_key = $auth->secret;
    }
    $cookie_str = sha1(implode('', array($uid, $auth_type, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $encrypt_key)));
    $expire = time() + 3600 * 24 * 365;
    setcookie('s', $cookie_str, $expire);
    setcookie('auth_type', $auth_type, $expire);
    setcookie('uid', $uid, $expire);
    $auth->setMeta('buildcommand.unique', array(array('uid', 'type')));
    $auth->setMeta('buildcommand.indexes', array('uid' => 'uid'));
    R::store($auth);
}
Esempio n. 3
0
 public function getIdentity($oauth_user_id)
 {
     // get twitter handle
     #$request = new OAuthRequester('http://api.twitter.com/1/account/verify_credentials.xml', 'GET');
     $request = new OAuthRequester('http://api.twitter.com/1/account/verify_credentials.json', 'GET');
     $result = $request->doRequest($oauth_user_id);
     if ($result['code'] == 200) {
         $data = json_decode($result['body'], true);
         if (is_null($data)) {
             switch (json_last_error()) {
                 case JSON_ERROR_DEPTH:
                     error_log('JSON Error: Maximum stack depth exceeded');
                     break;
                 case JSON_ERROR_CTRL_CHAR:
                     error_log('JSON Error: Unexpected control character found');
                     break;
                 case JSON_ERROR_SYNTAX:
                     error_log('JSON Error: Syntax error, malformed JSON');
                     break;
                 case JSON_ERROR_NONE:
                     error_log('JSON Error: No errors');
                     break;
             }
             return null;
         }
         if (!is_null($data) && array_key_exists('id', $data) && array_key_exists('name', $data)) {
             return $data;
         }
     }
     return null;
 }
function getResponseAPI($userIdZyncro, $sessionid, $serviceAPI)
{
    // Init the OAuthStore
    $options = array('consumer_key' => CONSUMER_KEY, 'consumer_secret' => CONSUMER_SECRET, 'server_uri' => OAUTH_HOST, 'request_token_uri' => REQUEST_TOKEN_URL, 'signature_methods' => array('HMAC-SHA1'), 'authorize_uri' => AUTHORIZE_URL, 'access_token_uri' => ACCESS_TOKEN_URL);
    // Note: do not use "Session" storage in production. Prefer a database
    // storage, such as MySQL.
    OAuthStore::instance("Session", $options);
    try {
        // get a request token
        $getRequestTokenParams = array();
        $tokenResultParams = OAuthRequester::requestRequestToken(CONSUMER_KEY, 0, $getRequestTokenParams, 'GET');
        // get an access token
        $oauthToken = $tokenResultParams['token'];
        $getAccessTokenParams = array('oauth_verifier' => $sessionid);
        OAuthRequester::requestAccessToken(CONSUMER_KEY, $oauthToken, 0, 'POST', $getAccessTokenParams);
        // make the request.
        $urlRequest = OAUTH_HOST . $serviceAPI;
        $request = new OAuthRequester($urlRequest, 'GET');
        $result = $request->doRequest(0);
        if ($result['code'] == 200) {
            return $result['body'];
        }
    } catch (OAuthException2 $e) {
    }
}
Esempio n. 5
0
 /**
  * Do request 
  * 
  * @param   string $type Type of request
  * @param   string $url URL
  * @param   array $params (Optional) Parameters
  * @access  public
  * @return  mixed
  */
 public function request($type, $url, $params = array())
 {
     ApiDebug::p('running request from ' . __CLASS__);
     $oauth = $this->_getOAuthInstance();
     $request = new \OAuthRequester(ApiUtils::getFullUrl($url, self::$_epoint), $type, $params);
     $data = $request->doRequest(0, self::_getCurlOptions());
     ApiDebug::p('got response from server', $data);
     return $data['body'];
 }
Esempio n. 6
0
 public function getIdentity($oauth_user_id)
 {
     // get twitter handle
     $request = new OAuthRequester('http://www.ohloh.net/accounts/me.xml', 'GET');
     $result = $request->doRequest($oauth_user_id);
     if ($result['code'] == 200) {
         $raw_xml = $result['body'];
         $xml = new SimpleXMLElement($raw_xml);
         // todo add more fields
         return array('id' => (string) $xml->id, 'name' => (string) $xml->name);
     }
     return null;
 }
Esempio n. 7
0
 public function getIdentity($oauth_user_id)
 {
     // get meetup user id
     $request = new OAuthRequester('https://www.google.com/m8/feeds/groups/default/full', 'GET');
     $result = $request->doRequest($oauth_user_id);
     $self_url = null;
     if ($result['code'] == 200) {
         $raw_xml = $result['body'];
         $xml = new SimpleXMLElement($raw_xml);
         return array('id' => (string) $xml->id, 'name' => (string) $xml->author->name, 'email' => (string) $xml->author->email);
     }
     return null;
 }
Esempio n. 8
0
 public function getIdentity($oauth_user_id)
 {
     // get meetup user id
     $request = new OAuthRequester('https://api.meetup.com/members.json/?relation=self', 'GET');
     $result = $request->doRequest($oauth_user_id);
     if ($result['code'] == 200) {
         $userdata = json_decode($result['body'], true);
         // array includes 'id' parameter which uniquely identifies a user
         if (array_key_exists('id', $userdata['results'][0]) && array_key_exists('name', $userdata['results'][0])) {
             return $userdata['results'][0];
         }
     }
     return null;
 }
Esempio n. 9
0
 function query($query)
 {
     if (preg_match("/^SELECT|^SHOW|^DESCRIBE/i", $query)) {
         $request = new OAuthRequester(URL . "?sql=" . rawurlencode($query), 'GET');
     } else {
         $request = new OAuthRequester(URL, 'POST', "sql=" . rawurlencode($query));
     }
     $result = $request->doRequest($this->user_id);
     if ($result['code'] == 200) {
         return $result['body'];
     } else {
         return null;
     }
 }
 function query($query)
 {
     if (preg_match("/^SELECT|^SHOW|^DESCRIBE/i", $query)) {
         $request = new OAuthRequester("https://www.googleapis.com/fusiontables/v1/query?sql=" . rawurlencode($query), 'GET');
     } else {
         $request = new OAuthRequester("https://www.googleapis.com/fusiontables/v1/query", 'POST', "sql=" . rawurlencode($query));
     }
     $result = $request->doRequest($this->user_id);
     if ($result['code'] == 200) {
         return $result['body'];
     } else {
         return null;
     }
 }
Esempio n. 11
0
  public function run_query($endpoint, $params, $method="GET")
  {
    if (!$this->apiKey)
      throw new Semantics3_AuthenticationError('No API key provided.');

    if (!$this->apiSecret)
      throw new Semantics3_AuthenticationError('No API secret provided.');

    $options = array( 'consumer_key' => $this->apiKey, 'consumer_secret' => $this->apiSecret );
    OAuthStore::instance("2Leg", $options );
    $url = $this->apiBase.$endpoint;
    if ($method == "GET") {
      $url = $url."?q=".urlencode(json_encode($params));
      $params = null;
    }
    else {
      $params = json_encode($params);
    }

    try
    {
      switch ($method) {
        case "GET":
          $request = new OAuthRequester($url, $method, $params);
          break;
        case "POST":
          $request = new OAuthRequester($url, $method, '', $params);
          break;
        case "DELETE":
          $request = new OAuthRequester($url, $method);
          break;
        default:
          $request = new OAuthRequester($url, $method);
      }

      $result = $request->doRequest();
      return $result['body'];
    }
    catch(OAuthException2 $e)
    {
      print "\n";
      $error = $e->getMessage();
      print $error."\n";
    }

  }
Esempio n. 12
0
function fGetTweets($user, $limit)
{
    $options = array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET);
    OAuthStore::instance("2Leg", $options);
    try {
        // Obtain a request object for the request we want to make
        $request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
        $result = $request->doRequest(0);
        parse_str($result['body'], $params);
        // now make the request.
        $request = new OAuthRequester(TWITTER_PUBLIC_TIMELINE_API, 'GET', $params);
        $result = $request->doRequest();
        $response = $result['body'];
    } catch (OAuthException2 $e) {
        $response = "Exception" . $e->getMessage();
    }
    return $response;
}
Esempio n. 13
0
 protected function getOAuthRequester($method, $url, $params)
 {
     switch ($method) {
         case "GET":
             $request = new OAuthRequester($url, $method, $params);
             break;
         case "POST":
             $request = new OAuthRequester($url, $method, '', $params);
             break;
         case "DELETE":
             $request = new OAuthRequester($url, $method);
             break;
         default:
             $request = new OAuthRequester($url, $method);
     }
     $result = $request->doRequest();
     return $result['body'];
 }
Esempio n. 14
0
 function index()
 {
     $options = array('consumer_key' => $this->key, 'consumer_secret' => $this->secret);
     OAuthStore::instance("2Leg", $options);
     $url = "http://api.twitter.com/1/statuses/home_timeline.format?include_entities=true";
     // this is the URL of the request
     $method = "GET";
     // you can also use POST instead
     $params = null;
     try {
         // Obtain a request object for the request we want to make
         $request = new OAuthRequester($url, $method, $params);
         // Sign the request, perform a curl request and return the results,
         // throws OAuthException2 exception on an error
         // $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
         $result = $request->doRequest();
         $response = $result['body'];
         echo $response;
     } catch (OAuthException2 $e) {
     }
 }
Esempio n. 15
0
function readTimeline($user, $count)
{
    try {
        // Obtain a request object for the request we want to make
        $request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
        $result = $request->doRequest(0);
        parse_str($result['body'], $params);
        // now make the request.
        if ($user === false) {
            $url = TWITTER_PUBLIC_TIMELINE_API;
        } else {
            $url = TWITTER_USER_TIMELINE_API . '?screen_name=' . $user . '&count=' . $count;
        }
        $request = new OAuthRequester($url, 'GET', $params);
        $result = $request->doRequest();
        $response = $result['body'];
    } catch (OAuthException2 $e) {
        $response = "Exception" . $e->getMessage();
    }
    return $response;
}
Esempio n. 16
0
 /**
  * send an api call to yotpo to authenticate and get an access token
  * @return access token
  */
 public function oauthAuthentication()
 {
     if ($this->app_key == null or $this->secret == null) {
         Mage::log('Missing app key or secret');
         return null;
     }
     $yotpo_options = array('consumer_key' => $this->app_key, 'consumer_secret' => $this->secret, 'client_id' => $this->app_key, 'client_secret' => $this->secret, 'grant_type' => 'client_credentials');
     OAuthStore::instance("2Leg", $yotpo_options);
     try {
         $request = new OAuthRequester(self::YOTPO_OAUTH_TOKEN_URL, "POST", $yotpo_options);
         if (!$request) {
             Mage::log('Failed to get token access from yotpo api');
             return null;
         }
         $result = $request->doRequest(0);
         $tokenParams = json_decode($result['body'], true);
         return $tokenParams['access_token'];
     } catch (OAuthException2 $e) {
         Mage::log('error: ' . $e);
         return null;
     }
 }
Esempio n. 17
0
 public function run_query($endpoint, $query_arr)
 {
     if (!$this->apiKey) {
         throw new Semantics3_AuthenticationError('No API key provided.');
     }
     if (!$this->apiSecret) {
         throw new Semantics3_AuthenticationError('No API secret provided.');
     }
     $options = array('consumer_key' => $this->apiKey, 'consumer_secret' => $this->apiSecret);
     OAuthStore::instance("2Leg", $options);
     $url = "https://api.semantics3.com/v1/{$endpoint}?q=" . $query_arr;
     $method = "GET";
     $params = null;
     try {
         $request = new OAuthRequester($url, $method, $params);
         $result = $request->doRequest();
         return $result['body'];
     } catch (OAuthException2 $e) {
         print "\n";
         $error = $e->getMessage();
         print $error . "\n";
     }
 }
Esempio n. 18
0
<?php

//session_destroy();
if (!empty($_SESSION['SFDOCTOR_TOKEN'])) {
    try {
        echo '<pre>GET: ' . $uriProfile . '<br/>';
        print_r('');
        echo '</pre>';
        $tokenResultParams = $_SESSION['SFDOCTOR_TOKEN'];
        $request = new OAuthRequester($uriProfile, 'GET', $tokenResultParams);
        $result = $request->doRequest(0);
        if ($result['code'] == 200) {
            echo '<pre>';
            print_r(json_decode($result['body']));
            echo '</pre>';
            exit;
        } else {
            echo 'Error';
        }
    } catch (OAuthException2 $e) {
        echo '<pre>';
        print_r('Error. Maybe you must login with 65dotor account.');
        echo '</pre>';
        echo '<pre>';
        print_r($e->getMessage());
        echo '</pre>';
        echo '<pre>';
        print_r($e);
        echo '</pre>';
        exit;
    }
Esempio n. 19
0
 /**
  * signs and executes the request
  * @return array ('code'=>int, 'headers'=>array(), 'body'=>string)
  */
 protected function execute($method, $resource, $params = array(), $body = null)
 {
     //remove empty entries from the fields
     $params = $this->removeEmptiesFromArray($params);
     $options = array('consumer_key' => $this->settings->account, 'consumer_secret' => $this->settings->secretkey);
     OAuthStore::instance('2Leg', $options);
     try {
         //print_r($params);
         $url = $this->settings->base_url . '/sites/' . $this->settings->account . $resource;
         $request = new OAuthRequester($url, $method, $params);
         $result = $request->doRequest();
         return $result;
     } catch (OAuthException2 $e) {
         error_log($e->getMessage());
         //throw new Exception('Error. ' . $e->getMessage());
         return array();
     }
 }
Esempio n. 20
0
 /**
  * 
  * signs and executes the request
  *
  * @param string $method HTTP method, e.g. GET, POST, DELETE
  * @param string $resource e.g. /consumptions.json
  * @param array $params query parameters (GET or DELETE)
  * @param array $fields data fields to be encoded as JSON (POST or PUT)
  * @return array ('code'=>int, 'headers'=>array(), 'body'=>string)
  */
 protected function execute($method, $resource, $params = array(), $data = NULL)
 {
     $options = array('consumer_key' => $this->settings->account, 'consumer_secret' => $this->settings->secretkey);
     OAuthStore::instance('2Leg', $options);
     try {
         //print_r($params);
         $url = $this->settings->base_url . '/sites/' . $this->settings->account . $resource;
         if ($method == 'GET' || $method == 'DELETE') {
             $request = new OAuthRequester($url, $method, $params);
         } else {
             if (is_object($data)) {
                 // data is a single item, user or consumption object
                 $body = json_encode($data->getFields());
             } else {
                 if (is_array($data)) {
                     // data is an array of items, users or consumptions
                     $objects = array();
                     foreach ($data as $object) {
                         $objects[] = $object->getFields();
                     }
                     $body = json_encode($objects);
                 }
             }
             $request = new OAuthRequester($url, $method, null, $body);
         }
         $result = $request->doRequest();
         //print_r($result);
         return $result;
     } catch (OAuthException2 $e) {
         error_log($e->getMessage());
         //throw new Exception('Error. ' . $e->getMessage());
         return array();
     }
 }
Esempio n. 21
0
 function synchronize()
 {
     header("Content-Type: text/event-stream\n\n");
     $ALREADY_SEARCHED_PHONES = array();
     $i = 0;
     $st = $this->db->prepare('SELECT audience_phone FROM audience WHERE sync = 0');
     $st->execute($params);
     while ($audience_phone = $st->fetch(PDO::FETCH_ASSOC)) {
         $phone = $audience_phone['audience_phone'];
         if (!array_search($phone, $ALREADY_SEARCHED_PHONES)) {
             array_push($ALREADY_SEARCHED_PHONES, $phone);
             $CONDUCTTR_REQUEST_URL = "https://api.conducttr.com/v1/project/" . CONDUCTTR_PROJECT_ID . "/code?audience_phone=" . $phone;
             $options = array('consumer_key' => CONDUCTTR_CONSUMER_KEY, 'consumer_secret' => CONDUCTTR_CONSUMER_SECRET);
             OAuthStore::instance("2Leg", $options);
             try {
                 $request = new OAuthRequester(CONDUCTTR_REQUEST_TOKEN_URL, $method);
                 $result = $request->doRequest(0);
                 parse_str($result['body'], $params);
                 $request = new OAuthRequester($CONDUCTTR_REQUEST_URL, "GET", $params);
                 $result = $request->doRequest();
                 $response = json_decode($result['body']);
                 if ($response->results[0]->code == $_REQUEST['code']) {
                     $params = array(':audience_phone' => $phone);
                     $st = $this->db->prepare('UPDATE audience SET sync = 1 WHERE audience_phone = :audience_phone');
                     if ($st->execute($params)) {
                         header("Content-Type: text/event-stream\n\n");
                         header("Cache-Control: no-cache");
                         // recommended to prevent caching of event data.
                         echo "id: {$serverTime}" . PHP_EOL;
                         echo "data: {$phone}" . PHP_EOL;
                         echo "retry: 10000" . PHP_EOL;
                         echo PHP_EOL;
                         ob_flush();
                         flush();
                     }
                 }
             } catch (OAuthException2 $e) {
                 echo "Exception" . $e->getMessage();
             }
         }
     }
     sleep(1);
 }
Esempio n. 22
0
 /**
  * Sign the request, perform a curl request and return the results
  * @param string urlStr unsigned URL request
  * @return array ex: array ('code'=>int, 'headers'=>array(), 'body'=>string)
  */
 protected function request($urlStr, $requestMethod = "GET", $params = null)
 {
     //custom headers
     $curlOptions[CURLOPT_HTTPHEADER] = array();
     $curlOptions[CURLOPT_HTTPHEADER][] = "X-Factual-Lib: " . $this->config['factual']['driverversion'];
     if ($requestMethod == "POST") {
         $curlOptions[CURLOPT_HTTPHEADER][] = "Content-Type: " . "application/x-www-form-urlencoded";
     }
     //other curl options
     $curlOptions[CURLOPT_CONNECTTIMEOUT] = $this->connectTimeout;
     //connection timeout
     $curlOptions[CURLOPT_TIMEOUT] = $this->curlTimeout;
     //execution timeout
     // Build request with OAuth request params
     $request = new OAuthRequester($urlStr, $requestMethod, $params);
     //check & flag debug
     if ($this->debug) {
         $request->debug = true;
         //set debug on oauth request object for curl output
     }
     //Make request
     try {
         $callStart = microtime(true);
         $result = $request->doRequest(0, $curlOptions);
         $callEnd = microtime(true);
     } catch (Exception $e) {
         //catch client exception
         $info['request']['encoded'] = $urlStr;
         $info['request']['unencoded'] = urldecode($urlStr);
         $info['driver'] = $this->config['factual']['driverversion'];
         $info['method'] = $requestMethod;
         $info['message'] = "Service exception (likely a problem on the server side). Client did not connect and returned '" . $e->getMessage() . "'";
         $factualE = new FactualApiException($info);
         throw $factualE;
     }
     $result['request'] = $urlStr;
     //pass request string onto response
     $result['tablename'] = $this->lastTable;
     //pass table name to result object (not available with rawGet())
     //catch server exception & load up on debug data
     if ($result['code'] >= 400 | $this->debug) {
         $body = json_decode($result['body'], true);
         //get a boatload of debug data
         $info['code'] = $result['code'];
         $info['version'] = $body['version'];
         $info['status'] = $body['status'];
         $info['returnheaders'] = $result['headers'];
         $info['driver'] = $this->config['factual']['driverversion'];
         $info['method'] = $requestMethod;
         if (isset($body['error_type'])) {
             $info['error_type'] = $body['error_type'];
         }
         if (isset($body['message'])) {
             $info['message'] = $body['message'];
         }
         if (isset($result['request'])) {
             $info['request']['encoded'] = $result['request'];
             $info['request']['unencoded'] = urldecode($result['request']);
         }
         if (isset($result['tablename'])) {
             $info['tablename'] = $result['tablename'];
         }
         //add post body to debug
         if ($params) {
             $info['body'] = $params;
         }
         //add execution time
         $info['time'] = $callEnd - $callStart;
         //write debug info to stderr if debug mode on
         if ($this->debug) {
             //add only select curl debug information
             unset($request->curlInfo['url']);
             unset($request->curlInfo['content_type']);
             unset($request->curlInfo['certinfo']);
             unset($request->curlInfo['redirect_time']);
             unset($request->curlInfo['redirect_time']);
             unset($request->curlInfo['filetime']);
             unset($request->curlInfo['ssl_verify_result']);
             $info['curl'] = $request->curlInfo;
             $info = array_filter($info);
             //remove empty elements for readability
             file_put_contents('php://stderr', "Debug " . print_r($info, true));
         }
         //chuck exception
         if ($result['code'] >= 400) {
             $factualE = new FactualApiException($info);
             throw $factualE;
         }
     }
     //check for deprecation, add to stdout
     if ($result['code'] == 301) {
         file_put_contents('php://stderr', "Entity is deprecated");
     }
     return $result;
 }
Esempio n. 23
0
 public function apisignedrequestAction()
 {
     $service = new Ml_Model_Service();
     $this->_helper->loadOauthstore->setinstance();
     require EXTERNAL_LIBRARY_PATH . '/oauth-php/library/OAuthRequester.php';
     $userId = $service->getInput("User ID");
     $requestUri = $service->getInput("Request URI");
     $httpMethod = $service->getInput("HTTP Method");
     // Parameters, appended to the request depending on the request method.
     // Will become the POST body or the GET query string.
     $numOfParams = $service->getInput("Number of params");
     $params = array();
     for ($n = 0; $n < $numOfParams; $n++) {
         $param = $service->getInput("Param");
         $value = $service->getInput("Value");
         $params[$param] = $value;
     }
     // Obtain a request object for the request we want to make
     $req = new OAuthRequester($requestUri, $httpMethod, $params);
     try {
         // Sign the request, perform a curl request and return the results,
         //throws OAuthException exception on an error
         $result = $req->doRequest($userId);
         //$result is an array with the content:
         //array ('code'=>int, 'headers'=>array(), 'body'=>string)
         print_r($result);
     } catch (Exception $e) {
         print_r($e->getMessage());
     }
 }
Esempio n. 24
0
 public function makeOAuthRequest($request, $method = null, $params = null, $body = null, $files = null)
 {
     $request = new OAuthRequester($request, $method, $params, $body, $files);
     return $request->doRequest($this->oauth_user_id);
 }
Esempio n. 25
0
require dirname(__FILE__) . '/fx.php';
if ($user_id === false) {
    ?>
<form method="post" action="/follows/manage/">
	<input type="text" style="width:15em;" name="username" />
	<input type="submit" value="Login" />
</form>
<?php 
    return;
}
// Obtain a request object for the request we want to make
$req = new OAuthRequester($server['server_uri'] . '/direct_messages.json', 'GET', array());
// Sign the request, perform a curl request and return the results, throws OAuthException exception on an error
try {
    $result = $req->doRequest($user_id);
} catch (OAuthException $e) {
    header('Location: /follows/manage/register');
    exit;
}
$page = 'follows';
$title = 'Follows';
require dirname(__FILE__) . '/../../header.tpl.php';
echo '<h1>Direct Messages</h1>';
echo '<p>Since this is currently just an OAuth test this just shows the results of a call to get your direct messages. This is an authenticated request so it serves to prove the point but has nothing to do with this application.</p>';
$result = json_decode($result['body']);
if (!$result) {
    die('Invalid response');
}
foreach ($result as $msg) {
    echo '<div style="clear:both; margin-bottom: 0.5em;">';
Esempio n. 26
0
 function oauth_call($method, $matchphrase, $phone)
 {
     if ($phone != "") {
         $CONDUCTTR_REQUEST_URL = "https://api.conducttr.com/v1/project/" . CONDUCTTR_PROJECT_ID . "/" . $matchphrase . "?audience_phone=" . $phone;
     } else {
         $CONDUCTTR_REQUEST_URL = "https://api.conducttr.com/v1/project/" . CONDUCTTR_PROJECT_ID . "/" . $matchphrase;
     }
     $options = array('consumer_key' => CONDUCTTR_CONSUMER_KEY, 'consumer_secret' => CONDUCTTR_CONSUMER_SECRET);
     OAuthStore::instance("2Leg", $options);
     try {
         $secrets = array('signature_methods' => array('HMAC-SHA1'), 'token' => CONDUCTTR_ACCESS_TOKEN, 'token_secret' => CONDUCTTR_ACCESS_TOKEN_SECRET, 'nonce' => md5(md5(date('H:i:s')) . md5(time())), 'timestamp' => time(), 'consumer_key' => CONDUCTTR_CONSUMER_KEY, 'consumer_secret' => CONDUCTTR_CONSUMER_SECRET);
         $request = new OAuthRequester($CONDUCTTR_REQUEST_URL, $method, $secrets);
         $result = $request->doRequest();
         return json_decode($result['body']);
     } catch (OAuthException2 $e) {
         echo "Exception" . $e->getMessage();
     }
 }
 DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
 UNINTERRUPTED OR ERROR FREE.
*/
include_once "vendor/oauth/OAuthStore.php";
include_once "vendor/oauth/OAuthRequester.php";
//- Prepare the PHP OAuth for consuming our Oxygen service
$options = array('consumer_key' => ConsumerKey, 'consumer_secret' => ConsumerSecret, 'server_uri' => BaseUrl, 'request_token_uri' => BaseUrl . 'OAuth/RequestToken', 'authorize_uri' => BaseUrl . 'OAuth/Authorize', 'access_token_uri' => BaseUrl . 'OAuth/AccessToken');
OAuthStore::instance('Session', $options);
$fname = realpath(dirname(__FILE__)) . '/access_token.txt';
$access = unserialize(file_get_contents($fname));
//- To disable the SSL check to avoid an exception with invalidate certificate on the server,
//- use the cURL CURLOPT_SSL_VERIFYPEER option and set it to false.
//- Refresh the token
try {
    OAuthStore::instance()->addServerToken(ConsumerKey, 'access', $access['oauth_token'], $access['oauth_token_secret'], 0, $options);
    $request = new OAuthRequester($options['access_token_uri'], 'POST', $access);
    $ret = $request->doRequest(0, array(CURLOPT_SSL_VERIFYPEER => 0));
    $ret = explode('&', $ret['body']);
    foreach ($ret as $key => $value) {
        $entry = explode('=', $value);
        $access[$entry[0]] = rawurldecode($entry[1]);
    }
    //- In this sample, we save the token to a file
    $fname = realpath(dirname(__FILE__)) . '/access_token.txt';
    file_put_contents($fname, serialize($access));
} catch (Exception $e) {
    echo "OAuth/AccessToken\n", 'Caught exception: ', $e->getMessage(), "\n";
    exit;
}
//- Done
//exit ;
Esempio n. 28
0
        $options = array('oauth_as_header' => false);
        // get a request token
        $tokenResultParams = OAuthRequester::requestRequestToken(OPERA_CONSUMER_KEY, 0, $getAuthTokenParams, 'POST', $options);
        $_SESSION['oauth_token'] = $tokenResultParams['token'];
        //  redirect to the opera authorization page, they will redirect back
        header("Location: " . OPERA_AUTHORIZE_URL . "?oauth_token=" . $tokenResultParams['token']);
    } else {
        //  STEP 2:  Get an access token
        try {
            OAuthRequester::requestAccessToken(OPERA_CONSUMER_KEY, $_SESSION['oauth_token'], 0, 'POST', $options = array('oauth_verifier' => $_GET['oauth_verifier']));
        } catch (OAuthException2 $e) {
            var_dump($e);
            // Something wrong with the oauth_token.
            // Could be:
            // 1. Was already ok
            // 2. We were not authorized
            return;
        }
        // make the docs requestrequest.
        $request = new OAuthRequester("http://my.opera.com/community/api/users/status.pl", 'GET');
        $result = $request->doRequest(0, array(CURLOPT_HTTPHEADER => array('Accept: application/json')));
        if ($result['code'] == 200) {
            var_dump($result['body']);
        } else {
            echo 'Error';
        }
    }
} catch (OAuthException2 $e) {
    echo "OAuthException:  " . $e->getMessage();
    var_dump($e);
}
Esempio n. 29
0
 /**
  * Returns an array with user infos from the OAuth provier.
  *
  * @return array The current user array
  */
 public function getOauthUser()
 {
     if (empty($this->user)) {
         $request = new \OAuthRequester($this->userUrl, "GET", $_GET);
         $result = $request->doRequest();
         $doc = new \DOMDocument();
         $doc->loadXML($result['body']);
         $xPath = new \DOMXpath($doc);
         $userTag = $doc->getElementsByTagName("user")->item(0);
         $this->user['name'] = $userTag->getAttribute('display_name');
         $this->user['id'] = $userTag->getAttribute('id');
         $imgTags = $xPath->query("//user/img");
         if ($imgTags->length > 0) {
             $this->user['pic_url'] = $imgTags->item(0)->getAttribute('href');
         }
     }
     return $this->user;
 }
Esempio n. 30
0
 /**
  * Execute client WS request with token authentication
  * @param string $functionname
  * @param array $params
  * @param bool $json
  * @return mixed
  */
 public function call($functionname, $params, $json = false)
 {
     if ($this->type == 'oauth') {
         $url = $this->serverurl . '?wsfunction=' . $functionname;
         $body = '';
         $options = array();
         if ($json) {
             $url .= '&alt=json';
             $body = json_encode($params);
         } else {
             $body = format_postdata_for_curlcall($params);
         }
         // setup the client side OAuth
         $oauth_options = array('consumer_key' => $this->consumer->consumer_key, 'consumer_secret' => $this->consumer->consumer_secret, 'server_uri' => 'http://example.com/webservice/rest/server.php', 'request_token_uri' => 'http://example.com/maharadev/webservice/oauthv1.php/request_token', 'authorize_uri' => 'http://example.com/webservice/oauthv1.php/authorize', 'access_token_uri' => 'http://example.com/webservice/oauthv1.php/access_token');
         $store = OAuthStore::instance("Session", $oauth_options, true);
         $store->addServerToken($this->consumer->consumer_key, 'access', $this->token['token'], $this->token['token_secret'], 1);
         $request = new OAuthRequester($url, 'POST', $options, $body);
         $result = $request->doRequest(0);
         if ($result['code'] != 200) {
             throw new Exception('REST OAuth error: ' . var_export($result, true));
         }
         $result = $result['body'];
         if ($json) {
             $values = (array) json_decode($result, true);
             return $values;
         }
     } else {
         // do a JSON based call - just soooo easy compared to XML/SOAP
         if ($json) {
             $data = json_encode($params);
             $url = $this->serverurl . '?' . $this->auth . '&wsfunction=' . $functionname . '&alt=json';
             $result = file_get_contents($url, false, stream_context_create(array('http' => array('method' => 'POST', 'header' => "Content-Type: application/json\r\nConnection: close\r\nContent-Length: " . strlen($data) . "\r\n", 'content' => $data))));
             $values = (array) json_decode($result, true);
             return $values;
         }
         // default to parsing HTTP parameters
         $result = webservice_download_file_content($this->serverurl . '?' . $this->auth . '&wsfunction=' . $functionname, null, $params);
     }
     //after the call, for those not using JSON, parseout the results
     // from REST XML response to PHP
     $xml2array = new webservice_xml2array($result);
     $raw = $xml2array->getResult();
     if (isset($raw['EXCEPTION'])) {
         $debug = isset($raw['EXCEPTION']['DEBUGINFO']) ? $raw['EXCEPTION']['DEBUGINFO']['#text'] : '';
         throw new Exception('REST error: ' . $raw['EXCEPTION']['MESSAGE']['#text'] . ' (' . $raw['EXCEPTION']['@class'] . ') ' . $debug);
     }
     $result = array();
     if (isset($raw['RESPONSE'])) {
         $node = $raw['RESPONSE'];
         if (isset($node['MULTIPLE'])) {
             $result = self::recurse_structure($node['MULTIPLE']);
         } else {
             if (isset($raw['RESPONSE']['SINGLE'])) {
                 $result = $raw['RESPONSE']['SINGLE'];
             } else {
                 // empty result ?
                 $result = $raw['RESPONSE'];
             }
         }
     }
     return $result;
 }