powered by nequal
Home » Services_Twitter » Timeline » 1510

Changeset 1510 -- 2010-01-12 17:28:46

Author
悠希@Ariela
Comment
トークンの保存、読み込みロジックを外部関数で定義するように変更。 (複数ユーザ対応アプリケーション向け)

Diffs

Services_Twitter/trunk/example.php

@@ -5,18 +5,24 @@
// Services_Twitterの設定情報
$config = new Services_Twitter_Config();
+// アプリケーション認識キーの設定
+$config->setApplicationKey(sha1('Services_Twitter Example Code'));
+
+// 登録情報のCookieキーの設定
+$config->setCookieName('services_twitter_id');
+
// コンシューマキーの設定
// テスト値:Services_Twitterのコンシューマキーを利用
$config->setConsumer('Rzt2HVOtG1TmcgtE8r1rQ','DDHJGoElzijet5AWsNWkazAQvhVDaoxSqru20oDrdM');
-// 認証情報ファイルのパス設定
-$config->setAuthFile(dirname(__FILE__) . DIRECTORY_SEPARATOR . '.twitter');
+// トークンの読み込み・書き込み処理を登録
+$config->setTokenReadFunction('readTokens');
+$config->setTokenSaveFunction('saveTokens');
// 認証ページ、認証コールバックURIの設定
$config->setAuthPage(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'example.template.php');
$config->setCallback('http://localhost/stw/trunk/example.php');
-
// Services_Twitterのインスタンス化
$tweet = new Services_Twitter($config);
@@ -24,11 +30,33 @@
//未認証時は認証用のページが表示される。
$tweet->connect();
-// APIの利用状況を取得する。
-$limit = $tweet->getRateLimitStatus();
-debug($limit);
+// 認証情報の設定
+if ($tweet->isAuthorized()) {
+    // APIの利用状況を取得する。
+    $limit = $tweet->getRateLimitStatus();
+    debug($limit);
+}
+/**
+ * 保存したトークンを取得する
+ */
+function readTokens() {
+    $authfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.twitter';
+    if (file_exists($authfile)) {
+        return unserialize(file_get_contents($authfile));
+    }
+    return null;
+}
+
+/**
+ * トークンを保存する
+ */
+function saveTokens($tokens) {
+    $authfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.twitter';
+    file_put_contents($authfile, serialize($tokens));
+}
+
function debug($value) {
echo '<pre>';
var_dump($value);

Services_Twitter/trunk/Services/Twitter/Connection.php

@@ -44,20 +44,12 @@
* Services_Twitterの通信クラスをインスタンス化する
* @param Services_Twitter_Config $config Services_Twitter設定クラス
*/
-    public function __construct($config) {
+    public function __construct(&$config) {
$this->_config = $config;
// 認証情報を取得する
-        $authFile = $this->_config->getAuthFile();
-        if (file_exists($authFile)) {
-            $this->_authInfo = unserialize(file_get_contents($authFile));
-        } else {
-            $this->_authInfo = array(
-                 'oauth_access_token' => null
-                ,'oauth_access_token_secret' => null
-            );
-        }
-
+        $config = $this->_config;
+        $this->_authInfo = $config->raiseTokenRead();
}
/**
@@ -124,13 +116,24 @@
$_SESSION['oauth_state'] === 'authorized';
-        $authFile = $this->_config->getAuthFile();
-        file_put_contents($authFile, serialize($this->_authInfo));
+        $config = $this->_config;
+        $config->raiseTokenSave($this->_authInfo);
+
+        $authValue = sha1($config->getApplicationKey()
+                            . $this->_oauth->getToken()
+                            . $this->_oauth->getTokenSecret());
+
+        setcookie($this->_config->getCookieName(), $authValue);
+
// リダイレクト
-        header('Location: ' . $this->_config->getCallback());
+        header('Location: ' . $config->getCallback());
}
+    public function sendRequest($target, $args, $method) {
+        return $this->_oauth->sendRequest($target, $args, $method);
+    }
+
/**
*
* @return unknown_type
@@ -144,11 +147,16 @@
$requri = $this->_oauth->getAuthorizeURL('https://twitter.com/oauth/authorize');
-        if ($this->_auth_page !== null) {
-            require_once($this->_auth_page);
+        $authPage = $this->_config->getAuthPage();
+        if ($authPage !== null) {
+            require_once($authPage);
} else {
printf('<a href="%s">認証</a>', $requri);
}
die(0);
}
+
+    public function &getAuthInfo() {
+    	return $this->_authInfo;
+    }
}
\ ファイルの末尾に改行がありません

Services_Twitter/trunk/Services/Twitter/Config.php

@@ -1,12 +1,30 @@
<?php
class Services_Twitter_Config
{
+
+	/**
+	 * アプリケーション認識キーを保持する
+	 * @var string アプリケーション認識キー
+	 */
+	private $_appKey;
+
+	/**
+	 * 認証認識キーを保存するCookieの名称を保持する
+	 * @var string 認証認識キーを保存するCookieの名称
+	 */
+	private $_cookieName;
+
+	/**
+	 * 接続用トークンを保持する
+	 * @var string 接続用トークン
+	 */
+	private $_token;
+
/**
-     * 認証情報保存ファイルのパスを保持する
-     *
-     * @var string ファイルパス
+     * 接続用秘密トークンを保持する
+     * @var string 接続用秘密トークン
*/
-    private $_authFile;
+	private $_token_secret;
/**
* TwitterのOAuth認証に利用されるコンシューマキーを保持する
@@ -33,10 +51,23 @@
private $_callback;
/**
+     * トークンを読み込む関数を保持する
+     * @var callback トークンを読み込む関数
+     */
+    private $_tokenReadFunc;
+
+    /**
+     * トークンを保存する関数を保持する
+     * @var callback トークンを保存する関数
+     */
+    private $_tokenSaveFunc;
+
+    /**
* Services_Twitter_Configのインスタンスを作成する
*
*/
public function __construct() {
+    	$this->_cookieName = 'stid';
$this->_authFile = realpath('./') . DIRECTORY_SEPARATOR . 'twitter.auth';
$this->_consumer_key    = 'Rzt2HVOtG1TmcgtE8r1rQ';
$this->_consumer_secret = 'DDHJGoElzijet5AWsNWkazAQvhVDaoxSqru20oDrdM';
@@ -55,22 +86,64 @@
}
/**
-     * 認証情報保存ファイルのパスを設定する
-     * @param string $path 認証情報保存ファイルのパス
+     * アプリケーション認識キーを設定する
+     * @param string $key アプリケーション認識キー
*/
-    public function setAuthFile($path) {
-        $this->_authFile = $path;
+    public function setApplicationKey($key) {
+        $this->_appKey = $key;
}
/**
-     * 認証情報保存ファイルのパスを取得する
-     * @return string 認証情報保存ファイルのパス
+     * アプリケーション認識キーを取得する
+     * @return string アプリケーション認識キー
*/
-    public function getAuthFile() {
-    	return $this->_authFile;
+    public function getApplicationKey() {
+    	return $this->_appKey;
}
/**
+     * 認証認識キーを保存するCookieの名称を設定する
+     * @param string $name 認証認識キーを保存するCookieの名称
+     */
+    public function setCookieName($name) {
+    	$this->_cookieName = $name;
+    }
+
+    /**
+     * 認証認識キーを保存するCookieの名称を取得する
+     * @return string 認証認識キーを保存するCookieの名称
+     */
+    public function getCookieName() {
+    	return $this->_cookieName;
+    }
+
+    /**
+     * 接続用トークンを設定する
+     * @param string $token トークン
+     * @param string $tokenSecret 秘密トークン
+     */
+    public function setToken($token, $tokenSecret) {
+    	$this->_token = $token;
+    	$this->_token_secret = $tokenSecret;
+    }
+
+    /**
+     * 接続用トークンを取得する
+     * @return string トークン
+     */
+    public function getToken() {
+    	return $this->_token;
+    }
+
+    /**
+     * 接続用秘密トークンを取得する
+     * @return string 秘密トークン
+     */
+    public function getTokenSecret() {
+    	return $this->_token_secret;
+    }
+
+    /**
* TwitterのOAuth認証に利用されるコンシューマキー、シークレットを設定する
* @param string $key コンシューマキー
* @param string $secret コンシューマシークレット
@@ -127,4 +200,39 @@
public function getCallback() {
return $this->_callback;
}
+
+    public function setTokenReadFunction($callback) {
+    	$this->_tokenReadFunc = $callback;
+    }
+
+    public function setTokenSaveFunction($callback) {
+    	$this->_tokenSaveFunc = $callback;
+    }
+
+    public function getAuthInfo() {
+        $authInfo = array(
+             'oauth_access_token' => $this->getToken()
+            ,'oauth_access_token_secret' => $this->getTokenSecret()
+        );
+
+        return $authInfo;
+    }
+
+    public function raiseTokenRead() {
+        $tokens = call_user_func($this->_tokenReadFunc);
+        $this->setToken($tokens['oauth_access_token'], $tokens['oauth_access_token_secret']);
+        return $this->getAuthInfo();
+    }
+
+    public function raiseTokenSave($tokens) {
+        call_user_func($this->_tokenSaveFunc, $tokens);
+    }
+
+
+/*
+    private $_tokenReadFunc;
+    private $_tokenSaveFunc;
+$config->setAuthInfoReaderFunction('readTokens');
+$config->setAuthInfoRegisterFunction('saveTokens');
+ */
}
\ ファイルの末尾に改行がありません

Services_Twitter/trunk/Services/Twitter.php

@@ -24,19 +24,13 @@
*/
private $_config;
-    // データ保持 ==================================================================================
-
/**
-     * 認証情報を保持する
-     * @var array OAuthトークン情報
+     * Services_Twitterの接続情報を保持する
+     * @var Services_Twitter_Connection 接続情報
*/
-    private $_authInfo;
+    private $_connection;
-    /**
-     * HTTP_OAuthのインスタンスを保持する
-     * @var object HTTP_OAuthのインスタンス
-     */
-    private $_oauth;
+    // データ保持 ==================================================================================
/**
* APIの設定を保持する
@@ -60,7 +54,7 @@
* Services_Twitterをインスタンス化します
* @return Services_Twitter インスタンス
*/
-    public function __construct($config = null) {
+    public function __construct(&$config = null) {
$this->_apiConfigs =
simplexml_load_file(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Twitter/API.xml');
@@ -69,110 +63,18 @@
} else {
$this->_config = new Services_Twitter_Config();
}
+
+        $this->_connection = new Services_Twitter_Connection($this->_config);
}
/**
* OAuthにてTwitterへのアクセスを行う
*/
public function connect() {
-		session_start();
-
-		// 認証情報を取得する
-		$config = $this->_config;
-		$authFile = $config->getAuthFile();
-		if (file_exists($authFile)) {
-			$this->_authInfo = unserialize($authFile);
-		} else {
-			$this->_authInfo = array(
-				 'oauth_access_token' => null
-				,'oauth_access_token_secret' => null
-			);
-		}
-
-		try {
-			$this->_oauth = new HTTP_OAuth_Consumer($config->getConsumerKey(), $config->getConsumerSecret());
-			$http_request = new HTTP_Request2();
-			$http_request->setConfig('ssl_verify_peer', false);
-			$consumer_request = new HTTP_OAuth_Consumer_Request();
-			$consumer_request->accept($http_request);
-			$this->_oauth->accept($consumer_request);
-
-			if(!empty($_REQUEST['oauth_token']) && $_SESSION['oauth_state'] === 'start') {
-				// 認証から戻ってきた場合
-				$this->resultAuthorization();
-			}
-
-			if (!empty($this->_authInfo['oauth_access_token']) && !empty($this->_authInfo['oauth_access_token_secret'])) {
-				// 認証済みの場合
-				$this->_oauth->setToken($this->_authInfo['oauth_access_token']);
-				$this->_oauth->setTokenSecret($this->_authInfo['oauth_access_token_secret']);
-			} else {
-				// 未承認の場合
-				$this->reconnect();
-				$this->callAuthorization();
-			}
-		} catch (Exception $e) {
-			die($e->getMessage());
-		}
+		$this->_connection->authorize();
}
/**
-	 * セッション情報を作り直す。
-	 */
-	public function reconnect() {
-		$_SESSION = null;
-		session_destroy();
-		session_start();
-	}
-
-	/**
-	 * トークンを取得し、認証情報保存ファイルへ保存するメソッド
-
-	 */
-	private function resultAuthorization() {
-
-		if (empty($this->_authInfo['oauth_access_token']) || empty($this->_authInfo['oauth_access_token_secret'])) {
-			// トークンが未取得の場合
-			$this->_oauth->setToken($_SESSION['oauth_request_token']);
-			$this->_oauth->setTokenSecret($_SESSION['oauth_request_token_secret']);
-
-			$verifier = $_GET['oauth_verifier'];
-			$token = $this->_oauth->getAccessToken('https://twitter.com/oauth/access_token', $verifier);
-
-			// トークンを保存
-			$this->_authInfo['oauth_access_token'] = $this->_oauth->getToken();
-			$this->_authInfo['oauth_access_token_secret'] = $this->_oauth->getTokenSecret();
-
-			$config = $this->_config;
-            $authFile = $config->getAuthFile();
-
-			file_put_contents($authFile, serialize($this->_authInfo));
-		}
-		$_SESSION['oauth_state'] = 'returned';
-	}
-
-	/**
-	 * 認証を行う為のURIを表示するメソッド
-	 */
-	private function callAuthorization() {
-		$config = $this->_config;
-		$this->_oauth->getRequestToken('https://twitter.com/oauth/request_token', $config->getCallback());
-
-		$_SESSION['oauth_request_token'] = $this->_oauth->getToken();
-		$_SESSION['oauth_request_token_secret'] = $this->_oauth->getTokenSecret();
-		$_SESSION['oauth_state'] = 'start';
-
-		$requri = $this->_oauth->getAuthorizeURL('https://twitter.com/oauth/authorize');
-
-     	if ($config->getAuthPage() !== null) {
-		    require_once($config->getAuthPage());
-		} else {
-    		printf('<a href="%s">認証</a>', $requri);
-		}
-		die(0);
-	}
-
-	/**
* 通信した結果のステータスコードを取得する
* @return int ステータスコード
*/
@@ -194,7 +96,7 @@
* @return bool 通信が正常に終了したかどうかを返す
*/
private function sendRequest($config) {
-		$req = $this->_oauth->sendRequest($config['Target'], $config['Args'], $config['Method']);
+		$req = $this->_connection->sendRequest($config['Target'], $config['Args'], $config['Method']);
$this->_status = $req->getStatus();
@@ -412,5 +314,13 @@
return $result;
}
+	public function getAuthInfo() {
+        return $this->_connection->getAuthInfo();
+	}
+
+	public function isAuthorized() {
+		return $this->_connection->isAuthorized();
+	}
+
}
?>
\ ファイルの末尾に改行がありません