Пример #1
0
/**
 * Uses two-legged OAuth to respond to a Google documents list API request
 * @param string $base_feed Full URL of the resource to access
 * @param array $params (optional) parameters to be added to url line
 * @param string $type The HTTP method (GET, POST, PUT, DELETE)
 * @param string $postData (optional) POST/PUT request body
 * @param string $version (optional) if not sent will be set to 3.0
 * @param string $content_type (optional) what kind of content is being sent
 * @param string $slug (optional) used in determining the revision of a document
 * @param boolean $batch is this a batch transmission?
 * @return string $response body from the server
 */
function twolegged($base_feed, $params, $type, $postdata = null, $version = null, $content_type = null, $slug = null, $batch = null)
{
    global $CFG;
    require_once $CFG->dirroot . '/repository/morsle/lib.php';
    // for morsle_decode
    require_once $CFG->dirroot . '/google/oauth.php';
    // Establish an OAuth consumer based on our admin 'credentials'
    if (!($CONSUMER_KEY = get_config('morsle', 'consumer_key'))) {
        return NULL;
    }
    if (!($CONSUMER_SECRET = get_config('morsle', 'oauthsecretstr'))) {
        return NULL;
    }
    $CONSUMER_SECRET = morsle_decode($CONSUMER_SECRET);
    $consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET, NULL);
    // Create an Atom entry
    $contactAtom = new DOMDocument();
    //    $contactAtom = null;
    $request = OAuthRequest::from_consumer_and_token($consumer, NULL, $type, $base_feed, $params);
    // Sign the constructed OAuth request using HMAC-SHA1
    $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
    //  scope=https://docs.google.com/feeds/%20http://spreadsheets.google.com/feeds/%20https://docs.googleusercontent.com/
    // Make signed OAuth request to the Contacts API server
    if (!is_null($params)) {
        $url = $base_feed . '?' . implode_assoc('=', '&', $params);
    } else {
        $url = $base_feed;
    }
    $header_request = $request->to_header();
    $response = send_request($request->get_normalized_http_method(), $url, $header_request, $contactAtom, $postdata, $version, $content_type, $slug, $batch);
    return $response;
}
Пример #2
0
function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body)
{
    $hash = base64_encode(sha1($body, TRUE));
    $parms = array('oauth_body_hash' => $hash);
    $test_token = '';
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
    // Pass this back up "out of band" for debugging
    global $LastOAuthBodyBaseString;
    $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();
    // echo($LastOAuthBodyBaseString."\m");
    $header = $acc_req->to_header();
    $header = $header . "\r\nContent-type: " . $content_type . "\r\n";
    $params = array('http' => array('method' => 'POST', 'content' => $body, 'header' => $header));
    try {
        $ctx = stream_context_create($params);
        $fp = @fopen($endpoint, 'rb', false, $ctx);
    } catch (Exception $e) {
        $fp = false;
    }
    if ($fp) {
        $response = @stream_get_contents($fp);
    } else {
        // Try CURL
        $headers = explode("\r\n", $header);
        $response = sendXmlOverPost($endpoint, $body, $headers);
    }
    if ($response === false) {
        throw new Exception("Problem reading data from {$endpoint}, {$php_errormsg}");
    }
    return $response;
}
/**
 * Makes a request to the Yelp API and returns the response
 *
 * @param    $host    The domain host of the API
 * @param    $path    The path of the APi after the domain
 * @return   The JSON response from the request
 */
