コード例 #1
0
ファイル: OauthPresenter.php プロジェクト: osmcz/website
 protected function getUserDetailsAndLoginUser()
 {
     $this->oauth->setToken($this->getSession('oauth')->token, $this->getSession('oauth')->secret);
     //fetch user datail XML
     $this->oauth->fetch(self::API_URL . "user/details");
     $user_details = $this->oauth->getLastResponse();
     $xml = simplexml_load_string($user_details);
     $user = array('id' => $xml->user['id'], 'username' => $xml->user['display_name'], 'account_created' => $xml->user['account_created'], 'img' => $xml->user->img['href'], 'changesets' => $xml->user->changesets['count'], 'traces' => $xml->user->traces['count'], 'description' => $xml->user->description, 'home_lat' => $xml->user->home['lat'], 'home_lon' => $xml->user->home['lon'], 'last_login' => date("Y-m-d H:i:s"));
     // convert xml-nodes to strings
     foreach ($user as &$val) {
         $val = strval($val);
     }
     // update db
     $row = dibi::fetch('SELECT * FROM users WHERE id = %i', $user['id']);
     if ($row) {
         //better dont change usernames, we use it as primary key
         unset($user['username']);
         dibi::query('UPDATE users SET ', $user, ' WHERE id = %i', $user['id']);
     } else {
         $user['first_login'] = new DateTime();
         dibi::query('INSERT INTO users ', $user);
     }
     // load complete row from db
     $dbuser = dibi::fetch('SELECT * FROM users WHERE id = %i', $user['id']);
     if ($dbuser['webpages'] != 'admin' and $dbuser['webpages'] != 'all') {
         $dbuser['webpages'] = '14' . ($dbuser['webpages'] ? ',' : '') . $dbuser['webpages'];
     }
     $this->user->login(new Identity($dbuser['username'], array($dbuser['webpages'] == 'admin' ? 'admin' : 'user'), $dbuser));
     // remove all tokens - TODO if tokens to be used, save them in DB
     $this->redirectUrl('//' . $_SERVER['HTTP_HOST'] . $this->getSession('oauth')->back_url);
 }
コード例 #2
0
 function call($command)
 {
     session_start();
     if (!isset($_GET['oauth_token']) && $_SESSION['state'] == 1) {
         $_SESSION['state'] = 0;
     }
     try {
         $oauth = new \OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         $oauth->enableDebug();
         if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
             $request_token_info = $oauth->getRequestToken($this->request_url);
             $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
             $_SESSION['state'] = 1;
             header('Location: ' . $this->authorize_url . '?oauth_token=' . $request_token_info['oauth_token']);
             exit;
         } else {
             if ($_SESSION['state'] == 1) {
                 $oauth->setToken($_GET['oauth_token'], $_SESSION['secret']);
                 $access_token_info = $oauth->getAccessToken($this->access_token_url);
                 error_log("acc token info " . $access_token_info, 1, "*****@*****.**");
                 $_SESSION['state'] = 2;
                 $_SESSION['token'] = $access_token_info['oauth_token'];
                 $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
             }
         }
         $oauth->setToken($_SESSION['token'], $_SESSION['secret']);
         $oauth->fetch("{$this->api_url}{$command}");
         $json = json_decode($oauth->getLastResponse());
     } catch (\OAuthException $E) {
         return $E->lastResponse;
     }
     return $json;
 }
コード例 #3
0
 /**
  * @param string $consumerKey
  * @param string $consumerSecret
  * @param string $accessToken
  * @param string$accessSecret
  * @return void
  * @throws Exception
  */
 public function setOAuthClient($consumerKey, $consumerSecret, $accessToken, $accessSecret)
 {
     if (!class_exists('OAuth')) {
         throw new Exception('The OAuth PHP module must be present to perform OAuth requests.', 1424003541);
     }
     $this->oAuthClient = new \OAuth($consumerKey, $consumerSecret);
     $this->oAuthClient->setToken($accessToken, $accessSecret);
 }
コード例 #4
0
ファイル: Twitter.php プロジェクト: joksnet/php-old
 protected function connect()
 {
     $this->oauth->setToken($this->token, $this->tokenSecret);
     $accessToken = $this->oauth->getAccessToken(self::URL_ACCESS . (Request::hasQuery('oauth_verifier') ? '?oauth_verifier=' . Request::getQuery('oauth_verifier') : ''));
     $this->state = self::STATE_CONNECTED;
     $this->token = $accessToken['oauth_token'];
     $this->tokenSecret = $accessToken['oauth_token_secret'];
     Session::set('Twitter_Token', $this->token);
     Session::set('Twitter_TokenSecret', $this->tokenSecret);
     Session::set('Twitter_State', $this->state);
     TwCensus::redirect('/');
 }
