コード例 #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
 /**
  * Send a POST request to the specified URL with the specified payload.
  * @param string $url
  * @param string $data
  * @return string Remote data
  **/
 public function sendPOST($url, $data = array())
 {
     $data['_fake_status'] = '200';
     // Send the actual request.
     try {
         $this->instance->fetch($url, $data, OAUTH_HTTP_METHOD_POST, array('User-Agent' => sprintf(Imgur::$user_agent, Imgur::$key)));
     } catch (OAuthException $e) {
         throw new Imgur_Exception("Could not successfully do a sendPOST: " . $e->getMessage(), null, $e);
     }
     return $this->instance->getLastResponse();
 }
コード例 #3
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");
    }
}
コード例 #4
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;
     }
 }
コード例 #5
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;
     }
 }
コード例 #6
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;
 }
コード例 #7
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;
}
コード例 #8
0
 function do_recharge_request($param)
 {
     $random_number = rand(5, 10);
     $transaction_id = "abc" . $random_number;
     // string. Number not allowed
     //$db->insert("recharge_test_table",array("trans_id" => $transaction_id,"time"=>time()));
     $oauth_consumer_key = $client_id = $consumer_key = "spacepoint_nigeria_demo_user1";
     $oauth_consumer_secret = $client_secret = $consumer_secret = "wltJSD3ztLKfBQmIW32iSGfcrwe3okS0";
     $username = "******";
     //		$msisdn = "2348059827239"; // mobile number +234-8059827239
     //		$msisdn = "2340123456789";
     $msisdn = "234" . $param['mobile_no'];
     //		$face_value = 5000;
     $face_value = (int) $param['amount'];
     //$face_value *= 100;
     $supplier_api = "ttdemo_v1";
     $product_info = array("product" => "airtime");
     //	echo $face_value;
     //	echo " ";
     //	echo $msisdn;exit;
     try {
         $params = array("username" => $username, "msisdn" => $msisdn, "transaction_id" => $transaction_id, "face_value" => $face_value, "supplier_api" => $supplier_api, "product_info" => $product_info);
         $request = new OAuth($oauth_consumer_key, $oauth_consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         //print_r($request);
         $request->disableSSLChecks();
         $request->fetch("https://hsc16.miranetworks.net:16000/v1/recharge", json_encode($params), OAUTH_HTTP_METHOD_POST, array("Content-Type" => "application/json"));
         return $response = $request->getLastResponse();
         //echo $response;
         //			echo "<pre>";
         //			print_r($response);
         //			return $response;
     } catch (Exception $e) {
         return 'Message: ' . $e->getMessage();
     }
 }
コード例 #9
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);
}
コード例 #10
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;
}
 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);
 }
コード例 #12
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();
     }
 }
コード例 #13
0
 /**
  * @param string $command
  * @param string $method
  * @param array $parameters
  * @param array $content
  * @return mixed $data
  * @throws Exception
  * @throws \TYPO3\Flow\Http\Exception
  */
 public function call($command, $method = 'GET', array $parameters = array(), array $content = array())
 {
     $url = $this->apiUrl . $command;
     $this->emitBeforeApiCall($url, $method);
     try {
         $this->oAuthClient->fetch($url, $parameters, $method);
     } catch (\OAuthException $e) {
         // we get a 404 Response here, so lets process it
     }
     $response = $this->getResponse();
     $this->emitApiCall($url, $method, $response);
     $statusCode = $response->getStatusCode();
     if ($statusCode < 200 || $statusCode >= 400) {
         throw new Exception('ApiRequest was not successful for command  ' . $command . ' Response was: ' . $response->getStatus(), 1408987295);
     }
     $content = json_decode($response->getContent(), TRUE);
     if ($content === NULL) {
         throw new Exception('Response from ApiRequest is not a valid json', 1408987294);
     }
     return $content;
 }
コード例 #14
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.";
     }
 }
コード例 #15
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();
     }
 }
コード例 #16
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;
}
コード例 #17
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'];
 }