function request($host, $path) {
    $unsigned_url = "http://" . $host . $path;

    // Token object built using the OAuth library
    $token = new OAuthToken($GLOBALS['TOKEN'], $GLOBALS['TOKEN_SECRET']);

    // Consumer object built using the OAuth library
    $consumer = new OAuthConsumer($GLOBALS['CONSUMER_KEY'], $GLOBALS['CONSUMER_SECRET']);

    // Yelp uses HMAC SHA1 encoding
    $signature_method = new OAuthSignatureMethod_HMAC_SHA1();

    $oauthrequest = OAuthRequest::from_consumer_and_token(
        $consumer,
        $token,
        'GET',
        $unsigned_url
    );

    // Sign the request
    $oauthrequest->sign_request($signature_method, $consumer, $token);

    // Get the signed URL
    $signed_url = $oauthrequest->to_url();

    // Send Yelp API Call
    $ch = curl_init($signed_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
Пример #4
0
 /**
  * Sign our target URL with OAuth auth stuff.
  *
  * @param string $url
  * @param array $params
  * @return string
  */
 protected function oAuthUrl($url, $params = array())
 {
     // In an ideal world this would be better encapsulated. :)
     $request = OAuthRequest::from_consumer_and_token($this->oauth->consumer, $this->oauth->token, 'GET', $url, $params);
     $request->sign_request($this->oauth->sha1_method, $this->oauth->consumer, $this->oauth->token);
     return $request->to_url();
 }
Пример #5
0
function getYelp($term, $location)
{
    $unsigned_url = "http://api.yelp.com/v2/search?term=" . urlencode($term) . "&location=" . urlencode($location) . "&limit=1";
    // Set your keys here
    $consumer_key = "8LjXkvQ-lcUe7dSlvIHhAQ";
    $consumer_secret = "7AnAzMD4h6mthw27wT48qZFEJoo";
    $token = "B-j7tOmv_GPGzZsfc_VId-cjRMLlBcCq";
    $token_secret = "Hjq6GZOp61HR_JxUgB9_O7HpqKA";
    // Token object built using the OAuth library
    $token = new OAuthToken($token, $token_secret);
    // Consumer object built using the OAuth library
    $consumer = new OAuthConsumer($consumer_key, $consumer_secret);
    // Yelp uses HMAC SHA1 encoding
    $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
    // Build OAuth Request using the OAuth PHP library. Uses the consumer and token object created above.
    $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_url);
    // Sign the request
    $oauthrequest->sign_request($signature_method, $consumer, $token);
    // Get the signed URL
    $signed_url = $oauthrequest->to_url();
    // Send Yelp API Call
    $ch = curl_init($signed_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $data = curl_exec($ch);
    // Yelp response
    curl_close($ch);
    // Handle Yelp response data
    //$response = json_decode($data);
    // Print it for debugging
    //print_r($response);
    return $data;
}
Пример #6
0
function signParameters($oldparms, $endpoint, $method, $key, $secret, $org_secret, $org_id, $org_desc)
{
    global $last_base_string;
    $parms = $oldparms;
    $parms["lti_version"] = "LTI-1p0";
    $parms["lti_message_type"] = "basic-lti-launch-request";
    if ($org_id) {
        $parms["tool_consumer_instance_guid"] = $org_id;
    }
    if ($org_desc) {
        $parms["tool_consumer_instance_description"] = $org_desc;
        $parms["tool_consumer_instance_name"] = $org_desc;
    }
    $parms["basiclti_submit"] = "Launch Tool";
    $parms["oauth_callback"] = "about:blank";
    if ($org_secret) {
        $oauth_consumer_secret = $org_secret;
        $oauth_consumer_key = $org_id;
    } else {
        $oauth_consumer_secret = $secret;
        $oauth_consumer_key = $key;
    }
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
    // Pass this back up "out of band" for debugging
    $last_base_string = $acc_req->get_signature_base_string();
    $newparms = $acc_req->get_parameters();
    return $newparms;
}
Пример #7
0
 public function getFeed()
 {
     $biz = 'gjelina-venice-2';
     $url = 'http://api.yelp.com/v2/business/' . $biz;
     $this->token = env('YELP_ACCESS_TOKEN');
     $this->secret = env('YELP_ACCESS_TOKEN_SECRET');
     $this->consumer_key = env('YELP_CONSUMER_KEY');
     $this->consumer_secret = env('YELP_CONSUMER_SECRET');
     // Token object built using the OAuth library
     $token = new OAuthToken($this->token, $this->token_secret);
     // Consumer object built using the OAuth library
     $consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret);
     // Yelp uses HMAC SHA1 encoding
     $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
     // Build OAuth Request using the OAuth PHP library. Uses the consumer and token object created above.
     $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $url);
     // Sign the request
     $oauthrequest->sign_request($signature_method, $consumer, $token);
     // Get the signed URL
     $signed_url = $oauthrequest->to_url();
     //$signed_url = str_replace("gjelina-venice-2?", "gjelina-venice-2&", $signed_url);
     echo $signed_url . "<br><br>";
     $r = $this->callCurl($signed_url);
     $arr = json_decode($r);
     printR($arr);
     // foreach($arr->error as $k=>$v) {
     //      echo rawurldecode($v)."<br><br>";
     // }
     printR($r);
     exit;
 }
function get_pco_data($url,$method = "GET",$content = Null){
	global $pco_key, $pco_secret, $user_access_token, $user_access_token_secret;

	$test_consumer  = new OAuthConsumer($pco_key, $pco_secret, NULL);
	$access_consumer = new OAuthConsumer($user_access_token, $user_access_token_secret, NULL);

	// build and sign request
	$request = OAuthRequest::from_consumer_and_token($test_consumer,
	  $access_consumer, 
	  $method,
	  $url, 
	  NULL);
	$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),
	  $test_consumer, 
	  $access_consumer
	);
	
	if (isset($content)){
		//define request headers
		$headers = array("Accept: application/xml");
		$headers[] = $request->to_header();
		$headers[] = "Content-type: application/xml";
		$response = run_curl($url, $method, $headers, $content);
	}
	else {
		// make GET request
		$response = run_curl($request, $method);
	}
	
	return $response;

}
 protected function execute($arguments = array(), $options = array())
 {
     require_once realpath(dirname(__FILE__) . '/../../../../lib/vendor/OAuth/OAuth.php');
     new sfDatabaseManager($this->configuration);
     sfContext::createInstance($this->createConfiguration('pc_frontend', 'prod'), 'pc_frontend');
     $consumerKey = isset($options['consumer-key']) && $options['consumer-key'] ? $options['consumer-key'] : opOpenSocialToolKit::getOAuthConsumerKey();
     $consumer = new OAuthConsumer($consumerKey, null, null);
     $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin();
     $httpOptions = opOpenSocialToolKit::getHttpOptions();
     $queueGroups = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueueGroups();
     $limitRequest = (int) $options['limit-request'];
     $limitRequestApp = (int) $options['limit-request-app'];
     $allRequest = 0;
     foreach ($queueGroups as $group) {
         $application = Doctrine::getTable('Application')->find($group[0]);
         $links = $application->getLinks();
         $linkHash = array();
         foreach ($links as $link) {
             if (isset($link['rel']) && isset($link['href'])) {
                 $method = isset($link['method']) ? strtolower($link['method']) : '';
                 $method = 'post' !== $method ? 'get' : 'post';
                 $linkHash[$link['rel']] = array('href' => $link['href'], 'method' => $method);
             }
         }
         $queues = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueuesByApplicationId($group[0], $limitRequestApp);
         foreach ($queues as $queue) {
             if (!isset($linkHash[$queue->getName()])) {
                 $queue->delete();
                 continue;
             }
             $href = $linkHash[$queue->getName()]['href'];
             $method = $linkHash[$queue->getName()]['method'];
             $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $href, $queue->getParams());
             $oauthRequest->sign_request($signatureMethod, $consumer, null);
             $client = new Zend_Http_Client();
             if ('post' !== $method) {
                 $method = 'get';
                 $client->setMethod(Zend_Http_Client::GET);
                 $href .= '?' . $oauthRequest->to_postdata();
             } else {
                 $client->setMethod(Zend_Http_Client::POST);
                 $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
                 $client->setRawData($oauthRequest->to_postdata());
             }
             $client->setConfig($httpOptions);
             $client->setUri($href);
             $client->setHeaders($oauthRequest->to_header());
             $response = $client->request();
             if ($response->isSuccessful()) {
                 $queue->delete();
             }
             $allRequest++;
             if ($limitRequest && $limitRequest <= $allRequest) {
                 break 2;
             }
         }
         $application->free(true);
         $queues->free(true);
     }
 }
 public function __construct($consumer, $token, $http_method, $http_url, $parameters = array())
 {
     $this->OAuthRequest = OAuthRequest::from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters);
     $this->OAuthRequest->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $token);
     $this->method = $http_method;
     $this->parameters = is_array($parameters) ? $parameters : array($parameters);
 }
function brukar_client_oauth_callback()
{
    require_once drupal_get_path('module', 'brukar_common') . '/OAuth.php';
    $method = new OAuthSignatureMethod_HMAC_SHA1();
    $consumer = new OAuthConsumer(variable_get('brukar_consumer_key'), variable_get('brukar_consumer_secret'));
    if (isset($_SESSION['auth_oauth']) && $_SESSION['auth_oauth']['oauth_token'] == $_GET['oauth_token']) {
        unset($_GET['oauth_token']);
        $tmp = new OAuthToken($_SESSION['auth_oauth']['oauth_token'], $_SESSION['auth_oauth']['oauth_token_secret']);
        $req = OAuthRequest::from_consumer_and_token($consumer, $tmp, 'GET', variable_get('brukar_url') . 'server/oauth/access_token', array());
        $req->sign_request($method, $consumer, $tmp);
        parse_str(trim(file_get_contents($req->to_url())), $token);
        unset($_SESSION['auth_oauth']);
        if (count($token) > 0) {
            $_SESSION['_brukar_access_token'] = array('token' => $token['oauth_token'], 'token_secret' => $token['oauth_token_secret']);
            $token = new OAuthToken($token['oauth_token'], $token['oauth_token_secret']);
            $req = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', variable_get('brukar_url') . 'server/oauth/user', array());
            $req->sign_request($method, $consumer, $token);
            brukar_client_login((array) json_decode(trim(file_get_contents($req->to_url()))));
        }
    }
    $debug_data = array('cookie' => $_COOKIE, 'request_uri' => request_uri(), 'auth_oauth' => isset($_SESSION['auth_oauth']) ? $_SESSION['auth_oauth'] : 'no auth_oauth');
    watchdog('brukar_client', 'User login failed.<br/>Debug data:<br/><pre>!debug_data</pre><br/>', array('!debug_data' => print_r($debug_data, TRUE)), WATCHDOG_ERROR);
    drupal_set_message(t('Noe gikk feil under innlogging.'), 'warning');
    drupal_goto('<front>');
}
Пример #12
0
 /**
  * Adds a signature to the request
  *
  * @access public
  * @author Joel Bout, <*****@*****.**>
  * @param $authorizationHeader Move the signature parameters into the Authorization header of the request
  */
 public function sign(common_http_Request $request, common_http_Credentials $credentials, $authorizationHeader = false)
 {
     if (!$credentials instanceof tao_models_classes_oauth_Credentials) {
         throw new tao_models_classes_oauth_Exception('Invalid credentals: ' . gettype($credentials));
     }
     $oauthRequest = $this->getOauthRequest($request);
     $dataStore = new tao_models_classes_oauth_DataStore();
     $consumer = $dataStore->getOauthConsumer($credentials);
     $token = $dataStore->new_request_token($consumer);
     $allInitialParameters = array();
     $allInitialParameters = array_merge($allInitialParameters, $request->getParams());
     $allInitialParameters = array_merge($allInitialParameters, $request->getHeaders());
     //oauth_body_hash is used for the signing computation
     if ($authorizationHeader) {
         $oauth_body_hash = base64_encode(sha1($request->getBody(), true));
         //the signature should be ciomputed from encoded versions
         $allInitialParameters = array_merge($allInitialParameters, array("oauth_body_hash" => $oauth_body_hash));
     }
     //$authorizationHeader = self::buildAuthorizationHeader($signatureParameters);
     $signedRequest = OAuthRequest::from_consumer_and_token($consumer, $token, $oauthRequest->get_normalized_http_method(), $oauthRequest->getUrl(), $allInitialParameters);
     $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
     //common_logger::d('Base string: '.$signedRequest->get_signature_base_string());
     $signedRequest->sign_request($signature_method, $consumer, $token);
     common_logger::d('Base string from TAO/Joel: ' . $signedRequest->get_signature_base_string());
     if ($authorizationHeader) {
         $combinedParameters = $signedRequest->get_parameters();
         $signatureParameters = array_diff_assoc($combinedParameters, $allInitialParameters);
         $signatureParameters["oauth_body_hash"] = base64_encode(sha1($request->getBody(), true));
         $signatureHeaders = array("Authorization" => self::buildAuthorizationHeader($signatureParameters));
         $signedRequest = new common_http_Request($signedRequest->getUrl(), $signedRequest->get_normalized_http_method(), $request->getParams(), array_merge($signatureHeaders, $request->getHeaders()), $request->getBody());
     } else {
         $signedRequest = new common_http_Request($signedRequest->getUrl(), $signedRequest->get_normalized_http_method(), $signedRequest->get_parameters(), $request->getHeaders(), $request->getBody());
     }
     return $signedRequest;
 }
Пример #13
0
 /**
  * @return OAuthRequest
  */
 public function newRequestMessage($method, $url, $parameters)
 {
     if (!isset($method)) {
         $method = $this->getProperty("httpMethod");
         if ($method == null) {
             $method = $this->consumer->getProperty("httpMethod");
             if ($method == null) {
                 $method = "GET";
             }
         }
     }
     $message = OAuthRequest::from_consumer_and_token($this->consumer, $this->accessToken, $method, $url, $parameters);
     $signatureMethod = null;
     if ($parameters[OAuth::$OAUTH_SIGNATURE_METHOD] == OAuth::$RSA_SHA1) {
         $signatureMethod = new OAuthSignatureMethod_RSA_SHA1();
     } else {
         if ($parameters[OAuth::$OAUTH_SIGNATURE_METHOD] == OAuth::$HMAC_SHA1) {
             $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
         } else {
             //PLAINTEXT
             $signatureMethod = new OAuthSignatureMethod_PLAINTEXT();
         }
     }
     $message->sign_request($signatureMethod, $this->consumer, $this->tokenSecret);
     return $message;
 }
function immediate_update_outcome_in_canvas($oauth_consumer_key, $secret, $lti_sourced_id, $lis_outcome_service_url, $score)
{
    set_time_limit(180);
    $xmlRequest = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<imsx_POXEnvelopeRequest xmlns=\"http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0\">\n    <imsx_POXHeader>\n        <imsx_POXRequestHeaderInfo>\n            <imsx_version>V1.0</imsx_version>\n            <imsx_messageIdentifier>999999123</imsx_messageIdentifier>\n        </imsx_POXRequestHeaderInfo>\n    </imsx_POXHeader>\n    <imsx_POXBody>\n        <replaceResultRequest>\n            <resultRecord>\n                <sourcedGUID>\n                    <sourcedId>{$lti_sourced_id}</sourcedId>\n                </sourcedGUID>\n                <result>\n                    <resultScore>\n                        <language>en</language>\n                        <textString>" . $score . "</textString>\n                    </resultScore>\n                </result>\n            </resultRecord>\n        </replaceResultRequest>\n    </imsx_POXBody>\n</imsx_POXEnvelopeRequest>";
    $hash = base64_encode(sha1($xmlRequest, TRUE));
    $params = array('oauth_body_hash' => $hash);
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $consumer = new OAuthConsumer($oauth_consumer_key, $secret, NULL);
    $req = OAuthRequest::from_consumer_and_token($consumer, NULL, 'POST', $lis_outcome_service_url, $params);
    $req->sign_request($hmac_method, $consumer, NULL);
    $params = $req->get_parameters();
    $header = $req->to_header();
    $header .= "\nContent-type: application/xml";
    $ext_response = do_post_request($lis_outcome_service_url, $xmlRequest, $header);
    $ext_doc = new DOMDocument();
    set_error_handler(array($this, 'HandleXmlError'));
    $ext_doc->loadXML($ext_response);
    restore_error_handler();
    $ext_nodes = domnode_to_array($ext_doc->documentElement);
    if (!isset($ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_codeMajor'])) {
        throw new Exception("No imsx_codeMajor from outcome service for " . $lti_sourced_id);
    }
    if ($ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_codeMajor'] != 'success' && isset($ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_description']) && $ext_nodes['imsx_POXHeader']['imsx_POXResponseHeaderInfo']['imsx_statusInfo']['imsx_description'] != 'User is no longer in course') {
        throw new Exception("No success code from outcome service for " . $lti_sourced_id);
    }
}
Пример #15
0
 private function _getYelpRequest($yelp_id)
 {
     $cache = $this->cache;
     if (($data = $cache->load(md5($yelp_id))) === false) {
         // For example, request business with id 'the-waterboy-sacramento'
         $unsigned_url = "http://api.yelp.com/v2/business/{$yelp_id}";
         // Token object built using the OAuth library
         $token = new OAuthToken($this->_token, $this->_token_secret);
         // Consumer object built using the OAuth library
         $consumer = new OAuthConsumer($this->_consumer_key, $this->_consumer_secret);
         // Yelp uses HMAC SHA1 encoding
         $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
         // Build OAuth Request using the OAuth PHP library. Uses the consumer and token object created above.
         $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_url);
         // Sign the request
         $oauthrequest->sign_request($signature_method, $consumer, $token);
         // Get the signed URL
         $signed_url = $oauthrequest->to_url();
         // Send Yelp API Call
         $ch = curl_init($signed_url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         $data = curl_exec($ch);
         // Yelp response
         curl_close($ch);
         // Handle Yelp response data
         $response = json_decode($data);
         $cache->save($response, md5($yelp_id));
     }
     return $data;
 }
Пример #16
0
Файл: user.php Проект: xctcc/npt
function user_oauth_sign(&$url, &$args = false)
{
    require_once 'OAuth.php';
    $method = $args !== false ? 'POST' : 'GET';
    if (preg_match_all('#[?&]([^=]+)=([^&]+)#', $url, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
            $args[$match[1]] = $match[2];
        }
        $url = substr($url, 0, strpos($url, '?'));
    }
    $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
    $consumer = new OAuthConsumer(OAUTH_KEY, OAUTH_SECRET);
    $token = NULL;
    if (($oauth_token = $_GET['oauth_token']) && $_SESSION['oauth_request_token_secret']) {
        $oauth_token_secret = $_SESSION['oauth_request_token_secret'];
    } else {
        list($oauth_token, $oauth_token_secret) = explode('|', $GLOBALS['user']['password']);
    }
    if ($oauth_token && $oauth_token_secret) {
        $token = new OAuthConsumer($oauth_token, $oauth_token_secret);
    }
    $request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $args);
    $request->sign_request($sig_method, $consumer, $token);
    switch ($method) {
        case 'GET':
            $url = $request->to_url();
            $args = false;
            return;
        case 'POST':
            $url = $request->get_normalized_http_url();
            $args = $request->to_postdata();
            return;
    }
}
Пример #17
0
function get_yelp_data_for_truck($vendor_name, $lat, $long)
{
    // Configuration.
    $consumer_key = '';
    $consumer_secret = '';
    $token = '';
    $token_secret = '';
    // Search params.
    $params = array('term' => $vendor_name, 'category_filter' => 'foodtrucks,foodstands', 'location' => 'San Francisco, CA', 'cll' => (string) $lat . "," . (string) $long, 'limit' => 1);
    // Build the request.
    $unsigned_uri = "http://api.yelp.com/v2/search/?" . http_build_query($params);
    // Token object built using the OAuth library
    $token = new OAuthToken($token, $token_secret);
    // Consumer object built using the OAuth library
    $consumer = new OAuthConsumer($consumer_key, $consumer_secret);
    // Yelp uses HMAC SHA1 encoding
    $signature_method = new OAuthSignatureMethod_HMAC_SHA1();
    $oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_uri);
    // Sign the request
    $oauthrequest->sign_request($signature_method, $consumer, $token);
    // Get the signed URL
    $signed_url = $oauthrequest->to_url();
    $results = fetch_data($signed_url);
    // Ensure a business listing is returned and the location is not closed
    // permanently.
    if (array_key_exists("businesses", $results) && !$results["businesses"][0]["is_closed"]) {
        return $results["businesses"][0];
    }
    return null;
}
Пример #18
0
 function checkStatusByMerchantRef($pesapalMerchantReference)
 {
     $request_status = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, "GET", $this->QueryPaymentStatusByMerchantRef, $this->params);
     $request_status->set_parameter("pesapal_merchant_reference", $pesapalMerchantReference);
     $request_status->sign_request($this->signature_method, $this->consumer, $this->token);
     $status = $this->curlRequest($request_status);
     return $status;
 }
Пример #19
0
 function update($status)
 {
     $tk = new TwitterToken();
     $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, 'POST', $tk->api_root . '/statuses/update.xml', array('status' => $status));
     $req->sign_request($this->method, $this->consumer, $this->token);
     $response = $this->http($req->get_normalized_http_url(), $req->to_postdata());
     return $response;
 }
Пример #20
0
 public function getUserInfo($url, $accessToken)
 {
     $data_req = OAuthRequest::from_consumer_and_token($this->consumer, $accessToken, "GET", $url, NULL);
     $data_req->sign_request($this->signer, $this->consumer, $accessToken);
     $data = SimpleSAML_Utilities::fetch($data_req->to_url());
     #print_r($data);
     $dataDecoded = json_decode($data, TRUE);
     return $dataDecoded;
 }
Пример #21
0
 public function add_headers(&$url, &$headers, &$data, &$type, &$options)
 {
     $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $options['type'], $url, $data);
     $request->sign_request($this->signature_method, $this->consumer, $this->token);
     $header = $request->to_header();
     // Strip leading 'Authorization:'
     $header = trim(substr($header, 14));
     $headers['Authorization'] = trim($header, ' ');
 }
Пример #22
0
 function request($url, $method, $params = null)
 {
     $sign = new OAuthSignatureMethod_HMAC_SHA1();
     $request = OAuthRequest::from_consumer_and_token($this->consumer, null, $method, $url, $params);
     $request->sign_request($sign, $this->consumer, null);
     $ch = curl_init($request);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     return curl_exec($ch);
 }
Пример #23
0
 function play()
 {
     if ($this->session->userdata('user_id')) {
         //get oauth stuff
     } else {
         redirect('/join');
     }
     $this->load->library('form_validation');
     $this->form_validation->set_rules('name', 'Stage Name', 'required|trim');
     $this->form_validation->set_rules('paypal_email', 'Donation Email Address', 'required|trim');
     $this->form_validation->set_rules('website', 'Website URL', 'required|trim');
     if ($this->form_validation->run() == FALSE) {
         require_once "/Users/aaronfrank/Sites/busk/php/OAuth.php";
         require_once "/Users/aaronfrank/Sites/busk/php/OAuthConfig.php";
         $key = '';
         //'<your app's API key>';
         $secret = '';
         //'<your app's secret>';
         $request_token_endpoint = 'http://api.justin.tv/oauth/request_token';
         $oauth_access_token_endpoint = 'http://api.justin.tv/oauth/access_token';
         $authorize_endpoint = 'http://api.justin.tv/oauth/authorize';
         $test_consumer = new OAuthConsumer($key, $secret, NULL);
         //prepare to get request token
         $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
         $parsed = parse_url($request_token_endpoint);
         $req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "GET", $request_token_endpoint);
         $req_req->sign_request($sig_method, $test_consumer, NULL);
         $req_token = doHttpRequest($req_req->to_url());
         //assuming the req token fetch was a success, we should have
         //oauth_token and oauth_token_secret
         parse_str($req_token, $tokens);
         $oauth_token = $tokens['oauth_token'];
         $oauth_token_secret = $tokens['oauth_token_secret'];
         $consumer = $test_consumer;
         // new OAuthConsumer($oauth_token, $oauth_token_secret, NULL);
         $auth_token = new OAuthConsumer($oauth_token, $oauth_token_secret);
         $access_token_req = new OAuthRequest("GET", $oauth_access_token_endpoint);
         $access_token_req = $access_token_req->from_consumer_and_token($test_consumer, $auth_token, "GET", $oauth_access_token_endpoint);
         $access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $auth_token);
         $after_access_request = doHttpRequest($access_token_req->to_url());
         $access_tokens = $tokens;
         $access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);
         $streamkey_req = $access_token_req->from_consumer_and_token($consumer, $access_token, "GET", "http://api.justin.tv/api/stream/new_stream_key/busktv.xml");
         $streamkey_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $access_token);
         $xml = doHttpRequest($streamkey_req->to_url());
         $xml_parser = xml_parser_create();
         xml_parse_into_struct($xml_parser, $xml, $vals, $index);
         $data['stream_key'] = $vals[0]['value'];
         $view_name = 'play_form';
     } else {
         $data['stream_key'] = $this->input->post('stream_key');
         $view_name = 'play';
     }
     $data['title'] = "Broadcast";
     $this->load->view($view_name, $data);
 }