コード例 #5
0
ファイル: rdio.php プロジェクト: rdio/rdio-php
 private function _getOAuth()
 {
     $oauth = new OAuth($this->key, $this->secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
     if (isset($_SESSION['access_key']) && isset($_SESSION['access_secret'])) {
         $oauth->setToken($_SESSION['access_key'], $_SESSION['access_secret']);
     } else {
         if (isset($_SESSION['request_key']) && isset($_SESSION['request_secret'])) {
             $oauth->setToken($_SESSION['request_key'], $_SESSION['request_secret']);
         }
     }
     return $oauth;
 }
コード例 #6
0
 /**
  * Call Twitter API methods
  * 
  * @param string $method
  * @param array $accessToken
  * @param OAuth $oauth
  * @param array $params (include oauth_method = POST/GET if need to override)
  * @return string
  */
 public static function call($method, $accessToken = null, OAuth $oauth, $params = array())
 {
     $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
     $resource = sprintf('%s/%s.json', 'https://api.twitter.com/1.1', $method);
     // POST or GET
     $method = OAUTH_HTTP_METHOD_GET;
     if (isset($params['oauth_method'])) {
         if ('POST' == strtoupper($params['oauth_method'])) {
             $method = OAUTH_HTTP_METHOD_POST;
         }
     } else {
         // If resource contains update, retweet (not retweets), filter, destroy, new, create - then POST not GET
         foreach (array('update', 'retweet/', 'filter', 'destroy', 'new', 'create') as $resourcePart) {
             if (false !== strpos($resource, $resourcePart)) {
                 $method = OAUTH_HTTP_METHOD_POST;
                 break;
             }
         }
     }
     if ($method == OAUTH_HTTP_METHOD_GET) {
         if (count($params)) {
             $resource = sprintf('%s?%s', $resource, http_build_query($params));
         }
         $params = null;
     }
     // Get back bad response if don't specify method where needs to be POST
     if ($oauth->fetch($resource, $params, $method)) {
         return $oauth->getLastResponse();
     } else {
         return null;
     }
 }
コード例 #7
0
 /** 
  * Retrive Twitter auth data in Cookie set by Twitter JSSDK.
  * 
  * @param CakeRequest $request Request object.
  * @return mixed Either false or an object of user information of Twitter
  */
 public function getUser(CakeRequest $request)
 {
     $api = Configure::read('SocialSignIn.API.Twitter');
     // $request_token_url = 'http://api.twitter.com/oauth/request_token';
     // $access_token_url = "http://twitter.com/oauth/access_token";
     // $authorize_url="http://twitter.com/oauth/authorize";
     $session_name = $this->settings['session'];
     $s = SessionComponent::read($session_name);
     // if already authenticated, user object is stored in the session
     if (isset($s['User']) && is_object($s['User'])) {
         return $s['User'];
     }
     if (isset($request->query['oauth_token']) && isset($s['secret'])) {
         $oauth = new OAuth($this->settings['consumer_key'], $this->settings['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         $oauth->setToken($request->query['oauth_token'], $s['secret']);
         $access_token_info = $oauth->getAccessToken($api['access_token_url']);
         if ($access_token_info['oauth_token']) {
             $oauth->setToken($access_token_info['oauth_token'], $access_token_info['oauth_token_secret']);
             $data = $oauth->fetch($api['fetch_url']);
             $user = json_decode($oauth->getLastResponse());
             return $user;
         }
     }
     return false;
 }
コード例 #8
0
 public static function authorize($consumer_key, $consumer_secret, $request_token, $request_secret)
 {
     $oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
     $oauth->setToken($request_token, $request_secret);
     $access_token_info = $oauth->getAccessToken(GOOGLE_OAUTH_ACCESS_TOKEN_API);
     return array("access_token" => $access_token_info["oauth_token"], "access_secret" => $access_token_info["oauth_token_secret"]);
 }
コード例 #9
0
ファイル: methods.php プロジェクト: RichieDupes/PeoplePods
function getTwitterFriendIds($user)
{
    $cacheExpire = 24 * 60 * 60;
    $POD = $user->POD;
    $key = $POD->libOptions('twitter_api');
    $secret = $POD->libOptions('twitter_secret');
    $friends = array();
    if ($user->get('twitter_token')) {
        if ($user->get('twitter_list') != '' && time() - $user->get('twitter_list_generated') < $cacheExpire) {
            $twoots = json_decode($user->get('twitter_list'));
            foreach ($twoots as $f) {
                $friends[] = $f;
            }
        } else {
            try {
                $oauth = new OAuth($key, $secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
                $oauth->enableDebug();
                // This will generate debug output in your error_log
                $oauth->setToken($user->get('twitter_token'), $user->get('twitter_secret'));
                $oauth->fetch('https://twitter.com/friends/ids.json?cursor=-1&user_id=' . $user->get('twitter_id'));
                $json = json_decode($oauth->getLastResponse());
            } catch (Exception $e) {
            }
            // contains the first 5000 twitter friends
            foreach ($json->ids as $id) {
                $friends[] = $id;
            }
            $user->addMeta('twitter_list', json_encode($friends));
            $user->addMeta('twitter_list_generated', time());
        }
    }
    return $friends;
}
コード例 #10
0
ファイル: external_post.php プロジェクト: brainsqueezer/fffff
function twitter_post($text, $short_url)
{
    global $globals;
    if (!class_exists("OAuth")) {
        syslog(LOG_NOTICE, "Meneame: pecl/oauth is not installed");
        return;
    }
    if (!$globals['twitter_consumer_key'] || !$globals['twitter_consumer_secret'] || !$globals['twitter_token'] || !$globals['twitter_token_secret']) {
        syslog(LOG_NOTICE, "Meneame: consumer_key, consumer_secret, token, or token_secret not defined");
        return;
    }
    $maxlen = 140 - 24;
    //strlen($short_url);
    $msg = mb_substr(text_to_summary(html_entity_decode($text), $maxlen), 0, $maxlen) . ' ' . $short_url;
    $req_url = 'https://api.twitter.com/oauth/request_token';
    $acc_url = 'https://api.twitter.com/oauth/access_token';
    $authurl = 'https://api.twitter.com/oauth/authorize';
    $api_url = 'https://api.twitter.com/1.1/statuses/update.json';
    $oauth = new OAuth($globals['twitter_consumer_key'], $globals['twitter_consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
    $oauth->debug = 1;
    $oauth->setToken($globals['twitter_token'], $globals['twitter_token_secret']);
    $api_args = array("status" => $msg, "empty_param" => NULL);
    /* No using geo yet
    	if (isset($entry['lat'])) {
    		$api_args['lat'] = $entry['lat'];
    		$api_args['long'] = $entry['long'];
    	}
    	*/
    try {
        $oauth->fetch($api_url, $api_args, OAUTH_HTTP_METHOD_POST, array("User-Agent" => "pecl/oauth"));
    } catch (Exception $e) {
        syslog(LOG_INFO, 'Menéame, Twitter caught exception: ' . $e->getMessage() . " in " . basename(__FILE__) . "\n");
    }
}
コード例 #11
0
ファイル: evernote.php プロジェクト: rizumita/fuel-evernote
 public static function getTokenCredentials()
 {
     $result = array();
     try {
         $access_token_url = \Fuel\Core\Config::get('evernote.evernote_server') . '/oauth';
         $oauth_verifier = \Fuel\Core\Session::get('oauthVerifier');
         $oauth = new \OAuth(\Fuel\Core\Config::get('evernote.consumer_key'), \Fuel\Core\Config::get('evernote.consumer_secret'));
         $request_token = \Fuel\Core\Session::get('requestToken');
         $request_token_secret = \Fuel\Core\Session::get('requestTokenSecret');
         $oauth->setToken($request_token, $request_token_secret);
         $access_token_info = $oauth->getAccessToken($access_token_url, null, $oauth_verifier);
         if ($access_token_info) {
             $result['status'] = 'success';
             $result['access_token'] = $access_token_info['oauth_token'];
             $result['access_token_secret'] = $access_token_info['oauth_token_secret'];
             $result['shard_id'] = $access_token_info['edam_shard'];
             $result['user_id'] = $access_token_info['edam_userId'];
         } else {
             $result['status'] = 'failure';
         }
     } catch (\OAuthException $e) {
         $result['status'] = 'failure';
     }
     return $result;
 }
コード例 #12
0
 public function REST_Request($callbackUrl, $url, $method, $data = array())
 {
     /**
      * Example of simple product POST using Admin account via Magento REST API. OAuth authorization is used
      */
     $callbackUrl = $callbackUrl;
     $temporaryCredentialsRequestUrl = $this->conf['magento_host'] . "/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
     $adminAuthorizationUrl = $this->conf['magento_host'] . '/admin/oauth_authorize';
     $accessTokenRequestUrl = $this->conf['magento_host'] . '/oauth/token';
     $apiUrl = $this->conf['magento_host'] . '/api/rest';
     $consumerKey = $this->conf['magentosoap_consumerKey'];
     $consumerSecret = $this->conf['magentosoap_consumerSecret'];
     $AccessToken = $this->conf["magentosoap_AccessToken"];
     $AccessSecret = $this->conf["magentosoap_AccessSecret"];
     try {
         //$_SESSION['state'] = 2;
         $authType = 2 == 2 ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
         $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
         $oauthClient->enableDebug();
         $oauthClient->disableSSLChecks();
         $oauthClient->setToken($AccessToken, $AccessSecret);
         $resourceUrl = $apiUrl . $url;
         $oauthClient->fetch($resourceUrl, $data, strtoupper($method), array("Content-Type" => "application/json", "Accept" => "*/*"));
         //$oauthClient->fetch($resourceUrl);
         $ret = json_decode($oauthClient->getLastResponse());
         $ret = array("error" => 0, "data" => $ret);
         return $ret;
     } catch (OAuthException $e) {
         $ret = array("error" => 1, "message" => "Checking quantity failed");
         return $ret;
     }
 }
コード例 #13
0
ファイル: Twitter.php プロジェクト: hubgit/libapi
 function authorize()
 {
     $oauth = new OAuth(Config::get('TWITTER_CONSUMER_KEY'), Config::get('TWITTER_CONSUMER_SECRET'), OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
     $oauth->enableDebug();
     try {
         $request_token = $oauth->getRequestToken($this->request_token_url);
     } catch (OAuthException $e) {
         debug($oauth->debugInfo);
     }
     $url = $this->authorize_url . '?' . http_build_query(array('oauth_token' => $request_token['oauth_token'], 'callback_url'));
     print 'Authorize: ' . $url . "\n";
     system(sprintf('open %s', escapeshellarg($url)));
     fwrite(STDOUT, "Enter the PIN: ");
     $verifier = trim(fgets(STDIN));
     //$oauth->setToken($token, $request_token['oauth_token_secret']);
     //$access_token = $oauth->getAccessToken($this->access_token_url);
     $oauth->setToken($request_token['oauth_token'], $request_token['oauth_token_secret']);
     try {
         $access_token = $oauth->getAccessToken($this->access_token_url, NULL, $verifier);
     } catch (OAuthException $e) {
         debug($oauth->debugInfo);
     }
     printf("'TWITTER_TOKEN' => '%s',\n'TWITTER_TOKEN_SECRET' => '%s',\n", $access_token['oauth_token'], $access_token['oauth_token_secret']);
     exit;
 }
コード例 #14
0
ファイル: Client.php プロジェクト: slowmotion/readerself
 public function getAccessToken($oauthToken, $oauthTokenSecret, $oauthVerifier)
 {
     $oauth = new \OAuth($this->consumerKey, $this->consumerSecret);
     $oauth->setToken($oauthToken, $oauthTokenSecret);
     $accessToken = $oauth->getAccessToken($this->getEndpoint('oauth'), null, $oauthVerifier);
     $this->token = $accessToken['oauth_token'];
     return $accessToken;
 }
コード例 #15
0
ファイル: connect.php プロジェクト: napthats/rtter_js_php
function getUserInfo($token, $secret)
{
    $oauth = new OAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
    $oauth->setToken($token, $secret);
    $oauth->fetch('http://twitter.com/account/verify_credentials.json');
    $buf = $oauth->getLastResponse();
    return json_decode($buf, true);
}
 public function GetReportsResponse($requestParameters, $requestBody, $oauthRequestUri)
 {
     $this->context->IppConfiguration->Logger->CustomLogger->Log(TraceLevel::Info, "Called PrepareRequest method");
     // This step is required since the configuration settings might have been changed.
     $this->RequestCompressor = CoreHelper::GetCompressor($this->context, true);
     $this->ResponseCompressor = CoreHelper::GetCompressor($this->context, false);
     $this->RequestSerializer = CoreHelper::GetSerializer($this->context, true);
     $this->ResponseSerializer = CoreHelper::GetSerializer($this->context, false);
     // Determine dest URI
     $requestUri = '';
     if ($requestParameters->ApiName) {
         // Example: "https://appcenter.intuit.com/api/v1/Account/AppMenu"
         $requestUri = $this->context->baseserviceURL . $requestParameters->ApiName;
     } else {
         if ($oauthRequestUri) {
             // Prepare the request Uri from base Uri and resource Uri.
             $requestUri = $oauthRequestUri;
         } else {
             if ($requestParameters->ResourceUri) {
                 $requestUri = $this->context->baseserviceURL . $requestParameters->ResourceUri;
             } else {
             }
         }
     }
     $oauth = new OAuth($this->context->requestValidator->ConsumerKey, $this->context->requestValidator->ConsumerSecret);
     $oauth->setToken($this->context->requestValidator->AccessToken, $this->context->requestValidator->AccessTokenSecret);
     $oauth->enableDebug();
     $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
     $oauth->disableSSLChecks();
     $httpHeaders = array();
     if ('QBO' == $this->context->serviceType || 'QBD' == $this->context->serviceType) {
         // IDS call
         $httpHeaders = array('accept' => 'application/json');
         // Log Request Body to a file
         $this->RequestLogging->LogPlatformRequests($requestBody, $requestUri, $httpHeaders, TRUE);
         if ($this->ResponseCompressor) {
             $this->ResponseCompressor->PrepareDecompress($httpHeaders);
         }
     } else {
         // IPP call
         $httpHeaders = array('accept' => 'application/json');
     }
     try {
         $OauthMethod = OAUTH_HTTP_METHOD_GET;
         $oauth->fetch($requestUri, $requestBody, $OauthMethod, $httpHeaders);
     } catch (OAuthException $e) {
         //echo "ERROR:\n";
         //print_r($e->getMessage()) . "\n";
         list($response_code, $response_xml, $response_headers) = $this->GetOAuthResponseHeaders($oauth);
         $this->RequestLogging->LogPlatformRequests($response_xml, $requestUri, $response_headers, FALSE);
         return FALSE;
     }
     list($response_code, $response_xml, $response_headers) = $this->GetOAuthResponseHeaders($oauth);
     // Log Request Body to a file
     $this->RequestLogging->LogPlatformRequests($response_xml, $requestUri, $response_headers, FALSE);
     return array($response_code, $response_xml);
 }
コード例 #17
0
 /**
  * Calls Netflix API methods
  *
  * @static
  * @param $method
  * @param null $accessToken
  * @param OAuth $oauth
  * @param array $params
  * @return string
  */
 public static function call($method, $accessToken = null, OAuth $oauth, $params = array())
 {
     $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
     $resource = sprintf('%s/%s?output=json', 'http://api.netflix.com', $method);
     if (count($params)) {
         $resource = sprintf('%s&%s', $resource, http_build_query($params));
     }
     if ($oauth->fetch($resource)) {
         return $oauth->getLastResponse();
     }
 }
コード例 #18
0
 /**
  * Calls Vimeo methods:
  * @see http://vimeo.com/api/docs/methods
  * 
  * @param String $method = Vimeo method to be called
  * @param Array $accessToken 
  * @param OAuth $oauth
  * @param Array $params - additional parameters required for Vimeo method
  * @return String Json string
  */
 public static function call($method, $accessToken = null, OAuth $oauth, $params = array())
 {
     if ($accessToken) {
         $oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
     }
     $resource = sprintf('%s?method=%s&format=json', 'http://vimeo.com/api/rest/v2/', $method);
     if (count($params)) {
         $resource = sprintf('%s&%s', $resource, http_build_query($params));
     }
     if ($oauth->fetch($resource)) {
         return $oauth->getLastResponse();
     }
 }
コード例 #19
0
 function __construct()
 {
     // In state=1 the next request should include an oauth_token.
     // If it doesn't go back to 0
     if (!isset($_GET['oauth_token']) && $_SESSION['state'] == 1) {
         $_SESSION['state'] = 0;
     }
     try {
         $oauth = new OAuth(self::CONSKEY, self::CONSSEC, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         $oauth->enableDebug();
         if ($_SESSION['state'] != 2) {
             if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
                 $queryString = http_build_query(array('scope' => 'https://www.googleapis.com/auth/latitude', 'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
                 $requestToken = $oauth->getRequestToken(self::REQ_URL . '?' . $queryString);
                 $_SESSION['secret'] = $requestToken['oauth_token_secret'];
                 $_SESSION['state'] = 1;
                 $queryString = http_build_query(array('oauth_token' => $requestToken['oauth_token'], 'domain' => $_SERVER['HTTP_HOST'], 'location' => 'all', 'granularity' => 'best'));
                 header('Location: ' . self::AUTH_URL . '?' . $queryString);
                 exit;
             } else {
                 if ($_SESSION['state'] == 1) {
                     $oauth->setToken($_GET['oauth_token'], $_SESSION['secret']);
                     $accessToken = $oauth->getAccessToken(self::ACC_URL);
                     $_SESSION['state'] = 2;
                     $_SESSION['token'] = $accessToken['oauth_token'];
                     $_SESSION['secret'] = $accessToken['oauth_token_secret'];
                 }
             }
         }
         $oauth->setToken($_SESSION['token'], $_SESSION['secret']);
     } catch (OAuthException $e) {
         trigger_error("OAuth fail: " . print_r($e, true));
         print "Oh dear, something failed during the OAuth handshake with google!";
         exit;
     }
     $this->oauth = $oauth;
 }
コード例 #20
0
function twitter_post($auth, $text, $short_url, $image = false)
{
    global $globals;
    if (empty($auth['twitter_token']) || empty($auth['twitter_token_secret']) || empty($auth['twitter_consumer_key']) || empty($auth['twitter_consumer_secret'])) {
        return false;
    }
    if (!class_exists("OAuth")) {
        syslog(LOG_NOTICE, "Meneame: pecl/oauth is not installed");
        return;
    }
    if (!$auth['twitter_consumer_key'] || !$auth['twitter_consumer_secret'] || !$auth['twitter_token'] || !$auth['twitter_token_secret']) {
        syslog(LOG_NOTICE, "Meneame: consumer_key, consumer_secret, token, or token_secret not defined");
        return;
    }
    $req_url = 'https://api.twitter.com/oauth/request_token';
    $acc_url = 'https://api.twitter.com/oauth/access_token';
    $authurl = 'https://api.twitter.com/oauth/authorize';
    $api_url = 'https://api.twitter.com/1.1/statuses/update.json';
    $api_media_url = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
    $api_args = array("empty_param" => NULL);
    $maxlen = 140 - 24;
    // minus the url length
    if ($image) {
        $maxlen -= 24;
        echo "Adding image: {$image}\n";
        $api_args['@media[]'] = '@' . $image;
        $url = $api_media_url;
    } else {
        $url = $api_url;
    }
    $msg = mb_substr(text_to_summary(html_entity_decode($text), $maxlen), 0, $maxlen);
    $msg_full = $msg . ' ' . $short_url;
    $api_args["status"] = $msg_full;
    $oauth = new OAuth($auth['twitter_consumer_key'], $auth['twitter_consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
    $oauth->debug = 1;
    $oauth->setRequestEngine(OAUTH_REQENGINE_CURL);
    // For posting images
    $oauth->setToken($auth['twitter_token'], $auth['twitter_token_secret']);
    try {
        $oauth->fetch($url, $api_args, OAUTH_HTTP_METHOD_POST, array("User-Agent" => "pecl/oauth"));
    } catch (Exception $e) {
        syslog(LOG_INFO, 'Menéame, Twitter caught exception: ' . $e->getMessage() . " in " . basename(__FILE__) . "\n");
        echo "Twitter post failed: {$msg} " . mb_strlen($msg) . "\n";
        return false;
    }
    // $response_info = $oauth->getLastResponseInfo();
    // echo $oauth->getLastResponse() . "\n";
    return true;
}
コード例 #21
0
 public function linkedin()
 {
     $oauth = new OAuth("772ot2tfqntox5", "Y6kUKUlWcWc6yDkd");
     $oauth->setToken("94616be2-c292-472d-9f45-dfad9b78f2ef", "cdf34568-ed5f-4a27-a15d-4c8bf276fb4d");
     $params = array();
     $headers = array();
     $method = OAUTH_HTTP_METHOD_GET;
     $url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,picture-url,location:(name))?format=json";
     $oauth->fetch($url, $params, $method, $headers);
     $result = json_decode($oauth->getLastResponse(), true);
     $this->info['nombre'] = $result['firstName'];
     $this->info['apellido'] = $result['lastName'];
     $this->info['foto'] = $result['pictureUrl'];
     $this->info['ubicacion'] = $result['location']['name'];
     $this->info['industria'] = $result['industry'];
 }
コード例 #22
0
 /**
  * Handle callback by managing oauth token, saving oauth state and calling redirect URL
  *
  * @param Request $request
  */
 public function handleCallback(Request $request)
 {
     try {
         $this->api = new \OAuth($this->options['consumer_key'], $this->options['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         $this->api->setToken($request->query->get('oauth_token'), $this->secret);
         $accessToken = $this->api->getAccessToken($this->options['access_token_endpoint']);
         $this->state = 2;
         $this->token = $accessToken['oauth_token'];
         $this->secret = $accessToken['oauth_token_secret'];
     } catch (\Exception $e) {
         $this->state = null;
     }
     $this->saveState();
     header('HTTP/1.1 302 Found');
     header('Location: ' . $this->redirectUrl);
 }
コード例 #23
0
 /**
  * fetches JSON request on F1, parses and returns response
  * @param string $url
  * @param string|array $data
  * @param const $method
  * @return void
  */
 public function fetchJson($url, $data = null, $method = OAUTH_HTTP_METHOD_GET)
 {
     try {
         $o = new OAuth($this->settings->key, $this->settings->secret, OAUTH_SIG_METHOD_HMACSHA1);
         $o->setToken($this->accessToken->oauth_token, $this->accessToken->oauth_token_secret);
         $headers = array('Content-Type' => 'application/json');
         if ($o->fetch($url, $data, $method, $headers)) {
             if ($this->settings->debug) {
                 return array('headers' => self::http_parse_headers($o->getLastResponseHeaders()), 'response' => json_decode($o->getLastResponse(), true));
             }
             return json_decode($o->getLastResponse(), true);
         }
     } catch (OAuthException $e) {
         $this->error = array('method' => $method, 'url' => $url, 'response' => self::http_parse_headers($o->getLastResponseHeaders()));
         return $this->error;
     }
 }
コード例 #24
0
ファイル: osmapi.php プロジェクト: tyrasd/Level0
function oauth_upload($comment, $data)
{
    global $messages, $error;
    if (!isset($_SESSION['osm_token']) || !isset($_SESSION['osm_secret'])) {
        $error = _('OAuth token was lost, please relogin.');
        oauth_logout();
        return false;
    }
    try {
        $stage = 'login';
        $oauth = new OAuth(CLIENT_ID, CLIENT_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
        $oauth->setToken($_SESSION['osm_token'], $_SESSION['osm_secret']);
        $change_data = create_changeset($data, $comment);
        $xml_content = array('Content-Type' => 'application/xml');
        $stage = 'create';
        // note: this call works instead of returning 401 because of $xml_content
        $oauth->fetch(OSM_API_URL . 'changeset/create', $change_data, OAUTH_HTTP_METHOD_PUT, $xml_content);
        if (!preg_match('/\\d+/', $oauth->getLastResponse(), $m)) {
            $error = _('Could not aquire changeset id for a new changeset.');
            return false;
        }
        $changeset = $m[0];
        $osc = create_osc($data, $changeset);
        $stage = 'upload';
        $oauth->fetch(OSM_API_URL . 'changeset/' . $changeset . '/upload', $osc, OAUTH_HTTP_METHOD_POST, $xml_content);
        // todo: parse response and renumber created objects?
        $stage = 'close';
        $oauth->fetch(OSM_API_URL . 'changeset/' . $changeset . '/close', array(), OAUTH_HTTP_METHOD_PUT);
        $chlink = '<a href="https://www.openstreetmap.org/changeset/' . $changeset . '" target="_blank">' . $changeset . '</a>';
        // todo: replace %d with %s and $chlink, removing str_replace
        $messages[] = '!' . str_replace($changeset, $chlink, sprintf(_('Changeset %d was uploaded successfully.'), $changeset));
        return true;
    } catch (OAuthException $E) {
        if ($stage == 'upload' && $E->getCode() == 409) {
            $error = sprintf(_('Conflict while uploading changeset %d: %s.'), $changeset, $oauth->getLastResponse());
            // todo: process conflict
            // http://wiki.openstreetmap.org/wiki/API_0.6#Error_codes_9
        } else {
            print_r($E);
            $msg = $oauth->getLastResponse();
            $error = sprintf(_('OAuth error %d at stage "%s": %s.'), $E->getCode(), $stage, $msg ? $msg : $E->getMessage());
        }
    }
    return false;
}
コード例 #25
0
 public static function get_token_credentials($oauth_verifier, $request_token, $request_token_secret)
 {
     $consumer_key = Config::get('evernote.oauth_consumer_key');
     $consumer_secret = Config::get('evernote.oauth_consumer_secret');
     $access_token_url = Config::get('evernote.evernote_server');
     $access_token_url .= Config::get('evernote.access_token_path');
     try {
         $oauth = new OAuth($consumer_key, $consumer_secret);
         $oauth->setToken($request_token, $request_token_secret);
         $access_token_info = $oauth->getAccessToken($access_token_url, null, $oauth_verifier);
         if ($access_token_info) {
             return $access_token_info;
         } else {
             Log::error('Failed to obtain token credentials: ' . $oauth->getLastResponse());
         }
     } catch (OAuthException $e) {
         Log::error('Error obtaining token credentials: ' . $e->getMessage());
     }
 }
コード例 #26
0
 private function getCategories()
 {
     $brands = Brands::all();
     return $brands;
     $consumer_key = 'b64350b6b45c8fed49aa9983bf197844';
     $consumer_secret = '85b3ce2964a63c8fb07d868a58f13b69';
     $oauth_token = 'd5608ad8dbd007c0d5cd10688e7d428d';
     $oauth_secret = '9f11ac72c96ffd96a00ee58cf67b2d2a';
     $client = new \OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
     $client->enableDebug();
     $client->setToken($oauth_token, $oauth_secret);
     try {
         $client->fetch('http://local.giftbig.com/rest/catalog', '', OAUTH_HTTP_METHOD_GET, ['Content-Type' => 'application/json', 'Accept' => '*/*']);
         $result = $client->getLastResponse();
         $result = json_decode($result);
         return $result->_embedded->products;
     } catch (\Exception $e) {
         return [];
     }
 }
コード例 #27
0
ファイル: twitter.php プロジェクト: xb11/Website
 /**
  * Publish a new post to Twitter
  * @param	Model_Blog_Post		The post
  */
 public function new_post(Model_Blog_Post $post)
 {
     $config = Kohana::$config->load('social.twitter');
     // No configuration?
     if (empty($config) || empty($config['consumer_key'])) {
         return;
     }
     $status = '';
     if (strlen($post->title) > 0) {
         $status = $post->title . ' - ';
     }
     $status .= strip_tags($post->content());
     if (strlen($status) > self::TWEET_LENGTH) {
         $status = substr($status, 0, self::TWEET_LENGTH) . '...';
     }
     $status .= ' ' . $post->short_url();
     $oauth = new OAuth($config['consumer_key'], $config['consumer_secret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
     $oauth->setToken($config['access_token'], $config['access_token_secret']);
     $oauth->fetch(self::UPDATE_URL, array('status' => $status), OAUTH_HTTP_METHOD_POST, array('User-Agent' => 'Daniel15 Blog TwitterPost'));
 }
コード例 #28
0
 /** 
  * Retrive Linkedin auth data in Cookie set by Linkedin JSSDK.
  * 
  * @param CakeRequest $request Request object.
  * @return mixed Either false or an object of user information of Linkedin
  */
 public function getUser(CakeRequest $request)
 {
     $cookie_name = 'linkedin_oauth_' . $this->settings['api_key'];
     if (isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name]) {
         $linkedin = json_decode($_COOKIE[$cookie_name]);
         if (isset($linkedin) && isset($linkedin->access_token) && $this->__verifyToken($linkedin)) {
             $oauth = new OAuth($this->settings['api_key'], $this->settings['secret_key']);
             $oauth->fetch('https://api.linkedin.com/uas/oauth/accessToken', array('xoauth_oauth2_access_token' => $linkedin->access_token), OAUTH_HTTP_METHOD_POST);
             parse_str($oauth->getLastResponse(), $response);
             $oauth->setToken($response['oauth_token'], $response['oauth_token_secret']);
             $url = 'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,public-profile-url,summary,positions)';
             // $url = 'http://api.linkedin.com/v1/people/~';
             $oauth->fetch($url, array(), OAUTH_HTTP_METHOD_GET, array('x-li-format' => 'json'));
             $profile = json_decode($oauth->getLastResponse());
             $linkedin->profile = $profile;
             return $linkedin;
         }
     }
     return false;
 }
コード例 #29
0
ファイル: twitter.php プロジェクト: jahrmando/botijon
 public function process($args)
 {
     $this->output = "";
     $args = trim($args);
     if (strlen($args) > 0) {
         try {
             $oauth = new OAuth($this->config["consumer_key"], $this->config["consumer_secret"], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
             $oauth->setToken($this->config["access_token"], $this->config["access_secret"]);
             $hashtag = false;
             if (preg_match("/^#/", $args)) {
                 $hashtag = true;
                 $oauth->fetch("https://api.twitter.com/1.1/search/tweets.json?q=" . urlencode($args) . "&count=3");
             } else {
                 $args = str_replace("@", "", $args);
                 $oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={$args}&count=1");
             }
             $twitter_data = json_decode($oauth->getLastResponse());
             if ($hashtag == false && count($twitter_data) > 0) {
                 $date = date('d/m/y H:i', strtotime($twitter_data[0]->created_at));
                 $this->output = "@{$args} : " . $twitter_data[0]->text . " -- {$date}";
             } elseif ($hashtag && isset($twitter_data->statuses)) {
                 $twits = array();
                 foreach ($twitter_data->statuses as $twit) {
                     array_push($twits, $twit->text);
                 }
                 $this->output = "{$args}: " . join("\n", $twits);
             } else {
                 if (is_array($twitter_data)) {
                     $this->output = "Ups! el usuario @{$args} no existe.";
                 } else {
                     $this->output = "El usuario @{$args} tiene sus twitts como privados.";
                 }
             }
         } catch (Exception $e) {
             $this->output = "No fue posible obtener twitts de {$args}. Ha ocurrido un error.";
         }
     } else {
         $this->output = "Ingresa un usuario.";
     }
 }
コード例 #30
0
function SendTweet($msg)
{
    if ($msg == '') {
        return false;
    }
    DebugMessage('Sending tweet of ' . strlen($msg) . " chars:\n" . $msg);
    global $twitterCredentials;
    if ($twitterCredentials === false) {
        return true;
    }
    $params = array();
    $params['status'] = $msg;
    $oauth = new OAuth($twitterCredentials['consumerKey'], $twitterCredentials['consumerSecret']);
    $oauth->setToken($twitterCredentials['WoWTokens']['accessToken'], $twitterCredentials['WoWTokens']['accessTokenSecret']);
    $url = 'https://api.twitter.com/1.1/statuses/update.json';
    try {
        $didWork = $oauth->fetch($url, $params, 'POST', array('Connection' => 'close'));
    } catch (OAuthException $e) {
        $didWork = false;
    }
    $ri = $oauth->getLastResponseInfo();
    $r = $oauth->getLastResponse();
    if ($didWork && $ri['http_code'] == '200') {
        $json = json_decode($r, true);
        if (json_last_error() == JSON_ERROR_NONE) {
            if (isset($json['id_str'])) {
                return $json['id_str'];
            }
        }
        return true;
    }
    if (isset($ri['http_code'])) {
        DebugMessage('Twitter returned HTTP code ' . $ri['http_code'], E_USER_WARNING);
    } else {
        DebugMessage('Twitter returned unknown HTTP code', E_USER_WARNING);
    }
    DebugMessage('Twitter returned: ' . print_r($ri, true), E_USER_WARNING);
    DebugMessage('Twitter returned: ' . print_r($r, true), E_USER_WARNING);
    return false;
}