コード例 #18
0
 protected static function fetch_tarball_via_oauth($key, $secret, $uri)
 {
     try {
         $oauth = new OAuth($key, $secret);
         $oauth->fetch($uri);
         WP_CLI::debug($oauth->getLastResponseHeaders());
         $headers = http_parse_headers($oauth->getLastResponseHeaders());
         $mime_type = self::parse_content_type_header($headers['Content-Type']);
         $content_disposition = self::parse_content_disposition_header($headers['Content-Disposition']);
         $filename = empty($content_disposition['filename']) ? $filename = tmpfile() : sys_get_temp_dir() . DIRECTORY_SEPARATOR . $content_disposition['filename'];
         file_put_contents($filename, $oauth->getLastResponse());
         return $filename;
     } catch (OAuthException $e) {
         WP_CLI::error_multi_line($e->getMessage(), true);
     }
     WP_CLI::error('Unknown error', true);
 }
コード例 #19
0
ファイル: OAuth.php プロジェクト: 99designs/php-desk
 private function request($method = 'GET', $path, $parameters = array(), $headers = array())
 {
     $url = rtrim($this->host, '/') . '/' . ltrim($path, '/');
     try {
         $result = $this->adapter->fetch($url, $parameters, strtoupper($method), $headers);
     } catch (\OAuthException $e) {
         $response = new Response($this->adapter->getLastResponse());
         $json = $response->json();
         if (empty($json->success)) {
             throw new \Desk\Exception\ApiCallFailureException('Desk.com request failed', $response);
         } else {
             throw $e;
         }
     }
     $body = $this->adapter->getLastResponse();
     return new Response($body);
 }
コード例 #20
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;
     }
 }
コード例 #21
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;
 }
コード例 #22
0
 private static function makeRequestAndPrintResponse($method, $params, $signature_method = OAUTH_SIG_METHOD_HMACSHA1)
 {
     $oauth = new OAuth(Settings::$USOSAPI_CONSUMER_KEY, Settings::$USOSAPI_CONSUMER_SECRET, $signature_method, OAUTH_AUTH_TYPE_URI);
     if ($signature_method == OAUTH_SIG_METHOD_PLAINTEXT) {
         $oauth->setRequestEngine(OAUTH_REQENGINE_CURL);
     }
     if (Settings::$DEBUG) {
         $oauth->enableDebug();
     }
     $url = Settings::$USOSAPI_BASE_URL . $method;
     try {
         $oauth->fetch($url, $params, OAUTH_HTTP_METHOD_POST);
     } catch (OAuthException $E) {
         /* Ignored on purpose. $response_info will be filled either way. */
     }
     $response_info = $oauth->getLastResponseInfo();
     header("HTTP/1.0 {$response_info["http_code"]}");
     header("Content-Type: {$response_info["content_type"]}");
     print $oauth->getLastResponse();
 }
コード例 #23
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 [];
     }
 }
コード例 #24
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'));
 }
コード例 #25
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;
}
コード例 #26
0
 private function _oauthReq($url, $content = null, $reqType = null, $nonce = null, $timestamp = null)
 {
     try {
         $oauth = new OAuth($this->clientKey, $this->clientSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
         $oauth->enableDebug();
         $oauth->setToken($this->tokenKey, $this->tokenSecret);
         if (!is_null($nonce)) {
             $oauth->setNonce($nonce);
         }
         if (!is_null($timestamp)) {
             $oauth->setTimestamp($timestamp);
         }
         if (is_null($reqType)) {
             $reqType = OAUTH_HTTP_METHOD_GET;
         }
         $oauth->fetch("{$url}", $content, $reqType);
         $ret = $oauth->getLastResponse();
         return $ret;
     } catch (OAuthException $e) {
         //return $e->lastResponse;
         return $e;
     }
 }
コード例 #27
0
ファイル: testapp1.php プロジェクト: achyutsinha/testapp
}
try {
    $authType = $_SESSION['state'] == 2 ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
    $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
    $oauthClient->enableDebug();
    if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
        $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
        $_SESSION['secret'] = $requestToken['oauth_token_secret'];
        $_SESSION['state'] = 1;
        header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
        exit;
    } else {
        if ($_SESSION['state'] == 1) {
            $oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
            $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
            $_SESSION['state'] = 2;
            $_SESSION['token'] = $accessToken['oauth_token'];
            $_SESSION['secret'] = $accessToken['oauth_token_secret'];
            header('Location: ' . $callbackUrl);
            exit;
        } else {
            $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
            $resourceUrl = "{$apiUrl}/products";
            $oauthClient->fetch($resourceUrl);
            $productsList = json_decode($oauthClient->getLastResponse());
            print_r($productsList);
        }
    }
} catch (OAuthException $e) {
    print_r($e);
}
コード例 #28
0
 /**
  * Action that displays a single TwitterFeed
  */
 public function showAction()
 {
     //die(print_r($this->twitterFeedRepository->findByAccountName('remco'),true));
     $ffdata = $this->request->getContentObjectData();
     $options = t3lib_div::xml2array($ffdata['pi_flexform']);
     $displayFeed = $options['data']['sDEF']['lDEF']['displayFeed']['vDEF'];
     $twitterFeed = $this->twitterFeedRepository->findByUid($displayFeed);
     $account = $twitterFeed->getAccount();
     if ($account->getUserToken() == null || $account->getUserSecret == null) {
         die('You need to add a twitter authorization token/secret to the database manually for now.');
     }
     /*
     $feed = curl_init("http://twitter.com/statuses/user_timeline/19768085.json?count=20");
     curl_setopt($feed,CURLOPT_RETURNTRANSFER,true);
     $data = curl_exec($feed);
     $data = json_decode($data,true);
     //var_dump($data);
     curl_close($feed);
     */
     $req_url = 'http://api.twitter.com/oauth/request_token';
     $authurl = 'https://api.twitter.com/oauth/authorize';
     $acc_url = 'https://api.twitter.com/oauth/access_token';
     $api_url = 'https://api.twitter.com';
     $args = $this->request->getArguments();
     if (isset($args['feed'])) {
         switch ($args['feed']) {
             case 1:
                 $fid = 1;
                 $title = "My";
                 $getfeed = $api_url . "/1/statuses/user_timeline.json";
                 break;
             case 2:
                 $fid = 2;
                 $title = "My Friends";
                 $getfeed = $api_url . "/1/statuses/home_timeline.json";
                 break;
             case 3:
                 $fid = 3;
                 $title = "Other Peoples";
                 $getfeed = $api_url . "/1/statuses/public_timeline.json";
                 break;
             case 4:
                 $fid = 4;
                 $title = "Search for 'remco'";
                 $getfeed = "http://search.twitter.com/search.json?q=remco";
                 break;
         }
     } else {
         $title = "My";
         $getfeed = $api_url . "/1/statuses/user_timeline.json";
         $fid = 1;
     }
     $json = apc_fetch("tx_twitterFeed_{$twitterFeed->getFeedName()}_JSON{$fid}");
     if ($json === FALSE) {
         try {
             $oauth = new OAuth($this->settings['consumerKey'], $this->settings['consumerSecret'], OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
             $oauth->setToken($account->getUserToken(), $account->getUserSecret());
             $oauth->fetch($getfeed, null, OAUTH_HTTP_METHOD_GET);
             $json = json_decode($oauth->getLastResponse(), true);
             apc_store("tx_twitterFeed_{$twitterFeed->getFeedName()}_JSON{$fid}", $json, 60 * 5);
             $status = "fetched from Twitter using OAUTH/GET/JSON and put in the APC cache afterwards";
         } catch (OAuthException $e) {
             $this->flashMessages->add($e->getMessage());
             $status = "cat /proc/status > /dev/null";
         }
     } else {
         $status = "from APC cached JSON";
     }
     //if($fid==4) print_r($json);
     $this->response->addAdditionalHeaderData("<script src=\"http://platform.twitter.com/anywhere.js?id={$this->settings['anywhereAPIKey']}&v=1\" type=\"text/javascript\"></script>");
     $this->view->assign('twitterFeed', $twitterFeed);
     $this->view->assign('data', $json);
     $this->view->assign('status', $status);
     $this->view->assign('title', $title);
 }
コード例 #29
0
 public function pushbackAction()
 {
     $oAuthClient = Mage::getModel('transfer/oauth_client');
     $params = $oAuthClient->getConfigFromSession();
     $oAuthClient->init($params);
     $state = $oAuthClient->authenticate();
     $acessToken = $oAuthClient->getAuthorizedToken();
     if ($state == Wage_Transfer_Model_OAuth_Client::OAUTH_STATE_NO_TOKEN) {
         Mage::getSingleton('adminhtml/session')->addError('Authorization has been rejected.');
         $redirectUrl = Mage::helper("adminhtml")->getUrl("adminhtml/cms_page");
         Mage::app()->getResponse()->setRedirect($redirectUrl);
         return;
     }
     if ($state == Wage_Transfer_Model_OAuth_Client::OAUTH_STATE_ACCESS_TOKEN) {
         $accessToken = $oAuthClient->getAuthorizedToken();
         $tokenArray = explode('&', $accessToken);
         $oauth_token = explode('=', $tokenArray[0])[1];
         $oauth_token_secret = explode('=', $tokenArray[1])[1];
         $consumerKey = $params['consumerKey'];
         $consumerSecret = $params['consumerSecret'];
     }
     if (isset($oauth_token) && isset($oauth_token_secret) && isset($consumerKey) && isset($consumerSecret)) {
         $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
         $oauthClient->setToken($oauth_token, $oauth_token_secret);
         $resourceUrl = $this->livehost . '/api/rest/cpages/';
         $cmsSession = Mage::getSingleton('core/session');
         $getCmsSession = $cmsSession->getPushcms();
         $cpagesData = array();
         if (Mage::getStoreConfig('transfer/general/log')) {
             Mage::log(print_r($getCmsSession, true), null, 'TransferLog.log');
         }
         $collection = Mage::getModel('cms/page')->getCollection()->addFieldToFilter('main_table.page_id', array('in' => $getCmsSession));
         $collection->getSelect()->columns("GROUP_CONCAT(page_store.store_id SEPARATOR ',') AS store_ids")->join(array('page_store' => $collection->getTable('cms/page_store')), 'main_table.page_id = page_store.page_id', array())->group('main_table.page_id');
         foreach ($collection as $key => $value) {
             $cpagesData['items'][] = $value->getData();
         }
         if (Mage::getStoreConfig('transfer/general/log')) {
             Mage::log(print_r($cpagesData, true), null, 'TransferLog.log');
         }
         $oauthClient->fetch($resourceUrl, json_encode($cpagesData), OAUTH_HTTP_METHOD_POST, array('Accept' => 'application/json', 'Content-Type' => 'application/json'));
         $getCmsSessionData = implode(',', $getCmsSession);
         $nowTimestamp = Varien_Date::now();
         $write = Mage::getSingleton('core/resource')->getConnection('core_write');
         $write->update("cms_page", array("push_to_live" => $nowTimestamp), "page_id IN ({$getCmsSessionData})");
         Mage::getSingleton('core/session')->unsPushcms();
     }
     //$pushpageData = json_decode($oauthClient->getLastResponse(), true);
     Mage::getSingleton('adminhtml/session')->addSuccess('CMS Pages updated successfully in live.');
     $redirectUrl = Mage::helper("adminhtml")->getUrl("adminhtml/cms_page");
     Mage::app()->getResponse()->setRedirect($redirectUrl);
 }
コード例 #30
0
<?php

require "config.inc.php";
try {
    $o = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
    $access_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/access_token_resp"));
    $o->setToken($access_token_info["oauth_token"], $access_token_info["oauth_token_secret"]);
    /* the following bit refreshes the token using the session handle (http://wiki.oauth.net/ScalableOAuth) ... you don't need it unless your original access token is invalid but you'll need to audit this yourself, for example sakes we'll pretend it has expired. */
    if (!empty($access_token_info["oauth_session_handle"])) {
        $o->setAuthType(OAUTH_AUTH_TYPE_URI);
        $access_token_info = $o->getAccessToken("https://api.login.yahoo.com/oauth/v2/get_token", $access_token_info["oauth_session_handle"]);
        $o->setToken($access_token_info["oauth_token"], $access_token_info["oauth_token_secret"]);
        $o->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
        file_put_contents(OAUTH_TMP_DIR . "/access_token_resp", serialize($access_token_info));
    }
    /* done refreshing access token, time to do some fetching! */
    $query = rawurlencode("select * from social.profile where guid=me");
    $o->fetch("http://query.yahooapis.com/v1/yql?q={$query}&format=xml");
    $response_info = $o->getLastResponseInfo();
    header("Content-Type: {$response_info["content_type"]}");
    echo $o->getLastResponse();
} catch (OAuthException $E) {
    echo "Exception caught!\n";
    echo "Response: " . $E->lastResponse . "\n";
}