Пример #24
0
 private function execute($selected_call, $method_type, $params)
 {
     // the endpoint for your request
     $endpoint = "{$this->netdnarws_url}/{$this->alias}{$selected_call}";
     //parse endpoint before creating OAuth request
     $parsed = parse_url($endpoint);
     if (array_key_exists("parsed", $parsed)) {
         parse_str($parsed['query'], $params);
     }
     //generate a request from your consumer
     require_once __DIR__ . '/OAuth/OAuthRequest.php';
     $req_req = OAuthRequest::from_consumer_and_token($this->consumer, null, $method_type, $endpoint, $params);
     //sign your OAuth request using hmac_sha1
     require_once __DIR__ . '/OAuth/OAuthSignatureMethod_HMAC_SHA1.php';
     $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
     $req_req->sign_request($sig_method, $this->consumer, null);
     // create curl resource
     $ch = curl_init();
     // set url
     curl_setopt($ch, CURLOPT_URL, $req_req);
     // return the transfer as a string
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     // Set SSL Verifyer off
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     // set curl timeout
     curl_setopt($ch, CURLOPT_TIMEOUT, 60);
     // set curl custom request type if not standard
     if ($method_type != "GET" && $method_type != "POST") {
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method_type);
     }
     if ($method_type == "POST" || $method_type == "PUT" || $method_type == "DELETE") {
         require_once __DIR__ . '/OAuth/OAuthUtil.php';
         $query_str = OAuthUtil::build_http_query($params);
         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:', 'Content-Length: ' . strlen($query_str)));
         curl_setopt($ch, CURLOPT_POSTFIELDS, $query_str);
     }
     // retrieve headers
     curl_setopt($ch, CURLOPT_HEADER, 1);
     curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
     //set user agent
     curl_setopt($ch, CURLOPT_USERAGENT, 'PHP NetDNA API Client');
     // make call
     $result = curl_exec($ch);
     $headers = curl_getinfo($ch);
     $curl_error = curl_error($ch);
     // close curl resource to free up system resources
     curl_close($ch);
     // $json_output contains the output string
     $json_output = substr($result, $headers['header_size']);
     // catch errors
     if (!empty($curl_error) || empty($json_output)) {
         //throw new \NetDNA\RWSException("CURL ERROR: $curl_error, Output: $json_output", $headers['http_code'], null, $headers);
         return 'CURL ERROR: ' . $curl_error . ', Output: ' . $json_output;
     }
     return $json_output;
 }
