Skip to content

Instantly share code, notes, and snippets.

@ksz
Created July 2, 2010 03:23
Show Gist options
  • Save ksz/460887 to your computer and use it in GitHub Desktop.
Save ksz/460887 to your computer and use it in GitHub Desktop.
<?php
App::import('Vendor', 'twitteroauth', array('file' => 'twitteroauth'.DS.'twitteroauth'.DS.'twitteroauth.php'));
class TwitterComponent extends Object
{
// user_id
var $user_id = '';
// screen_name
var $screen_name = '';
// consumer key
var $consumer_key = '';
// consumer secret
var $consumer_secret = '';
// access token
var $access_token = '';
// access token secret
var $access_token_secret = '';
// yahoo API key
var $yahoo_key = '';
// Twitter OAuth Object
var $twitter = null;
// ログレベル
var $loglevel = 3;
// ログディレクトリ
var $logdir = '';
// 結果メッセージ
var $result_message = '';
/*
* 初期化
*/
function initialize(&$controller, $params)
{
$this->controller = $controller;
$this->consumer_key = $params[0];
$this->consumer_secret = $params[1];
if (isset($this->controller->Session) && $token = $this->controller->Session->read('Twitter.auth')) {
$this->user_id = $token['user_id'];
$this->screen_name = $token['screen_name'];
$this->access_token = $token['oauth_token'];
$this->access_token_secret = $token['oauth_token_secret'];
} else {
if (isset($params[2])) {
$this->access_token = $params[2];
}
if (isset($params[3])) {
$this->access_token_secret = $params[3];
}
if (isset($params[4])) {
$this->screen_name = $params[4];
}
}
if ($this->access_token && $this->access_token_secret) {
$this->twitter = new TwitterOAuth($this->consumer_key,
$this->consumer_secret,
$this->access_token,
$this->access_token_secret);
} else {
$this->twitter = new TwitterOAuth($this->consumer_key,
$this->consumer_secret);
}
$this->logdir = LOGS . DS . 'twitter';
@mkdir($this->logdir);
$this->logdir .= DS . $this->screen_name;
@mkdir($this->logdir);
}
/*
* 認証URL取得
*/
function getRequestURL()
{
$token = $this->twitter->getRequestToken();
return $this->twitter->getAuthorizeURL($token);
}
/*
* 認証情報の取得
*/
function getAccessToken()
{
$param = array();
$param['oauth_consumer_key'] = $this->consumer_key;
$param['oauth_signature_method'] = 'HMAC-SHA1';
$param['oauth_timestamp'] = time();
$param['oauth_token'] = $this->controller->params['url']['oauth_token'];
$token = $this->twitter->getAccessToken($param);
$this->user_id = $token['user_id'];
$this->secreen_name = $token['screen_name'];
$this->access_token = $token['oauth_token'];
$this->access_token_secret = $token['oauth_token_secret'];
$this->controller->Session->write('Twitter.auth', $token);
return $token;
}
/*
* ツイート
*/
function tweet($status)
{
if ('string' == gettype($status)) {
$status = array('status' => $status);
}
if ('array' != gettype($status)) {
return false;
}
$result = $this->twitter->OAuthRequest('http://api.twitter.com/1/statuses/update.xml', 'POST', $status);
$this->result_message = $status['status'];
if ($this->_logging($result, 'tweet')) {
return $status['status'];
} else {
return false;
}
}
/*
* リプライ
*/
function reply($screen_name, $status)
{
if ('string' == gettype($status)) {
$status = '@' . $screen_name . ' ' . $status;
} else if ('array' == gettype($status)) {
$status['status'] = '@' . $screen_name . ' ' . $status['status'];
}
return $this->tweet($status);
}
/*
* .付きリプライ
*/
function replyToAll($screen_name, $status)
{
if ('string' == gettype($status)) {
$status = '.@' . $screen_name . ' ' . $status;
} else if ('array' == gettype($status)) {
$status['status'] = '.@' . $screen_name . ' ' . $status['status'];
}
return $this->tweet($status);
}
/*
* 非公式リツイート
*/
function retweet($screen_name, $status, $original_text)
{
$status_origin = $status;
if ('string' == gettype($status)) {
$status = $status . ' RT ' . '@' . $screen_name . ' ' . $original_text;
} else if ('array' == gettype($status)) {
$status['status'] = $status['status'] . ' RT ' . '@' . $screen_name . ' ' . $original_text;
}
if (mb_strlen($rt_status) >= 140) {
return $this->reply($screen_name, $status_origin);
}
return $this->tweet($status);
}
/*
* ホームタイムラインのエイリアス
*/
function getTimeline($option = array('count' => 30))
{
return $this->getHomeTimeline($option);
}
/*
* 公開タイムラインの取得
*/
function getPublicTimeline($option = array('count' => 30))
{
$result = $this->twitter->OAuthRequest('http://api.twitter.com/1/statuses/public_timeline.xml', 'GET', $option);
$this->result_message = "Get Public Timeline";
return $this->_logging($result, 'public');
}
/*
* ホームタイムラインの取得
*/
function getHomeTimeline($option = array('count' => 30))
{
$result = $this->twitter->OAuthRequest('http://api.twitter.com/1/statuses/friends_timeline.xml', 'GET', $option);
$this->result_message = "Get Home Timeline";
return $this->_logging($result, 'timeline');
}
/*
* フレンドタイムラインの取得
*/
function getFriendTimeline($option = array('count' => 30))
{
$result = $this->twitter->OAuthRequest('http://api.twitter.com/1/statuses/friends_timeline.xml', 'GET', $option);
$this->result_message = "Get Friend Timeline";
return $this->_logging($result, 'timeline');
}
/*
* メンションの取得
*/
function getMention($option = array('count' => 30))
{
$result = $this->twitter->OAuthRequest('http://api.twitter.com/1/statuses/mentions.xml', 'GET', $option);
$this->result_message = "Get Mention";
return $this->_logging($result, 'mention');
}
/*
* フォロー
*/
function follow($screen_name)
{
$result = $this->twitter->OAuthRequest("http://api.twitter.com/1/friendships/create/{$screen_name}.xml", 'POST', array());
$this->result_message = "Follow to {$screen_name}";
return $this->_logging($result, 'follow');
}
/*
* リフォロー
*/
function refollow($option = array())
{
$result = $this->twitter->OAuthRequest('http://api.twitter.com/1/statuses/followers.xml', 'GET', $option);
$this->result_message = "Get Followers";
$xml = $this->_logging($result, 'followers');
foreach($xml->user as $user) {
if ($user->following == 'false') {
$this->follow($user->screen_name);
}
}
return $xml;
}
/*
* ふぁぼる
*/
function favorite($status_id)
{
$result = $this->twitter->OAuthRequest("http://api.twitter.com/1/favorites/create/{$status_id}.xml", "POST", array());
$this->result_message = "Favolite to {$status_id}";
return $this->_logging($result, 'favorite');
}
/*
* 検索
*/
function search($query, &$xml = null)
{
$this->_writeDayLog('results', "Search for {$query}");
$query = urlencode($query);
$url = "http://search.twitter.com/search.atom?q={$query}";
$xml = simplexml_load_file($url);
$results = array();
foreach($xml->entry as $entry) {
$result['screen_name'] = r('http://twitter.com/', '', $entry->author->uri);
$result['text'] = (String)$entry->title;
$results[] = $result;
}
return $results;
}
/*
Yahooの形態日本語解析APIへ問い合わせ
*/
function analysSentence($sentence, $yahoo_key = null)
{
if (!$this->yahoo_key && !$yahoo_key) {
return false;
} else if ($yahoo_key) {
$this->yahoo_key = $yahoo_key;
}
$url = 'http://jlp.yahooapis.jp/MAService/V1/parse?';
$url .= "appid={$this->yahoo_key}&";
//$url .= 'results=ma&';
//$url .= 'filter=9&';
$url .= 'sentence=' . urlencode($sentence);
$xml = simplexml_load_file($url);
return $xml;
}
/*
* 解析結果センテンスの品詞を表示
*/
function dumpSentence($sentence)
{
$xml = $this->analysSentence($sentence);
foreach ($xml->ma_result->word_list->word as $cur) {
echo $cur->surface . ':' . $cur->pos . "\n";
}
}
/*
* ログ出力
*/
function _logging($result, $logtype = '')
{
if (strstr($result, 'Twitter is over capacity.')) {
return false;
}
$xml = simplexml_load_string($result);
// XMLログ
if ($this->loglevel >= 5) {
if (!$logtype) {
@mkdir($this->logdir . DS . 'xml');
file_put_contents($this->logdir . DS . 'xml' . DS . date('Y-m-d-H-i-s') . '.xml', $result);
} else {
@mkdir($this->logdir . DS . $logtype);
file_put_contents($this->logdir . DS . $logtype . DS . date('Y-m-d-H-i-s') . '.xml', $result);
}
}
// APIリミットログ
if ($this->loglevel >= 4) {
$limit = simplexml_load_file('http://twitter.com/account/rate_limit_status.xml');
$mes = 'hourly-limit=' . $limit->{"hourly-limit"} . ' ';
$mes .= 'remaining-hits=' . $limit->{"remaining-hits"} . ' ';
$mes .= 'reset-time=' . date('Y-m-d H:i:s', $limit->{"reset-time-in-seconds"} * 1);
$this->_writeDayLog('limits', $mes);
}
// ポスト数ログ
if ($this->loglevel >= 3 && $logtype == 'tweet' && !$xml->error) {
if ($cnt = @file_get_contents($this->logdir . DS . 'posts' . DS . date('Y-m-d') . DS . date('Y-m-d-H'))) {
$cnt ++;
} else {
$cnt = 1;
}
$this->_writeHourLog('posts', $cnt, false, false);
}
// 結果ログ
if ($this->loglevel >= 2 && !$xml->error) {
$this->_writeDayLog('results', $this->result_message);
}
// エラーログ
if ($this->loglevel >= 1 && $xml->error) {
$this->_writeDayLog('errors', $xml->error);
$this->result_message = $xml->error;
return false;
}
return $xml;
}
/*
* ログファイル書き込み(日にちごと)
*/
function _writeDayLog($dirname, $message, $addtime = true, $append = true)
{
$this->_writeLog(date('Y-m-d'), $dirname, $message, $addtime, $append);
}
/*
* ログファイル書き込み(時間ごと)
*/
function _writeHourLog($dirname, $message, $addtime = true, $append = true)
{
$this->_writeLog(date('Y-m-d-H'), $dirname, $message, $addtime, $append);
}
/*
* ログファイル書き込み
*/
function _writeLog($filename, $dirname, $message, $addtime = true, $append = true)
{
$dir = $this->logdir . DS . $dirname;
@mkdir($dir);
$dir .= DS . date('Y-m');
@mkdir($dir);
if ($addtime) {
$message = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
} else {
$message .= "\n";
}
if ($append) {
file_put_contents($dir . DS . $filename . '.log', $message, FILE_APPEND);
} else {
file_put_contents($dir . DS . $filename . '.log', $message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment