You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@shindig.apache.org by ch...@apache.org on 2009/12/10 13:43:56 UTC
svn commit: r889239 [1/2] - in /incubator/shindig/trunk/php: external/OAuth/
src/common/ src/common/sample/ src/gadgets/ src/gadgets/oauth/
src/gadgets/render/ src/social/oauth/ src/social/service/
src/social/servlet/ test/ test/common/ test/gadgets/
Author: chabotc
Date: Thu Dec 10 12:43:55 2009
New Revision: 889239
URL: http://svn.apache.org/viewvc?rev=889239&view=rev
Log:
OAuth and osapi.http patch by Arne Roomann-Kurrik, this patch completes the refactoring of the various http fetching mechanisms (though makeRequest, proxy or a social rpc call using osapi.http) and takes the first step in unifying the various oauth bits into one.
Added:
incubator/shindig/trunk/php/external/OAuth/
incubator/shindig/trunk/php/external/OAuth/OAuth.php
incubator/shindig/trunk/php/src/common/ShindigOAuth.php
incubator/shindig/trunk/php/src/social/service/HttpHandler.php
Modified:
incubator/shindig/trunk/php/src/common/sample/BasicRemoteContentFetcher.php
incubator/shindig/trunk/php/src/gadgets/SigningFetcher.php
incubator/shindig/trunk/php/src/gadgets/SigningFetcherFactory.php
incubator/shindig/trunk/php/src/gadgets/oauth/BasicOAuthStore.php
incubator/shindig/trunk/php/src/gadgets/oauth/OAuth.php
incubator/shindig/trunk/php/src/gadgets/oauth/OAuthAccessor.php
incubator/shindig/trunk/php/src/gadgets/oauth/OAuthFetcher.php
incubator/shindig/trunk/php/src/gadgets/render/GadgetBaseRenderer.php
incubator/shindig/trunk/php/src/social/oauth/OAuth.php
incubator/shindig/trunk/php/src/social/service/SystemHandler.php
incubator/shindig/trunk/php/src/social/servlet/ApiServlet.php
incubator/shindig/trunk/php/test/common/BasicRemoteContentTest.php
incubator/shindig/trunk/php/test/gadgets/SigningFetcherTest.php
incubator/shindig/trunk/php/test/index.php
Added: incubator/shindig/trunk/php/external/OAuth/OAuth.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/external/OAuth/OAuth.php?rev=889239&view=auto
==============================================================================
--- incubator/shindig/trunk/php/external/OAuth/OAuth.php (added)
+++ incubator/shindig/trunk/php/external/OAuth/OAuth.php Thu Dec 10 12:43:55 2009
@@ -0,0 +1,717 @@
+<?php
+
+/* Generic exception class
+ */
+class OAuthException extends Exception {
+ // pass
+}
+
+class OAuthConsumer {
+ public $key;
+ public $secret;
+
+ function __construct($key, $secret, $callback_url = NULL) {
+ $this->key = $key;
+ $this->secret = $secret;
+ $this->callback_url = $callback_url;
+ }
+
+ function __toString() {
+ return "OAuthConsumer[key=$this->key,secret=$this->secret]";
+ }
+}
+
+class OAuthToken {
+ // access tokens and request tokens
+ public $key;
+ public $secret;
+
+ /**
+ * key = the token
+ * secret = the token secret
+ */
+ function __construct($key, $secret) {
+ $this->key = $key;
+ $this->secret = $secret;
+ }
+
+ /**
+ * generates the basic string serialization of a token that a server
+ * would respond to request_token and access_token calls with
+ */
+ function to_string() {
+ return "oauth_token=" . OAuthUtil::urlencode_rfc3986($this->key) . "&oauth_token_secret=" . OAuthUtil::urlencode_rfc3986($this->secret);
+ }
+
+ function __toString() {
+ return $this->to_string();
+ }
+}
+
+class OAuthSignatureMethod {
+
+ public function check_signature(&$request, $consumer, $token, $signature) {
+ $built = $this->build_signature($request, $consumer, $token);
+ return $built == $signature;
+ }
+}
+
+class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
+
+ function get_name() {
+ return "HMAC-SHA1";
+ }
+
+ public function build_signature($request, $consumer, $token) {
+ $base_string = $request->get_signature_base_string();
+ $request->base_string = $base_string;
+
+ $key_parts = array($consumer->secret, ($token) ? $token->secret : "");
+
+ $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
+ $key = implode('&', $key_parts);
+
+ return base64_encode(hash_hmac('sha1', $base_string, $key, true));
+ }
+}
+
+class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
+
+ public function get_name() {
+ return "PLAINTEXT";
+ }
+
+ public function build_signature($request, $consumer, $token) {
+ $sig = array(OAuthUtil::urlencode_rfc3986($consumer->secret));
+
+ if ($token) {
+ array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
+ } else {
+ array_push($sig, '');
+ }
+
+ $raw = implode("&", $sig);
+ // for debug purposes
+ $request->base_string = $raw;
+
+ return OAuthUtil::urlencode_rfc3986($raw);
+ }
+}
+
+class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
+
+ public function get_name() {
+ return "RSA-SHA1";
+ }
+
+ protected function fetch_public_cert(&$request) {
+ // not implemented yet, ideas are:
+ // (1) do a lookup in a table of trusted certs keyed off of consumer
+ // (2) fetch via http using a url provided by the requester
+ // (3) some sort of specific discovery code based on request
+ //
+ // either way should return a string representation of the certificate
+ throw Exception("fetch_public_cert not implemented");
+ }
+
+ protected function fetch_private_cert(&$request) {
+ // not implemented yet, ideas are:
+ // (1) do a lookup in a table of trusted certs keyed off of consumer
+ //
+ // either way should return a string representation of the certificate
+ throw Exception("fetch_private_cert not implemented");
+ }
+
+ public function build_signature(&$request, $consumer, $token) {
+ $base_string = $request->get_signature_base_string();
+ $request->base_string = $base_string;
+
+ // Fetch the private key cert based on the request
+ $cert = $this->fetch_private_cert($request);
+
+ // Pull the private key ID from the certificate
+ $privatekeyid = openssl_get_privatekey($cert);
+
+ // Sign using the key
+ $ok = openssl_sign($base_string, $signature, $privatekeyid);
+
+ // Release the key resource
+ openssl_free_key($privatekeyid);
+
+ return base64_encode($signature);
+ }
+
+ public function check_signature(&$request, $consumer, $token, $signature) {
+ $decoded_sig = base64_decode($signature);
+
+ $base_string = $request->get_signature_base_string();
+
+ // Fetch the public key cert based on the request
+ $cert = $this->fetch_public_cert($request);
+
+ // Pull the public key ID from the certificate
+ $publickeyid = openssl_get_publickey($cert);
+
+ // Check the computed signature against the one passed in the query
+ $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
+
+ // Release the key resource
+ openssl_free_key($publickeyid);
+
+ return $ok == 1;
+ }
+}
+
+class OAuthRequest {
+ // Made protected for Shindig - need access to the $parameters array.
+ protected $parameters;
+ // Made protected for Shindig - need access to $http_method.
+ protected $http_method;
+ // Made protected for Shindig - need access to $http_url.
+ protected $http_url;
+ // for debug purposes
+ public $base_string;
+ public static $version = '1.0';
+ public static $POST_INPUT = 'php://input';
+
+ function __construct($http_method, $http_url, $parameters = NULL) {
+ @$parameters or $parameters = array();
+ $this->parameters = $parameters;
+ $this->http_method = $http_method;
+ $this->http_url = $http_url;
+ }
+
+ /**
+ * attempt to build up a request from what was passed to the server
+ */
+ public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL) {
+ $scheme = (! isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
+ @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
+ @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
+
+ // We weren't handed any parameters, so let's find the ones relevant to
+ // this request.
+ // If you run XML-RPC or similar you should use this to provide your own
+ // parsed parameter-list
+ if (! $parameters) {
+ // Find request headers
+ $request_headers = OAuthUtil::get_headers();
+
+ // Parse the query-string to find GET parameters
+ $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
+
+ // It's a POST request of the proper content-type, so parse POST
+ // parameters and add those overriding any duplicates from GET
+ if ($http_method == "POST" && @strstr($request_headers["Content-Type"], "application/x-www-form-urlencoded")) {
+ $post_data = OAuthUtil::parse_parameters(file_get_contents(self::$POST_INPUT));
+ $parameters = array_merge($parameters, $post_data);
+ }
+
+ // We have a Authorization-header with OAuth data. Parse the header
+ // and add those overriding any duplicates from GET or POST
+ if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
+ $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
+ $parameters = array_merge($parameters, $header_parameters);
+ }
+
+ }
+
+ return new OAuthRequest($http_method, $http_url, $parameters);
+ }
+
+ /**
+ * pretty much a helper function to set up the request
+ */
+ public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = NULL) {
+ @$parameters or $parameters = array();
+ $defaults = array("oauth_version" => OAuthRequest::$version,
+ "oauth_nonce" => OAuthRequest::generate_nonce(),
+ "oauth_timestamp" => OAuthRequest::generate_timestamp(),
+ "oauth_consumer_key" => $consumer->key);
+ if ($token) $defaults['oauth_token'] = $token->key;
+
+ $parameters = array_merge($defaults, $parameters);
+
+ return new OAuthRequest($http_method, $http_url, $parameters);
+ }
+
+ public function set_parameter($name, $value, $allow_duplicates = true) {
+ if ($allow_duplicates && isset($this->parameters[$name])) {
+ // We have already added parameter(s) with this name, so add to the list
+ if (is_scalar($this->parameters[$name])) {
+ // This is the first duplicate, so transform scalar (string)
+ // into an array so we can add the duplicates
+ $this->parameters[$name] = array(
+ $this->parameters[$name]);
+ }
+
+ $this->parameters[$name][] = $value;
+ } else {
+ $this->parameters[$name] = $value;
+ }
+ }
+
+ public function get_parameter($name) {
+ return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
+ }
+
+ public function get_parameters() {
+ return $this->parameters;
+ }
+
+ public function unset_parameter($name) {
+ unset($this->parameters[$name]);
+ }
+
+ /**
+ * The request parameters, sorted and concatenated into a normalized string.
+ * @return string
+ */
+ public function get_signable_parameters() {
+ // Grab all parameters
+ $params = $this->parameters;
+
+ // Remove oauth_signature if present
+ // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
+ if (isset($params['oauth_signature'])) {
+ unset($params['oauth_signature']);
+ }
+
+ return OAuthUtil::build_http_query($params);
+ }
+
+ /**
+ * Returns the base string of this request
+ *
+ * The base string defined as the method, the url
+ * and the parameters (normalized), each urlencoded
+ * and the concated with &.
+ */
+ public function get_signature_base_string() {
+ $parts = array($this->get_normalized_http_method(), $this->get_normalized_http_url(),
+ $this->get_signable_parameters());
+
+ $parts = OAuthUtil::urlencode_rfc3986($parts);
+
+ return implode('&', $parts);
+ }
+
+ /**
+ * just uppercases the http method
+ */
+ public function get_normalized_http_method() {
+ return strtoupper($this->http_method);
+ }
+
+ /**
+ * parses the url and rebuilds it to be
+ * scheme://host/path
+ */
+ public function get_normalized_http_url() {
+ $parts = parse_url($this->http_url);
+
+ $port = @$parts['port'];
+ $scheme = $parts['scheme'];
+ $host = $parts['host'];
+ $path = @$parts['path'];
+
+ $port or $port = ($scheme == 'https') ? '443' : '80';
+
+ if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
+ $host = "$host:$port";
+ }
+ return "$scheme://$host$path";
+ }
+
+ /**
+ * builds a url usable for a GET request
+ */
+ public function to_url() {
+ $post_data = $this->to_postdata();
+ $out = $this->get_normalized_http_url();
+ if ($post_data) {
+ $out .= '?' . $post_data;
+ }
+ return $out;
+ }
+
+ /**
+ * builds the data one would send in a POST request
+ */
+ public function to_postdata() {
+ return OAuthUtil::build_http_query($this->parameters);
+ }
+
+ /**
+ * builds the Authorization: header
+ */
+ public function to_header() {
+ $out = 'Authorization: OAuth realm=""';
+ $total = array();
+ foreach ($this->parameters as $k => $v) {
+ if (substr($k, 0, 5) != "oauth") continue;
+ if (is_array($v)) {
+ throw new OAuthException('Arrays not supported in headers');
+ }
+ $out .= ',' . OAuthUtil::urlencode_rfc3986($k) . '="' . OAuthUtil::urlencode_rfc3986($v) . '"';
+ }
+ return $out;
+ }
+
+ public function __toString() {
+ return $this->to_url();
+ }
+
+ public function sign_request($signature_method, $consumer, $token) {
+ $this->set_parameter("oauth_signature_method", $signature_method->get_name(), false);
+ $signature = $this->build_signature($signature_method, $consumer, $token);
+ $this->set_parameter("oauth_signature", $signature, false);
+ }
+
+ public function build_signature($signature_method, $consumer, $token) {
+ $signature = $signature_method->build_signature($this, $consumer, $token);
+ return $signature;
+ }
+
+ /**
+ * util function: current timestamp
+ */
+ private static function generate_timestamp() {
+ return time();
+ }
+
+ /**
+ * util function: current nonce
+ */
+ private static function generate_nonce() {
+ $mt = microtime();
+ $rand = mt_rand();
+
+ return md5($mt . $rand); // md5s look nicer than numbers
+ }
+}
+
+class OAuthServer {
+ protected $timestamp_threshold = 300; // in seconds, five minutes
+ protected $version = 1.0; // hi blaine
+ protected $signature_methods = array();
+
+ protected $data_store;
+
+ function __construct($data_store) {
+ $this->data_store = $data_store;
+ }
+
+ public function add_signature_method($signature_method) {
+ $this->signature_methods[$signature_method->get_name()] = $signature_method;
+ }
+
+ // high level functions
+
+
+ /**
+ * process a request_token request
+ * returns the request token on success
+ */
+ public function fetch_request_token(&$request) {
+ $this->get_version($request);
+
+ $consumer = $this->get_consumer($request);
+
+ // no token required for the initial token request
+ $token = NULL;
+
+ $this->check_signature($request, $consumer, $token);
+
+ $new_token = $this->data_store->new_request_token($consumer);
+
+ return $new_token;
+ }
+
+ /**
+ * process an access_token request
+ * returns the access token on success
+ */
+ public function fetch_access_token(&$request) {
+ $this->get_version($request);
+
+ $consumer = $this->get_consumer($request);
+
+ // requires authorized request token
+ $token = $this->get_token($request, $consumer, "request");
+
+ $this->check_signature($request, $consumer, $token);
+
+ $new_token = $this->data_store->new_access_token($token, $consumer);
+
+ return $new_token;
+ }
+
+ /**
+ * verify an api call, checks all the parameters
+ */
+ public function verify_request(&$request) {
+ $this->get_version($request);
+ $consumer = $this->get_consumer($request);
+ $token = $this->get_token($request, $consumer, "access");
+ $this->check_signature($request, $consumer, $token);
+ return array($consumer, $token);
+ }
+
+ // Internals from here
+ /**
+ * version 1
+ */
+ private function get_version(&$request) {
+ $version = $request->get_parameter("oauth_version");
+ if (! $version) {
+ $version = 1.0;
+ }
+ if ($version && $version != $this->version) {
+ throw new OAuthException("OAuth version '$version' not supported");
+ }
+ return $version;
+ }
+
+ /**
+ * figure out the signature with some defaults
+ */
+ private function get_signature_method(&$request) {
+ $signature_method = @$request->get_parameter("oauth_signature_method");
+ if (! $signature_method) {
+ $signature_method = "PLAINTEXT";
+ }
+ if (! in_array($signature_method, array_keys($this->signature_methods))) {
+ throw new OAuthException("Signature method '$signature_method' not supported " . "try one of the following: " . implode(", ", array_keys($this->signature_methods)));
+ }
+ return $this->signature_methods[$signature_method];
+ }
+
+ /**
+ * try to find the consumer for the provided request's consumer key
+ */
+ private function get_consumer(&$request) {
+ $consumer_key = @$request->get_parameter("oauth_consumer_key");
+ if (! $consumer_key) {
+ throw new OAuthException("Invalid consumer key");
+ }
+
+ $consumer = $this->data_store->lookup_consumer($consumer_key);
+ if (! $consumer) {
+ throw new OAuthException("Invalid consumer");
+ }
+
+ return $consumer;
+ }
+
+ /**
+ * try to find the token for the provided request's token key
+ */
+ private function get_token(&$request, $consumer, $token_type = "access") {
+ $token_field = @$request->get_parameter('oauth_token');
+ $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
+ if (! $token) {
+ throw new OAuthException("Invalid $token_type token: $token_field");
+ }
+ return $token;
+ }
+
+ /**
+ * all-in-one function to check the signature on a request
+ * should guess the signature method appropriately
+ */
+ private function check_signature(&$request, $consumer, $token) {
+ // this should probably be in a different method
+ $timestamp = @$request->get_parameter('oauth_timestamp');
+ $nonce = @$request->get_parameter('oauth_nonce');
+
+ $this->check_timestamp($timestamp);
+ $this->check_nonce($consumer, $token, $nonce, $timestamp);
+
+ $signature_method = $this->get_signature_method($request);
+
+ $signature = $request->get_parameter('oauth_signature');
+ $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
+
+ if (! $valid_sig) {
+ throw new OAuthException("Invalid signature");
+ }
+ }
+
+ /**
+ * check that the timestamp is new enough
+ */
+ private function check_timestamp($timestamp) {
+ // verify that timestamp is recentish
+ $now = time();
+ if ($now - $timestamp > $this->timestamp_threshold) {
+ throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
+ }
+ }
+
+ /**
+ * check that the nonce is not repeated
+ */
+ private function check_nonce($consumer, $token, $nonce, $timestamp) {
+ // verify that the nonce is uniqueish
+ $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
+ if ($found) {
+ throw new OAuthException("Nonce already used: $nonce");
+ }
+ }
+
+}
+
+class OAuthDataStore {
+
+ function lookup_consumer($consumer_key) { // implement me
+ }
+
+ function lookup_token($consumer, $token_type, $token) { // implement me
+ }
+
+ function lookup_nonce($consumer, $token, $nonce, $timestamp) { // implement me
+ }
+
+ function new_request_token($consumer) { // return a new token attached to this consumer
+ }
+
+ function new_access_token($token, $consumer) { // return a new access token attached to this consumer
+ // for the user associated with this token if the request token
+ // is authorized
+ // should also invalidate the request token
+ }
+
+}
+
+class OAuthUtil {
+
+ public static function urlencode_rfc3986($input) {
+ if (is_array($input)) {
+ return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
+ } else if (is_scalar($input)) {
+ return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
+ } else {
+ return '';
+ }
+ }
+
+ // This decode function isn't taking into consideration the above
+ // modifications to the encoding process. However, this method doesn't
+ // seem to be used anywhere so leaving it as is.
+ public static function urldecode_rfc3986($string) {
+ return urldecode($string);
+ }
+
+ // Utility function for turning the Authorization: header into
+ // parameters, has to do some unescaping
+ // Can filter out any non-oauth parameters if needed (default behaviour)
+ public static function split_header($header, $only_allow_oauth_parameters = true) {
+ $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
+ $offset = 0;
+ $params = array();
+ while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
+ $match = $matches[0];
+ $header_name = $matches[2][0];
+ $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
+ if (preg_match('/^oauth_/', $header_name) || ! $only_allow_oauth_parameters) {
+ $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
+ }
+ $offset = $match[1] + strlen($match[0]);
+ }
+
+ if (isset($params['realm'])) {
+ unset($params['realm']);
+ }
+
+ return $params;
+ }
+
+ // helper to try to sort out headers for people who aren't running apache
+ public static function get_headers() {
+ if (function_exists('apache_request_headers')) {
+ // we need this to get the actual Authorization: header
+ // because apache tends to tell us it doesn't exist
+ return apache_request_headers();
+ }
+ // otherwise we don't have apache and are just going to have to hope
+ // that $_SERVER actually contains what we need
+ $out = array();
+ foreach ($_SERVER as $key => $value) {
+ if (substr($key, 0, 5) == "HTTP_") {
+ // this is chaos, basically it is just there to capitalize the first
+ // letter of every word that is not an initial HTTP and strip HTTP
+ // code from przemek
+ $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
+ $out[$key] = $value;
+ }
+ }
+ return $out;
+ }
+
+ // This function takes a input like a=b&a=c&d=e and returns the parsed
+ // parameters like this
+ // array('a' => array('b','c'), 'd' => 'e')
+ public static function parse_parameters($input) {
+ if (! isset($input) || ! $input) return array();
+
+ $pairs = explode('&', $input);
+
+ $parsed_parameters = array();
+ foreach ($pairs as $pair) {
+ $split = explode('=', $pair, 2);
+ $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
+ $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
+
+ if (isset($parsed_parameters[$parameter])) {
+ // We have already recieved parameter(s) with this name, so add to the list
+ // of parameters with this name
+
+
+ if (is_scalar($parsed_parameters[$parameter])) {
+ // This is the first duplicate, so transform scalar (string) into an array
+ // so we can add the duplicates
+ $parsed_parameters[$parameter] = array(
+ $parsed_parameters[$parameter]);
+ }
+
+ $parsed_parameters[$parameter][] = $value;
+ } else {
+ $parsed_parameters[$parameter] = $value;
+ }
+ }
+ return $parsed_parameters;
+ }
+
+ public static function build_http_query($params) {
+ if (! $params) return '';
+
+ // Urlencode both keys and values
+ $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
+ $values = OAuthUtil::urlencode_rfc3986(array_values($params));
+ $params = array_combine($keys, $values);
+
+ // Parameters are sorted by name, using lexicographical byte value ordering.
+ // Ref: Spec: 9.1.1 (1)
+ uksort($params, 'strcmp');
+
+ $pairs = array();
+ foreach ($params as $parameter => $value) {
+ if (is_array($value)) {
+ // If two or more parameters share the same name, they are sorted by their value
+ // Ref: Spec: 9.1.1 (1)
+ natsort($value);
+ foreach ($value as $duplicate_value) {
+ $pairs[] = $parameter . '=' . $duplicate_value;
+ }
+ } else {
+ $pairs[] = $parameter . '=' . $value;
+ }
+ }
+ // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
+ // Each name-value pair is separated by an '&' character (ASCII code 38)
+ return implode('&', $pairs);
+ }
+}
+
+?>
Added: incubator/shindig/trunk/php/src/common/ShindigOAuth.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/common/ShindigOAuth.php?rev=889239&view=auto
==============================================================================
--- incubator/shindig/trunk/php/src/common/ShindigOAuth.php (added)
+++ incubator/shindig/trunk/php/src/common/ShindigOAuth.php Thu Dec 10 12:43:55 2009
@@ -0,0 +1,233 @@
+<?php
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+require_once 'external/OAuth/OAuth.php';
+
+class ShindigOAuthProblemException extends Exception {}
+
+class ShindigOAuthProtocolException extends Exception {}
+
+class ShindigOAuthNoDataException extends Exception {}
+
+class ShindigRsaSha1SignatureMethod extends OAuthSignatureMethod_RSA_SHA1 {
+ private $privateKey;
+ private $publicKey;
+
+ public function __construct($privateKey, $publicKey) {
+ $this->privateKey = $privateKey;
+ $this->publicKey = $publicKey;
+ }
+
+ protected function fetch_public_cert(&$request) {
+ return $this->publicKey;
+ }
+
+ protected function fetch_private_cert(&$request) {
+ return $this->privateKey;
+ }
+}
+
+
+class ShindigOAuth {
+ public static $VERSION_1_0 = "1.0";
+ public static $ENCODING = "UTF-8";
+ public static $FORM_ENCODED = "application/x-www-form-urlencoded";
+ public static $OAUTH_CONSUMER_KEY = "oauth_consumer_key";
+ public static $OAUTH_TOKEN = "oauth_token";
+ public static $OAUTH_TOKEN_SECRET = "oauth_token_secret";
+ public static $OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
+ public static $OAUTH_SIGNATURE = "oauth_signature";
+ public static $OAUTH_TIMESTAMP = "oauth_timestamp";
+ public static $OAUTH_NONCE = "oauth_nonce";
+ public static $OAUTH_VERSION = "oauth_version";
+ public static $HMAC_SHA1 = "HMAC_SHA1";
+ public static $RSA_SHA1 = "RSA_SHA1";
+ public static $BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----";
+ public static $END_PRIVATE_KEY = "-----END PRIVATE KEY-----";
+ public static $OAUTH_PROBLEM = "oauth_problem";
+}
+
+class ShindigOAuthRequest extends OAuthRequest {
+ /**
+ * Needed so that OAuthFetcher works with the correct type of requests.
+ */
+ public function __construct(OAuthRequest $request) {
+ $this->parameters = $request->parameters;
+ $this->http_url = $request->http_url;
+ $this->http_method = $request->http_method;
+ }
+
+ /**
+ * Needed so that OAuthFetcher works with the correct type of requests.
+ * @return ShindigOAuthRequest
+ */
+ public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
+ return new ShindigOAuthRequest(OAuthRequest::from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters));
+ }
+
+ /**
+ * Needed so that OAuthFetcher works with the correct type of requests.
+ * @return ShindigOAuthRequest
+ */
+ public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
+ return new ShindigOAuthRequest(OAuthRequest::from_request($http_method, $http_url, $parameters));
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ */
+ public function set_parameters($params) {
+ return $this->parameters = $params;
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ */
+ public function requireParameters($names) {
+ $present = $this->parameters;
+ $absent = array();
+ foreach ($names as $required) {
+ if (! in_array($required, $present)) {
+ $absent[] = $required;
+ }
+ }
+ if (count($absent) == 0) {
+ throw new ShindigOAuthProblemException("oauth_parameters_absent: " . ShindigOAuthUtil::urlencodeRFC3986($absent));
+ }
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ */
+ public function get_url() {
+ return $this->http_url;
+ }
+
+ /**
+ * Needed in SigningFetcher.php
+ */
+ public static function generate_nonce() {
+ $mt = microtime();
+ $rand = mt_rand();
+ return md5($mt . $rand); // md5s look nicer than numbers
+ }
+
+ /**
+ * Needed for from_consumer_and_token
+ */
+ private static function generate_timestamp() {
+ return time();
+ }
+}
+
+class ShindigOAuthUtil extends OAuthUtil {
+ public static $AUTH_SCHEME = "OAuth";
+ private static $AUTHORIZATION = "\ *[a-zA-Z0-9*]\ +(.*)";
+ private static $NVP = "(\\S*)\\s*\\=\\s*\"([^\"]*)\"";
+
+
+ /**
+ * Needed in OAuthFetcher.php
+ */
+ public static function getPostBodyString(Array $params) {
+ $result = '';
+ $first = true;
+ foreach ($params as $key => $val) {
+ if ($first) {
+ $first = false;
+ } else {
+ $result .= '&';
+ }
+ $result .= ShindigOAuthUtil::urlencode_rfc3986($key) . "=" . ShindigOAuthUtil::urlencode_rfc3986($val);
+ }
+ return $result;
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ * Return true if the given Content-Type header means FORM_ENCODED.
+ */
+ public static function isFormEncoded($contentType) {
+ if (! isset($contentType)) {
+ return false;
+ }
+ $semi = strpos($contentType, ";");
+ if ($semi >= 0) {
+ $contentType = substr($contentType, 0, $semi);
+ }
+ return strtolower(ShindigOAuth::$FORM_ENCODED) == strtolower(trim($contentType));
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ */
+ public static function addParameters($url, $oauthParams) {
+ $url .= strchr($url, '?') === false ? '?' : '&';
+ foreach ($oauthParams as $key => $value) {
+ $url .= ShindigOAuthUtil::urlencode_rfc3986($key)."=".ShindigOAuthUtil::urlencode_rfc3986($value)."&";
+ }
+ return $url;
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ */
+ public static function decodeForm($form) {
+ $parameters = array();
+ $explodedForm = explode("&", $form);
+ foreach ($explodedForm as $params) {
+ $value = explode("=", $params);
+ if (! empty($value[0]) && ! empty($value[1])) {
+ $parameters[ShindigOAuthUtil::urldecode_rfc3986($value[0])] = ShindigOAuthUtil::urldecode_rfc3986($value[1]);
+ }
+ }
+ return $parameters;
+ }
+
+ /**
+ * Needed in OAuthFetcher.php
+ *
+ * Parse the parameters from an OAuth Authorization or WWW-Authenticate
+ * header. The realm is included as a parameter. If the given header doesn't
+ * start with "OAuth ", return an empty list.
+ */
+ public static function decodeAuthorization($authorization) {
+ $into = array();
+ if ($authorization != null) {
+ $m = ereg(ShindigOAuthUtil::$AUTHORIZATION, $authorization);
+ if ($m !== false) {
+ if (strpos($authorization, ShindigOAuthUtil::$AUTH_SCHEME) == 0) {
+ $authorization = str_replace("OAuth ", "", $authorization);
+ $authParams = explode(", ", $authorization);
+ foreach ($authParams as $params) {
+ $m = ereg(ShindigOAuthUtil::$NVP, $params);
+ if ($m == 1) {
+ $keyValue = explode("=", $params);
+ $name = ShindigOAuthUtil::urlencode_rfc3986($keyValue[0]);
+ $value = ShindigOAuthUtil::urlencode_rfc3986(str_replace("\"", "", $keyValue[1]));
+ $into[$name] = $value;
+ }
+ }
+ }
+ }
+ }
+ return $into;
+ }
+}
\ No newline at end of file
Modified: incubator/shindig/trunk/php/src/common/sample/BasicRemoteContentFetcher.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/common/sample/BasicRemoteContentFetcher.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/common/sample/BasicRemoteContentFetcher.php (original)
+++ incubator/shindig/trunk/php/src/common/sample/BasicRemoteContentFetcher.php Thu Dec 10 12:43:55 2009
@@ -107,7 +107,7 @@
}
}
// the xml and json parsers get very upset if there are invalid UTF8 sequences in the string, by recoding it any bad chars will be filtered out
- $content = mb_convert_encoding($content, 'UTF-8', $charset);
+ //$content = mb_convert_encoding($content, 'UTF-8', $charset);
}
// on redirects and such we get multiple headers back from curl it seems, we really only want the last one
while (substr($content, 0, strlen('HTTP')) == 'HTTP' && strpos($content, "\r\n\r\n") !== false) {
Modified: incubator/shindig/trunk/php/src/gadgets/SigningFetcher.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/SigningFetcher.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/SigningFetcher.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/SigningFetcher.php Thu Dec 10 12:43:55 2009
@@ -18,14 +18,14 @@
* under the License.
*/
-/**
- * Implements signed fetch based on the OAuth request signing algorithm.
- *
- * Subclasses can override signMessage to use their own crypto if they don't
- * like the oauth.net code for some reason.
- *
- * Instances of this class are only accessed by a single thread at a time,
- * but instances may be created by multiple threads.
+/**
+ * Implements signed fetch based on the OAuth request signing algorithm.
+ *
+ * Subclasses can override signMessage to use their own crypto if they don't
+ * like the oauth.net code for some reason.
+ *
+ * Instances of this class are only accessed by a single thread at a time,
+ * but instances may be created by multiple threads.
*/
class SigningFetcher extends RemoteContentFetcher {
@@ -37,15 +37,15 @@
protected static $XOAUTH_PUBLIC_KEY_NEW = "xoauth_public_key";
protected static $ALLOWED_PARAM_NAME = '^[-_[:alnum:]]+$';
- /**
- * Private key we pass to the OAuth RSA_SHA1 algorithm.This can be a
- * PrivateKey object, or a PEM formatted private key, or a DER encoded byte
- * array for the private key.(No, really, they accept any of them.)
+ /**
+ * Private key we pass to the OAuth RSA_SHA1 algorithm.This can be a
+ * PrivateKey object, or a PEM formatted private key, or a DER encoded byte
+ * array for the private key.(No, really, they accept any of them.)
*/
protected $privateKeyObject;
- /**
- * The name of the key, included in the fetch to help with key rotation.
+ /**
+ * The name of the key, included in the fetch to help with key rotation.
*/
protected $keyName;
@@ -55,38 +55,16 @@
private $fetcher;
/**
- * Constructor based on signing with the given PrivateKey object.
+ * Constructor based on signing with the given PrivateKey object, as returned
+ * from the openssl_pkey_get_private method.
*
* @param RemoteContentFetcher $fetcher
* @param keyName name of the key to include in the request
- * @param privateKey the key to use for the signing
+ * @param privateKey A key resource identifier, as returned from
+ * openssl_pkey_get_private
* @return SigningFetcher
*/
- public static function makeFromPrivateKey(RemoteContentFetcher $fetcher, $keyName, $privateKey) {
- return new SigningFetcher($fetcher, $keyName, $privateKey);
- }
-
- /**
- * Constructor based on signing with the given PrivateKey object.
- *
- * @param RemoteContentFetcher $fetcher
- * @param keyName name of the key to include in the request
- * @param privateKey base64 encoded private key
- * @return SigningFetcher
- */
- public static function makeFromB64PrivateKey(RemoteContentFetcher $fetcher, $keyName, $privateKey) {
- return new SigningFetcher($fetcher, $keyName, $privateKey);
- }
-
- /**
- * Constructor based on signing with the given PrivateKey object.
- *
- * @param RemoteContentFetcher $fetcher
- * @param keyName name of the key to include in the request
- * @param privateKey DER encoded private key
- * @return SigningFetcher
- */
- public static function makeFromPrivateKeyBytes(RemoteContentFetcher $fetcher, $keyName, $privateKey) {
+ public static function makeFromOpenSslPrivateKey(RemoteContentFetcher $fetcher, $keyName, $privateKey) {
return new SigningFetcher($fetcher, $keyName, $privateKey);
}
@@ -112,8 +90,8 @@
$url = $request->getUrl();
$method = $request->getMethod();
try {
- // Parse the request into parameters for OAuth signing, stripping out
- // any OAuth or OpenSocial parameters injected by the client
+ // Parse the request into parameters for OAuth signing, stripping out
+ // any OAuth or OpenSocial parameters injected by the client
$parsedUri = parse_url($url);
$resource = $url;
$queryParams = array();
@@ -149,14 +127,13 @@
$this->addOpenSocialParams($msgParams, $request->getToken(), $request->getOptions()->ownerSigned, $request->getOptions()->viewerSigned);
$this->addOAuthParams($msgParams, $request->getToken());
$consumer = new OAuthConsumer(NULL, NULL, NULL);
- $consumer->setProperty(OAuthSignatureMethod_RSA_SHA1::$PRIVATE_KEY, $this->privateKeyObject);
- $signatureMethod = new OAuthSignatureMethod_RSA_SHA1();
+ $signatureMethod = new ShindigRsaSha1SignatureMethod($this->privateKeyObject, null);
$req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, $method, $resource, $msgParams);
$req_req->sign_request($signatureMethod, $consumer, NULL);
- // Rebuild the query string, including all of the parameters we added.
- // We have to be careful not to copy POST parameters into the query.
- // If post and query parameters share a name, they end up being removed
- // from the query.
+ // Rebuild the query string, including all of the parameters we added.
+ // We have to be careful not to copy POST parameters into the query.
+ // If post and query parameters share a name, they end up being removed
+ // from the query.
$forPost = array();
$postData = false;
if ($method == 'POST' && $signBody) {
@@ -165,7 +142,7 @@
if ($postData === false) {
$postData = array();
}
- $postData[] = OAuthUtil::urlencodeRFC3986($key) . "=" . OAuthUtil::urlencodeRFC3986($param);
+ $postData[] = OAuthUtil::urlencode_rfc3986($key) . "=" . OAuthUtil::urlencode_rfc3986($param);
}
if ($postData !== false) {
$postData = implode("&", $postData);
@@ -185,8 +162,8 @@
$newQuery .= urlencode($key) . '=' . urlencode($val) . '&';
}
}
- // Careful here; the OAuth form encoding scheme is slightly different than
- // the normal form encoding scheme, so we have to use the OAuth library
+ // Careful here; the OAuth form encoding scheme is slightly different than
+ // the normal form encoding scheme, so we have to use the OAuth library
// formEncode method.
$url = $parsedUri['scheme'] . '://' . $parsedUri['host'] . (isset($parsedUri['port']) ? ':' . $parsedUri['port'] : '') . (isset($parsedUri['path']) ? $parsedUri['path'] : '') . '?' . $newQuery;
$request->setUri($url);
@@ -224,24 +201,24 @@
}
private function addOAuthParams(&$msgParams, SecurityToken $token) {
- $msgParams[OAuth::$OAUTH_TOKEN] = '';
+ $msgParams[ShindigOAuth::$OAUTH_TOKEN] = '';
$domain = $token->getDomain();
if ($domain != null) {
- $msgParams[OAuth::$OAUTH_CONSUMER_KEY] = $domain;
+ $msgParams[ShindigOAuth::$OAUTH_CONSUMER_KEY] = $domain;
}
if ($this->keyName != null) {
$msgParams[SigningFetcher::$XOAUTH_PUBLIC_KEY_OLD] = $this->keyName;
$msgParams[SigningFetcher::$XOAUTH_PUBLIC_KEY_NEW] = $this->keyName;
}
- $nonce = OAuthRequest::generate_nonce();
- $msgParams[OAuth::$OAUTH_NONCE] = $nonce;
+ $nonce = ShindigOAuthRequest::generate_nonce();
+ $msgParams[ShindigOAuth::$OAUTH_NONCE] = $nonce;
$timestamp = time();
- $msgParams[OAuth::$OAUTH_TIMESTAMP] = $timestamp;
- $msgParams[OAuth::$OAUTH_SIGNATURE_METHOD] = OAuth::$RSA_SHA1;
+ $msgParams[ShindigOAuth::$OAUTH_TIMESTAMP] = $timestamp;
+ $msgParams[ShindigOAuth::$OAUTH_SIGNATURE_METHOD] = ShindigOAuth::$RSA_SHA1;
}
- /**
- * Strip out any owner or viewer id passed by the client.
+ /**
+ * Strip out any owner or viewer id passed by the client.
*/
private function sanitize($params) {
$list = array();
@@ -255,11 +232,11 @@
private function allowParam($paramName) {
$canonParamName = strtolower($paramName);
- // Exclude the fields which are only used to tell the proxy what to do
+ // Exclude the fields which are only used to tell the proxy what to do
// and the fields which should be added by signing the request later on
if ($canonParamName == "output" || $canonParamName == "httpmethod" || $canonParamName == "authz" || $canonParamName == "st" || $canonParamName == "headers" || $canonParamName == "url" || $canonParamName == "contenttype" || $canonParamName == "postdata" || $canonParamName == "numentries" || $canonParamName == "getsummaries" || $canonParamName == "signowner" || $canonParamName == "signviewer" || $canonParamName == "gadget" || $canonParamName == "bypassspeccache" || substr($canonParamName, 0, 5) == "oauth" || substr($canonParamName, 0, 6) == "xoauth" || substr($canonParamName, 0, 9) == "opensocial" || $canonParamName == "container") {
return false;
}
return true;
}
-}
+}
Modified: incubator/shindig/trunk/php/src/gadgets/SigningFetcherFactory.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/SigningFetcherFactory.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/SigningFetcherFactory.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/SigningFetcherFactory.php Thu Dec 10 12:43:55 2009
@@ -18,27 +18,27 @@
* under the License.
*/
-/**
- * Produces Signing content fetchers for input tokens.
+/**
+ * Produces Signing content fetchers for input tokens.
*/
class SigningFetcherFactory {
private $keyName;
private $privateKey;
- /**
- * Produces a signing fetcher that will sign requests and delegate actual
- * network retrieval to the {@code networkFetcher}
- *
+ /**
+ * Produces a signing fetcher that will sign requests and delegate actual
+ * network retrieval to the {@code networkFetcher}
+ *
* @param RemoteContentFetcher $networkFetcher The fetcher that will be doing actual work.
- * @return SigningFetcher
- * @throws GadgetException
+ * @return SigningFetcher
+ * @throws GadgetException
*/
public function getSigningFetcher(RemoteContentFetcher $networkFetcher) {
- return SigningFetcher::makeFromB64PrivateKey($networkFetcher, $this->keyName, $this->privateKey);
+ return SigningFetcher::makeFromOpenSslPrivateKey($networkFetcher, $this->keyName, $this->privateKey);
}
- /**
- * @param keyFile The file containing your private key for signing requests.
+ /**
+ * @param keyFile The file containing your private key for signing requests.
*/
public function __construct($keyFile = null) {
$this->keyName = 'http://' . $_SERVER["HTTP_HOST"] . Config::get('web_prefix') . '/public.cer';
@@ -77,4 +77,4 @@
$this->privateKey = $rsa_private_key;
}
}
-}
+}
Modified: incubator/shindig/trunk/php/src/gadgets/oauth/BasicOAuthStore.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/oauth/BasicOAuthStore.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/oauth/BasicOAuthStore.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/oauth/BasicOAuthStore.php Thu Dec 10 12:43:55 2009
@@ -18,14 +18,13 @@
* under the License.
*/
-class OAuthNoDataException extends Exception {
-}
+require 'src/common/ShindigOAuth.php';
class BasicOAuthStore implements OAuthStore {
-
+
private $consumerInfos = array();
private $tokens = array();
-
+
private $defaultConsumerKey;
private $defaultConsumerSecret;
@@ -45,10 +44,10 @@
$provKey->setServiceName($tokenKey->getServiceName());
//AccesorInfo
$result = $this->getOAuthAccessorProviderKey($provKey, $provInfo);
- //TokenInfo
+ //TokenInfo
$accessToken = $this->getTokenInfo($tokenKey);
if ($accessToken != null) {
- // maybe convert into methods
+ // maybe convert into methods
$result->getAccessor()->accessToken = $accessToken->getAccessToken();
$result->getAccessor()->tokenSecret = $accessToken->getTokenSecret();
}
@@ -57,23 +56,23 @@
public function getOAuthAccessorProviderKey(ProviderKey $providerKey, ProviderInfo $provInfo) {
if ($provInfo == null) {
- throw new OAuthNoDataException("must pass non-null provider info to getOAuthAccessor");
+ throw new ShindigOAuthNoDataException("must pass non-null provider info to getOAuthAccessor");
}
//AccesorInfo
$result = new AccesorInfo();
$result->setHttpMethod($provInfo->getHttpMethod());
$result->setParamLocation($provInfo->getParamLocation());
- //ConsumerKeyAndSecret
+ //ConsumerKeyAndSecret
$key = md5(serialize($providerKey));
$consumerKeyAndSecret = null;
if (isset($this->consumerInfos[$key])) {
$consumerKeyAndSecret = $this->consumerInfos[$key];
} else {
- throw new OAuthNoDataException("The Key was invalid for consumerInfos, maybe your oauth.json configuration is wrong.");
+ throw new ShindigOAuthNoDataException("Invalid or missing consumer key, please check your oauth.json configuration.");
}
if ($consumerKeyAndSecret == null) {
if ($this->defaultConsumerKey == null || $this->defaultConsumerSecret == null) {
- throw new OAuthNoDataException("ConsumerKeyAndSecret was null in oauth store");
+ throw new ShindigOAuthNoDataException("ConsumerKeyAndSecret was null in oauth store");
} else {
$consumerKeyAndSecret = new ConsumerKeyAndSecret($this->defaultConsumerKey, $this->defaultConsumerSecret, OAuthStoreVars::$KeyType['RSA_PRIVATE']);
}
@@ -81,11 +80,11 @@
//OAuthServiceProvider
$oauthProvider = $provInfo->getProvider();
if (! isset($oauthProvider)) {
- throw new OAuthNoDataException("OAuthService provider was null in provider info");
+ throw new ShindigOAuthNoDataException("OAuthService provider was null in provider info");
}
- // Accesing the class
+ // Accesing the class
$usePublicKeyCrypto = ($consumerKeyAndSecret->getKeyType() == OAuthStoreVars::$KeyType['RSA_PRIVATE']);
- //OAuthConsumer
+ //OAuthConsumer
$consumer = ($usePublicKeyCrypto) ? new OAuthConsumer($consumerKeyAndSecret->getConsumerKey(), null, $oauthProvider) : new OAuthConsumer($consumerKeyAndSecret->getConsumerKey(), $consumerKeyAndSecret->getConsumerSecret(), $oauthProvider);
if ($usePublicKeyCrypto) {
$consumer->setProperty(OAuthSignatureMethod_RSA_SHA1::$PRIVATE_KEY, $consumerKeyAndSecret->getConsumerSecret());
@@ -93,7 +92,7 @@
} else {
$result->setSignatureType(OAuthStoreVars::$SignatureType['HMAC_SHA1']);
}
-
+
$result->setAccessor(new OAuthAccessor($consumer));
return $result;
}
Modified: incubator/shindig/trunk/php/src/gadgets/oauth/OAuth.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/oauth/OAuth.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/oauth/OAuth.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/oauth/OAuth.php Thu Dec 10 12:43:55 2009
@@ -1,602 +0,0 @@
-<?php
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-class OAuth {
- public static $VERSION_1_0 = "1.0";
- public static $ENCODING = "UTF-8";
- public static $FORM_ENCODED = "application/x-www-form-urlencoded";
- public static $OAUTH_CONSUMER_KEY = "oauth_consumer_key";
- public static $OAUTH_TOKEN = "oauth_token";
- public static $OAUTH_TOKEN_SECRET = "oauth_token_secret";
- public static $OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
- public static $OAUTH_SIGNATURE = "oauth_signature";
- public static $OAUTH_TIMESTAMP = "oauth_timestamp";
- public static $OAUTH_NONCE = "oauth_nonce";
- public static $OAUTH_VERSION = "oauth_version";
- public static $HMAC_SHA1 = "HMAC_SHA1";
- public static $RSA_SHA1 = "RSA_SHA1";
- public static $BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----";
- public static $END_PRIVATE_KEY = "-----END PRIVATE KEY-----";
- public static $OAUTH_PROBLEM = "oauth_problem";
-}
-
-/* Generic exception class
- */
-class OAuthException extends Exception {
-}
-
-class OAuthProblemException extends Exception {
-}
-
-class OAuthProtocolException extends Exception {
-}
-
-class OAuthConsumer {
- public $key;
- public $secret;
- public $callback_url;
- private $properties = array();
-
- function __construct($key, $secret, $callback_url = NULL) {
- $this->key = $key;
- $this->secret = $secret;
- $this->callback_url = $callback_url;
- }
-
- public function getProperty($name) {
- return $this->properties[$name];
- }
-
- public function setProperty($name, $value) {
- $this->properties[$name] = $value;
- }
-
-}
-
-class OAuthToken {
- // access tokens and request tokens
- public $key;
- public $secret;
-
- /**
- * key = the token
- * secret = the token secret
- */
- function __construct($key, $secret) {
- $this->key = $key;
- $this->secret = $secret;
- }
-
- /**
- * generates the basic string serialization of a token that a server
- * would respond to request_token and access_token calls with
- */
- function to_string() {
- return "oauth_token=" . OAuthUtil::urlencodeRFC3986($this->key) . "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
- }
-
- function __toString() {
- return $this->to_string();
- }
-}
-
-class OAuthSignatureMethod {
-
- public function check_signature(&$request, $consumer, $token, $signature) {
- $built = $this->build_signature($request, $consumer, $token);
- return $built == $signature;
- }
-}
-
-class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
-
- function get_name() {
- return "HMAC-SHA1";
- }
-
- public function build_signature($request, $consumer, $token) {
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
- $key_parts = array($consumer->secret, (isset($token)) ? $token : "");
- $key_parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $key_parts);
- $key = implode('&', $key_parts);
- return base64_encode(hash_hmac('sha1', $base_string, $key, true));
- }
-
- //TODO: Double check this!
- public function check_signature(&$request, $consumer, $token, $signature) {
- $sign = $this->build_signature($request, $consumer, $token);
- return $sign == $signature;
- }
-}
-
-class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
-
- public function get_name() {
- return "PLAINTEXT";
- }
-
- public function build_signature($request, $consumer, $token) {
- $sig = array(OAuthUtil::urlencodeRFC3986($consumer->secret));
- if ($token) {
- array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret));
- } else {
- array_push($sig, '');
- }
- $raw = implode("&", $sig);
- // for debug purposes
- $request->base_string = $raw;
- return OAuthUtil::urlencodeRFC3986($raw);
- }
-
- //TODO: Double check this!
- public function check_signature(&$request, $consumer, $token, $signature) {
- $raw = OAuthUtil::urldecodeRFC3986($request->base_string);
- $sig = explode("&", $raw);
- array_pop($sig);
- $secret = array(OAuthUtil::urldecodeRFC3986($consumer->secret));
- return $sig == $secret;
- }
-}
-
-class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
- public static $PRIVATE_KEY = "RSA-SHA1.PrivateKey";
-
- public function get_name() {
- return "RSA-SHA1";
- }
-
- protected function fetch_public_cert(&$request) {
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- // (2) fetch via http using a url provided by the requester
- // (3) some sort of specific discovery code based on request
- //
- // either way should return a string representation of the certificate
- throw Exception("fetch_public_cert not implemented");
- }
-
- protected function fetch_private_cert(&$request) {
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- //
- // either way should return a string representation of the certificate
- throw new Exception("fetch_private_cert not implemented");
- }
-
- public function build_signature(&$request, OAuthConsumer $consumer, $token) {
- $base_string = $request->get_signature_base_string();
- // Fetch the private key cert based on the request
- $cert = $consumer->getProperty(OAuthSignatureMethod_RSA_SHA1::$PRIVATE_KEY);
- // Pull the private key ID from the certificate
- //FIXME this function seems to be called both for a oauth.json action where
- // there is no phrase required, but for signed requests too, which do require it
- // this is a dirty hack to make it work .. kinda
- if (! $privatekeyid = @openssl_pkey_get_private($cert)) {
- if (! $privatekeyid = @openssl_pkey_get_private($cert, Config::get('private_key_phrase') != '' ? (Config::get('private_key_phrase')) : null)) {
- throw new Exception("Could not load private key");
- }
- }
- // Sign using the key
- $signature = '';
- if (($ok = openssl_sign($base_string, $signature, $privatekeyid)) === false) {
- throw new OAuthException("Could not create signature");
- }
- // Release the key resource
- @openssl_free_key($privatekeyid);
- return base64_encode($signature);
- }
-
- public function check_signature(&$request, $consumer, $token, $signature) {
- $decoded_sig = base64_decode($signature);
- $base_string = $request->get_signature_base_string();
- // Fetch the public key cert based on the request
- $cert = $this->fetch_public_cert($request);
- // Pull the public key ID from the certificate
- $publickeyid = openssl_get_publickey($cert);
- // Check the computed signature against the one passed in the query
- $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
- // Release the key resource
- @openssl_free_key($publickeyid);
- return $ok == 1;
- }
-}
-
-class OAuthRequest {
- public $parameters;
- private $http_method;
- private $http_url;
- public $base_string;
- public static $version = '1.0';
-
- function __construct($http_method, $http_url, $parameters = NULL) {
- @$parameters or $parameters = array();
- $this->parameters = $parameters;
- $this->http_method = $http_method;
- $this->http_url = $http_url;
- }
-
- /**
- * attempt to build up a request from what was passed to the server
- */
- public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL) {
- $scheme = (! isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
- @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
- @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
- $request_headers = OAuthRequest::get_headers();
- // let the library user override things however they'd like, if they know
- // which parameters to use then go for it, for example XMLRPC might want to
- // do this
- if ($parameters) {
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- } elseif (@substr($request_headers['Authorization'], 0, 5) == "OAuth") {
- // next check for the auth header, we need to do some extra stuff
- // if that is the case, namely suck in the parameters from GET or POST
- // so that we can include them in the signature
- $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
- if ($http_method == "GET") {
- $req_parameters = $_GET;
- } else if ($http_method = "POST") {
- $req_parameters = $_POST;
- }
- $parameters = array_merge($header_parameters, $req_parameters);
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- } elseif ($http_method == "GET") {
- $req = new OAuthRequest($http_method, $http_url, $_GET);
- } elseif ($http_method == "POST") {
- $req = new OAuthRequest($http_method, $http_url, $_POST);
- }
- return $req;
- }
-
- /**
- * pretty much a helper function to set up the request
- * @return OAuthRequest
- */
- public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = NULL) {
- $parameters = is_array($parameters) ? $parameters : array();
- $defaults = array("oauth_nonce" => OAuthRequest::generate_nonce(), "oauth_timestamp" => OAuthRequest::generate_timestamp(), "oauth_consumer_key" => $consumer->key);
- $parameters = array_merge($defaults, $parameters);
- if (isset($token)) {
- $parameters['oauth_token'] = $token;
- }
- return new OAuthRequest($http_method, $http_url, $parameters);
- }
-
- public function set_parameter($name, $value) {
- $this->parameters[$name] = $value;
- }
-
- public function get_parameter($name) {
- return @$this->parameters[$name];
- }
-
- public function get_parameters() {
- return $this->parameters;
- }
-
- public function set_parameters($params) {
- return $this->parameters = $params;
- }
-
- //TODO double check if hash can be used
- public function requireParameters($names) {
- $present = $this->parameters;
- $absent = array();
- foreach ($names as $required) {
- if (! in_array($required, $present)) {
- $absent[] = $required;
- }
- }
- if (count($absent) == 0) {
- throw new OAuthProblemException("oauth_parameters_absent: " . OAuthUtil::urlencodeRFC3986($absent));
- }
- }
-
- /**
- * Returns the normalized parameters of the request
- *
- * This will be all (except oauth_signature) parameters,
- * sorted first by key, and if duplicate keys, then by
- * value.
- *
- * The returned string will be all the key=value pairs
- * concated by &.
- *
- * @return string
- */
- public function get_signable_parameters() {
- // Grab all parameters
- $params = $this->parameters;
- // Remove oauth_signature if present
- if (isset($params['oauth_signature'])) {
- unset($params['oauth_signature']);
- }
- // Urlencode both keys and values
- $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params));
- $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params));
- $params = array_combine($keys, $values);
- // Sort by keys (natsort)
- uksort($params, 'strnatcmp');
- // Generate key=value pairs
- $pairs = array();
- foreach ($params as $key => $value) {
- if (is_array($value)) {
- // If the value is an array, it's because there are multiple
- // with the same key, sort them, then add all the pairs
- natsort($value);
- foreach ($value as $v2) {
- $pairs[] = $key . '=' . $v2;
- }
- } else {
- $pairs[] = $key . '=' . $value;
- }
- }
- // Return the pairs, concated with &
- return implode('&', $pairs);
- }
-
- /**
- * Returns the base string of this request
- *
- * The base string defined as the method, the url
- * and the parameters (normalized), each urlencoded
- * and the concated with &.
- */
- public function get_signature_base_string() {
- $tmp = $this->parameters;
- $parts = parse_url($this->http_url);
- parse_str(@$parts['query'], $params);
- foreach ($params as $key => $value) {
- if ($key == "signOwner" || $key == "signViewer") {
- continue;
- }
- $this->parameters[$key] = $value;
- }
- $parts = array($this->get_normalized_http_method(), $this->get_normalized_http_url(), $this->get_signable_parameters());
- $parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $parts);
- $this->parameters = $tmp;
- return implode('&', $parts);
- }
-
- /**
- * just uppercases the http method
- */
- public function get_normalized_http_method() {
- return strtoupper($this->http_method);
- }
-
- /**
- * parses the url and rebuilds it to be
- * scheme://host/path
- */
- public function get_normalized_http_url() {
- $parts = parse_url($this->http_url);
- // FIXME: port should handle according to http://groups.google.com/group/oauth/browse_thread/thread/1b203a51d9590226
- $port = (isset($parts['port']) && $parts['port'] != '80') ? ':' . $parts['port'] : '';
- $path = (isset($parts['path'])) ? $parts['path'] : '';
-
- return $parts['scheme'] . '://' . $parts['host'] . $port . $path;
- }
-
- /**
- * builds a url usable for a GET request
- */
- public function to_url() {
- $out = $this->get_normalized_http_url() . "?";
- $out .= $this->to_postdata();
- $parts = parse_url($this->http_url);
- $out .= "&" . @$parts['query'];
- return $out;
- }
-
- public function get_url() {
- return $this->http_url;
- }
-
- /**
- * builds the data one would send in a POST request
- */
- public function to_postdata() {
- $total = array();
- foreach ($this->parameters as $k => $v) {
- $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v);
- }
- $out = implode("&", $total);
- return $out;
- }
-
- /**
- * builds the Authorization: header
- */
- public function to_header() {
- $out = '"Authorization: OAuth realm="",';
- foreach ($this->parameters as $k => $v) {
- if (substr($k, 0, 5) != "oauth") continue;
- $out .= ',' . OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '"';
- }
- return $out;
- }
-
- public function __toString() {
- return $this->to_url();
- }
-
- public function sign_request($signature_method, $consumer, $token) {
- $this->set_parameter("oauth_signature_method", $signature_method->get_name());
- $signature = $this->build_signature($signature_method, $consumer, $token);
- $this->set_parameter("oauth_signature", $signature);
- }
-
- public function build_signature($signature_method, $consumer, $token) {
- $signature = $signature_method->build_signature($this, $consumer, $token);
- return $signature;
- }
-
- /**
- * util function: current timestamp
- */
- private static function generate_timestamp() {
- return time();
- }
-
- /**
- * util function: current nonce
- */
- public static function generate_nonce() {
- $mt = microtime();
- $rand = mt_rand();
- return md5($mt . $rand); // md5s look nicer than numbers
- }
-
- /**
- * util function for turning the Authorization: header into
- * parameters, has to do some unescaping
- */
- private static function split_header($header) {
- // this should be a regex
- // error cases: commas in parameter values
- $parts = explode(",", $header);
- $out = array();
- foreach ($parts as $param) {
- $param = ltrim($param);
- // skip the "realm" param, nobody ever uses it anyway
- if (substr($param, 0, 5) != "oauth") continue;
- $param_parts = explode("=", $param);
- // rawurldecode() used because urldecode() will turn a "+" in the
- // value into a space
- $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, - 1));
- }
- return $out;
- }
-
- /**
- * helper to try to sort out headers for people who aren't running apache
- */
- private static function get_headers() {
- if (function_exists('apache_request_headers')) {
- // we need this to get the actual Authorization: header
- // because apache tends to tell us it doesn't exist
- return apache_request_headers();
- }
- // otherwise we don't have apache and are just going to have to hope
- // that $_SERVER actually contains what we need
- $out = array();
- foreach ($_SERVER as $key => $value) {
- if (substr($key, 0, 5) == "HTTP_") {
- // this is chaos, basically it is just there to capitalize the first
- // letter of every word that is not an initial HTTP and strip HTTP
- // code from przemek
- $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
- $out[$key] = $value;
- }
- }
- return $out;
- }
-}
-
-class OAuthUtil {
-
- public static $AUTH_SCHEME = "OAuth";
- private static $AUTHORIZATION = "\ *[a-zA-Z0-9*]\ +(.*)";
- private static $NVP = "(\\S*)\\s*\\=\\s*\"([^\"]*)\"";
-
- public static function getPostBodyString(Array $params) {
- $result = '';
- $first = true;
- foreach ($params as $key => $val) {
- if ($first) {
- $first = false;
- } else {
- $result .= '&';
- }
- $result .= OAuthUtil::urlencodeRFC3986($key) . "=" . OAuthUtil::urlencodeRFC3986($val);
- }
- return $result;
- }
-
- public static function urlencodeRFC3986($string) {
- return str_replace('%7E', '~', rawurlencode($string));
- }
-
- public static function urldecodeRFC3986($string) {
- return rawurldecode($string);
- }
-
- /** Return true if the given Content-Type header means FORM_ENCODED. */
- public static function isFormEncoded($contentType) {
- if (! isset($contentType)) {
- return false;
- }
- $semi = strpos($contentType, ";");
- if ($semi >= 0) {
- $contentType = substr($contentType, 0, $semi);
- }
- return strtolower(OAuth::$FORM_ENCODED) == strtolower(trim($contentType));
- }
-
- public static function addParameters($url, $oauthParams) {
- $url .= strchr($url, '?') === false ? '?' : '&';
- foreach ($oauthParams as $key => $value) {
- $url .= OAuthUtil::urlencodeRFC3986($key)."=".OAuthUtil::urlencodeRFC3986($value)."&";
- }
- return $url;
- }
-
- public static function decodeForm($form) {
- $parameters = array();
- $explodedForm = explode("&", $form);
- foreach ($explodedForm as $params) {
- $value = explode("=", $params);
- if (! empty($value[0]) && ! empty($value[1])) {
- $parameters[OAuthUtil::urldecodeRFC3986($value[0])] = OAuthUtil::urldecodeRFC3986($value[1]);
- }
- }
- return $parameters;
- }
-
- /**
- * Parse the parameters from an OAuth Authorization or WWW-Authenticate
- * header. The realm is included as a parameter. If the given header doesn't
- * start with "OAuth ", return an empty list.
- */
- public static function decodeAuthorization($authorization) {
- $into = array();
- if ($authorization != null) {
- $m = ereg(self::$AUTHORIZATION, $authorization);
- if ($m !== false) {
- if (strpos($authorization, OAuthUtil::$AUTH_SCHEME) == 0) {
- $authorization = str_replace("OAuth ", "", $authorization);
- $authParams = explode(", ", $authorization);
- foreach ($authParams as $params) {
- $m = ereg(OAuthUtil::$NVP, $params);
- if ($m == 1) {
- $keyValue = explode("=", $params);
- $name = OAuthUtil::urlencodeRFC3986($keyValue[0]);
- $value = OAuthUtil::urlencodeRFC3986(str_replace("\"", "", $keyValue[1]));
- $into[$name] = $value;
- }
- }
- }
- }
- }
- return $into;
- }
-}
Modified: incubator/shindig/trunk/php/src/gadgets/oauth/OAuthAccessor.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/oauth/OAuthAccessor.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/oauth/OAuthAccessor.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/oauth/OAuthAccessor.php Thu Dec 10 12:43:55 2009
@@ -53,16 +53,17 @@
}
}
}
- $message = OAuthRequest::from_consumer_and_token($this->consumer, $this->accessToken, $method, $url, $parameters);
+ $token = new OAuthToken($this->accessToken, $this->tokenSecret);
+ $message = ShindigOAuthRequest::from_consumer_and_token($this->consumer, $token, $method, $url, $parameters);
$signatureMethod = null;
- if ($parameters[OAuth::$OAUTH_SIGNATURE_METHOD] == OAuth::$RSA_SHA1) {
+ if ($parameters[ShindigOAuth::$OAUTH_SIGNATURE_METHOD] == ShindigOAuth::$RSA_SHA1) {
$signatureMethod = new OAuthSignatureMethod_RSA_SHA1();
- } else if ($parameters[OAuth::$OAUTH_SIGNATURE_METHOD] == OAuth::$HMAC_SHA1) {
+ } else if ($parameters[ShindigOAuth::$OAUTH_SIGNATURE_METHOD] == ShindigOAuth::$HMAC_SHA1) {
$signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
} else { //PLAINTEXT
$signatureMethod = new OAuthSignatureMethod_PLAINTEXT();
}
- $message->sign_request($signatureMethod, $this->consumer, $this->tokenSecret);
+ $message->sign_request($signatureMethod, $this->consumer, $token);
return $message;
}
Modified: incubator/shindig/trunk/php/src/gadgets/oauth/OAuthFetcher.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/oauth/OAuthFetcher.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/oauth/OAuthFetcher.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/oauth/OAuthFetcher.php Thu Dec 10 12:43:55 2009
@@ -61,9 +61,9 @@
*/
protected $authToken;
- /**
+ /**
* Parameters from makeRequest
- * @var OAuthRequestParams
+ * @var OAuthRequestParams
*/
protected $requestParams;
@@ -106,19 +106,19 @@
*/
private $aznUrl;
- /**
- * Error code for the client
+ /**
+ * Error code for the client
*/
private $error;
- /**
- * Error text for the client
+ /**
+ * Error text for the client
*/
private $errorText;
- /**
- * Whether or not we're supposed to ignore the spec cache when referring
- * to the gadget spec for information (e.g. OAuth URLs).
+ /**
+ * Whether or not we're supposed to ignore the spec cache when referring
+ * to the gadget spec for information (e.g. OAuth URLs).
*/
private $bypassSpecCache;
@@ -146,8 +146,8 @@
if ($origClientState != null && strlen($origClientState) > 0) {
try {
$this->origClientState = $this->oauthCrypter->unwrap($origClientState, self::$CLIENT_STATE_MAX_AGE_SECS);
- } catch (BlobCrypterException $e) {// Probably too old, pretend we never saw it at all.
-}
+ } catch (BlobCrypterException $e) { // Probably too old, pretend we never saw it at all.
+ }
}
if ($this->origClientState == null) {
$this->origClientState = array();
@@ -159,10 +159,10 @@
if ($this->error == null) {
$this->error = OAuthError::$UNKNOWN_PROBLEM;
}
- // Take a giant leap of faith and assume that the exception message
- // will be useful to a gadget developer. Also include the exception
- // stack trace, in case the problem report makes it to someone who knows
- // enough to do something useful with the stack.
+ // Take a giant leap of faith and assume that the exception message
+ // will be useful to a gadget developer. Also include the exception
+ // stack trace, in case the problem report makes it to someone who knows
+ // enough to do something useful with the stack.
$errorBuf = '';
$errorBuf .= $e->getMessage();
$errorBuf .= "\n\n";
@@ -198,7 +198,7 @@
$accessor->accessToken = $this->origClientState[self::$ACCESS_TOKEN_KEY];
$accessor->tokenSecret = $this->origClientState[self::$ACCESS_TOKEN_SECRET_KEY];
} else if ($accessor->accessToken == null && $this->requestParams->getRequestToken() != null) {
- // We don't have an access token yet, but the client sent us a
+ // We don't have an access token yet, but the client sent us a
// (hopefully) preapproved request token.
$accessor->requestToken = $this->requestParams->getRequestToken();
$accessor->tokenSecret = $this->requestParams->getRequestTokenSecret();
@@ -220,13 +220,13 @@
}
public function fetch($request) {
+ $this->realRequest = $request;
try {
$this->lookupOAuthMetadata();
} catch (Exception $e) {
$this->error = OAuthError::$BAD_OAUTH_CONFIGURATION;
return $this->buildErrorResponse($e);
}
- $this->realRequest = $request;
$response = $this->fetchRequest($request);
return $response;
}
@@ -235,6 +235,7 @@
* @return RemoteContentRequest
*/
public function fetchRequest(RemoteContentRequest $request) {
+ $this->realRequest = $request;
$this->checkCanApprove();
if ($this->needApproval()) {
// This is section 6.1 of the OAuth spec.
@@ -243,10 +244,10 @@
$this->buildClientApprovalState();
$this->buildAznUrl();
// break out of the content fetching chain, we need permission from
- // the user to do this
+ // the user to do this
return $this->buildOAuthApprovalResponse();
} elseif ($this->needAccessToken()) {
- // This is section 6.3 of the OAuth spec
+ // This is section 6.3 of the OAuth spec
$this->exchangeRequestToken($request);
$this->saveAccessToken();
$this->buildClientAccessState();
@@ -303,9 +304,10 @@
self::addIdentityParams($msgParams, $request->getToken());
$request = $this->newRequestMessageParams($url->url, $msgParams);
$reply = $this->sendOAuthMessage($request);
- $reply->requireParameters(array(OAuth::$OAUTH_TOKEN, OAuth::$OAUTH_TOKEN_SECRET));
- $accessor->requestToken = $reply->get_parameter(OAuth::$OAUTH_TOKEN);
- $accessor->tokenSecret = $reply->get_parameter(OAuth::$OAUTH_TOKEN_SECRET);
+ $reply->requireParameters(array(ShindigOAuth::$OAUTH_TOKEN,
+ ShindigOAuth::$OAUTH_TOKEN_SECRET));
+ $accessor->requestToken = $reply->get_parameter(ShindigOAuth::$OAUTH_TOKEN);
+ $accessor->tokenSecret = $reply->get_parameter(ShindigOAuth::$OAUTH_TOKEN_SECRET);
} catch (Exception $e) {
// It's unfortunate the OAuth libraries throw a generic Exception.
throw new GadgetException($e);
@@ -320,14 +322,14 @@
throw new Exception("params was null in " . "newRequestMessage " . "Use newRequesMessage if you don't have a params to pass");
}
switch ($this->accessorInfo->getSignatureType()) {
- case OAuth::$RSA_SHA1:
- $params[OAuth::$OAUTH_SIGNATURE_METHOD] = OAuth::$RSA_SHA1;
+ case ShindigOAuth::$RSA_SHA1:
+ $params[ShindigOAuth::$OAUTH_SIGNATURE_METHOD] = ShindigOAuth::$RSA_SHA1;
break;
case "PLAINTEXT":
- $params[OAuth::$OAUTH_SIGNATURE_METHOD] = "PLAINTEXT";
+ $params[ShindigOAuth::$OAUTH_SIGNATURE_METHOD] = "PLAINTEXT";
break;
default:
- $params[OAuth::$OAUTH_SIGNATURE_METHOD] = OAuth::$HMAC_SHA1;
+ $params[ShindigOAuth::$OAUTH_SIGNATURE_METHOD] = ShindigOAuth::$HMAC_SHA1;
}
$accessor = $this->accessorInfo->getAccessor();
return $accessor->newRequestMessage($method, $url, $params);
@@ -372,7 +374,7 @@
} else {
$first = false;
}
- $result .= OAuthUtil::urlencodeRFC3986($key) . "=\"" . OAuthUtil::urlencodeRFC3986($val) . '"';
+ $result .= ShindigOAuthUtil::urlencode_rfc3986($key) . "=\"" . ShindigOAuthUtil::urlencode_rfc3986($val) . '"';
}
return $result;
}
@@ -395,18 +397,18 @@
break;
case OAuthStoreVars::$OAuthParamLocation['POST_BODY']:
- if (! OAuthUtil::isFormEncoded($contentType)) {
+ if (! ShindigOAuthUtil::isFormEncoded($contentType)) {
throw new GadgetException("Invalid param: OAuth param location can only " . "be post_body if post body if of type x-www-form-urlencoded");
}
if (! isset($postBody) || count($postBody) == 0) {
- $postBody = OAuthUtil::getPostBodyString($oauthParams);
+ $postBody = ShindigOAuthUtil::getPostBodyString($oauthParams);
} else {
- $postBody = $postBody . "&" . OAuthUtil::getPostBodyString($oauthParams);
+ $postBody = $postBody . "&" . ShindigOAuthUtil::getPostBodyString($oauthParams);
}
break;
case OAuthStoreVars::$OAuthParamLocation['URI_QUERY']:
- $url = OAuthUtil::addParameters($url, $oauthParams);
+ $url = ShindigOAuthUtil::addParameters($url, $oauthParams);
break;
}
$postBodyBytes = ($postBody == null) ? null : null; //$postBody->getBytes("UTF-8"); //See what can we do with this?
@@ -418,15 +420,15 @@
/**
* Sends OAuth request token and access token messages.
*/
- private function sendOAuthMessage(OAuthRequest $request) {
+ private function sendOAuthMessage(ShindigOAuthRequest $request) {
$rcr = $this->createRemoteContentRequest($this->filterOAuthParams($request), $request->get_normalized_http_method(), $request->get_url(), null, RemoteContentRequest::$DEFAULT_CONTENT_TYPE, null, RemoteContentRequest::getDefaultOptions());
$rcr->setToken($this->authToken);
$remoteFetcherClass = Config::get('remote_content_fetcher');
$fetcher = new $remoteFetcherClass();
$content = $fetcher->fetchRequest($rcr);
- $reply = OAuthRequest::from_request();
- $params = OAuthUtil::decodeForm($content->getResponseContent());
+ $reply = ShindigOAuthRequest::from_request();
+ $params = ShindigOAuthUtil::decodeForm($content->getResponseContent());
$reply->set_parameters($params);
return $reply;
}
@@ -461,9 +463,9 @@
} else {
$authUrl .= "&";
}
- $authUrl .= OAuth::$OAUTH_TOKEN;
+ $authUrl .= ShindigOAuth::$OAUTH_TOKEN;
$authUrl .= "=";
- $authUrl .= OAuthUtil::urlencodeRFC3986($accessor->requestToken);
+ $authUrl .= ShindigOAuthUtil::urlencode_rfc3986($accessor->requestToken);
$this->aznUrl = $authUrl;
}
@@ -482,13 +484,14 @@
$accessor = $this->accessorInfo->getAccessor();
$url = $accessor->consumer->callback_url->accessTokenURL;
$msgParams = array();
- $msgParams[OAuth::$OAUTH_TOKEN] = $accessor->requestToken;
+ $msgParams[ShindigOAuth::$OAUTH_TOKEN] = $accessor->requestToken;
self::addIdentityParams($msgParams, $request->getToken());
$request = $this->newRequestMessageParams($url->url, $msgParams);
$reply = $this->sendOAuthMessage($request);
- $reply->requireParameters(array(OAuth::$OAUTH_TOKEN, OAuth::$OAUTH_TOKEN_SECRET));
- $accessor->accessToken = $reply->get_parameter(OAuth::$OAUTH_TOKEN);
- $accessor->tokenSecret = $reply->get_parameter(OAuth::$OAUTH_TOKEN_SECRET);
+ $reply->requireParameters(array(ShindigOAuth::$OAUTH_TOKEN,
+ ShindigOAuth::$OAUTH_TOKEN_SECRET));
+ $accessor->accessToken = $reply->get_parameter(ShindigOAuth::$OAUTH_TOKEN);
+ $accessor->tokenSecret = $reply->get_parameter(ShindigOAuth::$OAUTH_TOKEN_SECRET);
} catch (Exception $e) {
// It's unfortunate the OAuth libraries throw a generic Exception.
throw new GadgetException("INTERNAL SERVER ERROR: " . $e);
@@ -528,7 +531,7 @@
*/
private function fetchData() {
try {
- $msgParams = OAuthUtil::isFormEncoded($this->realRequest->getContentType()) ? OAuthUtil::urldecodeRFC3986($this->realRequest->getPostBody()) : array();
+ $msgParams = ShindigOAuthUtil::isFormEncoded($this->realRequest->getContentType()) ? ShindigOAuthUtil::urldecode_rfc3986($this->realRequest->getPostBody()) : array();
$method = $this->realRequest->getMethod();
$msgParams[self::$XOAUTH_APP_URL] = $this->authToken->getAppUrl();
// Build and sign the message.
@@ -541,8 +544,8 @@
$statusCode = $content->getHttpCode();
if ($statusCode >= 400 && $statusCode < 500) {
$message = $this->parseAuthHeader(null, $content);
- if ($message->get_parameter(OAuth::$OAUTH_PROBLEM) != null) {
- throw new OAuthProtocolException($message);
+ if ($message->get_parameter(ShindigOAuth::$OAUTH_PROBLEM) != null) {
+ throw new ShindigOAuthProtocolException($message);
}
}
// Track metadata on the response
@@ -553,21 +556,21 @@
}
}
- /**
- * Parse OAuth WWW-Authenticate header and either add them to an existing
- * message or create a new message.
- *
- * @param msg
- * @param resp
- * @return the updated message.
+ /**
+ * Parse OAuth WWW-Authenticate header and either add them to an existing
+ * message or create a new message.
+ *
+ * @param msg
+ * @param resp
+ * @return the updated message.
*/
- private function parseAuthHeader(OAuthRequest $msg = null, RemoteContentRequest $resp) {
+ private function parseAuthHeader(ShindigOAuthRequest $msg = null, RemoteContentRequest $resp) {
if ($msg == null) {
- $msg = OAuthRequest::from_request();
+ $msg = ShindigOAuthRequest::from_request();
}
$authHeaders = $resp->getResponseHeader("WWW-Authenticate");
if ($authHeaders != null) {
- $msg->set_parameters(OAuthUtil::decodeAuthorization($authHeaders));
+ $msg->set_parameters(ShindigOAuthUtil::decodeAuthorization($authHeaders));
}
return $msg;
}
Modified: incubator/shindig/trunk/php/src/gadgets/render/GadgetBaseRenderer.php
URL: http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/gadgets/render/GadgetBaseRenderer.php?rev=889239&r1=889238&r2=889239&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/gadgets/render/GadgetBaseRenderer.php (original)
+++ incubator/shindig/trunk/php/src/gadgets/render/GadgetBaseRenderer.php Thu Dec 10 12:43:55 2009
@@ -345,6 +345,7 @@
$styleNode->setAttribute('type', 'text/css');
$styleNode->appendChild($doc->createTextNode(Config::get('gadget_css')));
$node->appendChild($styleNode);
+
// Inject the OpenSocial feature javascripts
$scripts = $this->getJavaScripts();
if ($scripts['external']) {
@@ -423,7 +424,9 @@
"mediaitems.get", "albums.create",
"appdata.delete", "people.update",
"appdata.create"),
- 'http://%host%/gadgets/api/rpc' => array('cache.invalidate'));
+ 'http://%host%/gadgets/api/rpc' => array('cache.invalidate',
+ 'http.head', 'http.get', 'http.put',
+ 'http.post', 'http.delete'));
}
return "gadgets.config.init(" . json_encode($gadgetConfig) . ");\n";
}