Пример #25
0
 public static function fetchQuery($query, $ts)
 {
     if (!$query) {
         return;
     }
     $dbr = wfGetDB(DB_SLAVE);
     $sql = "select min(ql_time_fetched) as ts from dedup.query_lookup where ql_query=" . $dbr->addQuotes($query);
     $res = $dbr->query($sql, __METHOD__);
     foreach ($res as $row) {
         $oldTs = $row->ts;
     }
     if ($oldTs > $ts) {
         $dbw = wfGetDB(DB_MASTER);
         $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes("exists") . "," . $dbw->addQuotes(wfTimestampNow()) . ")";
         $dbw->query($sql, __METHOD__);
         return;
     }
     try {
         $cc_key = WH_YAHOO_BOSS_API_KEY;
         $cc_secret = WH_YAHOO_BOSS_API_SECRET;
         $url = "http://yboss.yahooapis.com/ysearch/web";
         $args = array();
         $args["q"] = $query;
         $args["format"] = "json";
         $consumer = new OAuthConsumer($cc_key, $cc_secret);
         $request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $url, $args);
         $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
         $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
         $ch = curl_init();
         $headers = array($request->to_header());
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
         $rsp = curl_exec($ch);
         $results = json_decode($rsp);
         if ($results->bossresponse->responsecode == 200) {
             $n = 0;
             $dbw = wfGetDB(DB_MASTER);
             foreach ($results->bossresponse->web->results as $result) {
                 $n++;
                 $sql = "insert into dedup.query_lookup(ql_query,ql_url,ql_pos,ql_time_fetched) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes($result->url) . "," . $dbw->addQuotes($n) . "," . $dbw->addQuotes(wfTimestampNow()) . ")";
                 $dbw->query($sql, __METHOD__);
             }
             $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes('success') . "," . $dbw->addQuotes(wfTimestampNow()) . ")";
             $dbw->query($sql, __METHOD__);
         } else {
             $dbw = wfGetDB(DB_MASTER);
             $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp, qll_timestamp, qll_comment) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes('badresponse') . "," . $dbw->addQuotes(wfTimestampNow()) . "," . $dbw->addQuotes("Response : " . ($results ? print_r($results, true) : ''));
             $dbw->query($sql, __METHOD__);
         }
     } catch (Exception $ex) {
         $dbw = wfGetDB(DB_MASTER);
         $sql = "insert into dedup.query_lookup_log(qll_query, qll_result, qll_timestamp, qll_comment) values(" . $dbw->addQuotes($query) . "," . $dbw->addQuotes("exception") . "," . $dbw->addQuotes(wfTimestampNow()) . "," . $dbw->addQuotes($ex->getMessage()) . ")";
         $dbw->query($sql, __METHOD__);
     }
 }
Пример #26
0
 function request($url, $method, $args = array())
 {
     $request = OAuthRequest::from_consumer_and_token(self::$consumer, self::$token, $method, $url, $args);
     $request->sign_request(self::$sha1_method, self::$consumer, self::$token);
     if ($method == 'GET') {
         return self::curl($request->to_url());
     } else {
         return self::curl($request->get_normalized_http_url(), $request->to_postdata());
     }
 }
Пример #27
0
 function getCompanyFollowersByName($companyName = "")
 {
     $api_url = $this->base_url . "/v1/companies/universal-name=" . $companyName . ":(num-followers)/";
     $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $api_url);
     $request->sign_request($this->signature_method, $this->consumer, $this->access_token);
     $auth_header = $request->to_header("https://api.linkedin.com");
     # this is the realm
     $response = $this->httpRequest($api_url, $auth_header, "GET");
     return $response;
 }
 /**
  * Post to Linkedin
  * @param type $comment
  * @param type $title
  * @param type $url
  * @param type $image_url
  * @param type $access_token
  * @return type
  */
 function share($comment, $title, $url, $image_url, $access_token)
 {
     $shareUrl = "http://api.linkedin.com/v1/people/~/shares";
     $xml = "<share>\n              <comment>{$comment}</comment>\n              <content>\n                 <title>{$title}</title>\n                     <description>asdfsadf</description>\n                 <submitted-url>{$url}</submitted-url>\n                 <submitted-image-url>{$image_url}</submitted-image-url>\n              </content>\n              <visibility>\n                <code>anyone</code>\n              </visibility>\n            </share>";
     $request = OAuthRequest::from_consumer_and_token($this->consumer, $access_token, "POST", $shareUrl);
     $request->sign_request($this->method, $this->consumer, $access_token);
     $auth_header = $request->to_header("https://api.linkedin.com");
     $response = $this->httpRequest($shareUrl, $auth_header, "POST", $xml);
     return $response;
 }
Пример #29
0
 function get_access_token()
 {
     $args = array();
     $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, 'GET', "https://api.twitter.com/oauth/access_token", $args);
     $request->sign_request($this->method, $this->consumer, $this->token);
     $request = $this->http($request->to_url());
     $token = $this->parse_access($request);
     $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
     return $token;
 }
Пример #30
0
 /**
  * Returns the value of the OAuth Authorization HTTP header for a given
  * endpoint URL.
  * @param string $url the endpoint URL to authorize against
  * @return string the OAuth Authorization HTTP header value
  */
 public function GetOAuthHeader($url)
 {
     $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
     $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, 'POST', $url, array());
     $request->sign_request($signatureMethod, $this->consumer, $this->token);
     $header = $request->to_header();
     // Remove "Authorization:" prefix.
     $pieces = explode(':', $header, 2);
     return trim($pieces[1]);
 }