Skip to content

Instantly share code, notes, and snippets.

@shobotch
Created May 20, 2012 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shobotch/2757162 to your computer and use it in GitHub Desktop.
Save shobotch/2757162 to your computer and use it in GitHub Desktop.
Ktaiweb library var.2
<?php
//メソッド名とか変わってるかもしれないから一応確認してね。TLの取得もできるかもしれないけど、きまぐれで取得できてないからだれかデバッグしてくれるとありがたい
class ktaiWebLibrary{
private $authenticity_token;
private $preliminaryCookie;
private $cookie; //_komadori_session=.+?;なものが入っています。
private $login; //ログインに成功すればtrue 失敗していればfalseが入っています。
public $userAgent = "Mozilla/0 (iPhone;)";//UserAgentを変更する場合はここを編集してください。
/*
* $tweet = new ktaiwebLibrary("user name","pawss word");
*/
public function __construct($username=null,$password=null){
if(!empty($username) && !empty($password)){
return $this->login($username, $password);
}
}
/*
* $tweet->setLoginId(array("cookie"=>"_komadori_session=.+?;","authenticity_token"=>"cookieと紐付いているauthenticity_token"));
* //idとパスワードを知らなくても、cookieとauthenticity_tokenがわかっていればログインすることが出来ます。
* //分散サーバーで動かすときにidとパスワードを使用しないで運用できます
*/
public function setLoginId($login = array()){
$this->cookie = $login["cookie"];
$this->authenticity_token = $login["authenticity_token"];
$this->login = true;
}
/*
* $tweet->getLoginId();
* //返り値
*
* array(
* ["cookie"] => "_komadori_session=.+?;",
* ["authenticity_token"] => "cookieと紐付いているauthenticity_token"
* )
*
* //jsonにして分散サーバーに渡して配列に戻してsetLoginId()をすれば円滑にログイン処理が出来ると思います。
*/
public function getLoginId(){
if(!$this->login)return false;
return array(
"cookie"=>$this->cookie,
"authenticity_token"=>$this->authenticity_token
);
}
/*
* $tweet->login($username,$password);
* //ログイン成功時にはtrue 失敗時にはfalseが帰ってきます。
*/
public function login($username,$password){
$socket = fsockopen("twtr.jp",80);
$request = array(
'GET / HTTP/1.1',
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
"\r\n"
);
fwrite($socket, join($request,"\r\n"));
ob_start();
fpassthru($socket);
$res = ob_get_clean();
$res = explode("\r\n\r\n",$res,2);
//HTMLからauthenticity_tokenを取得
$token["dom"] = @DOMDocument::loadHTML($res[1]);
$token["xml"] = simplexml_import_dom($token["dom"]);
$token["token"] = $token["xml"]->xpath('/html/body/div[3]/form/div/input');
$this->authenticity_token = (string)$token["token"][0]["value"];
//HTMLからCookie(komadori_session)を取得
preg_match("/_komadori_session=.+?;/",$res[0],$matches);
$this->preliminaryCookie = $matches[0];
if(!empty($this->authenticity_token) && !empty($this->preliminaryCookie)){
//ログイン処理
$socket = fsockopen("twtr.jp",80);
$post = http_build_query(
array(
'login'=>$username,
'password'=>$password,
'authenticity_token'=>$this->authenticity_token
),"","&");
//出力例: login=userName&password=password&authenticity_token=authenticity_token
$request = array(
'POST /login/ HTTP/1.1',
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
'Cookie:'.$this->preliminaryCookie,
'Content-type: application/x-www-form-urlencoded',
'Content-length: '.strlen($post)
);
fwrite($socket, implode($request,"\r\n")."\r\n\r\n".$post);
ob_start();
fpassthru($socket);
$res = ob_get_clean();
fclose($socket);
if($this->check_home($res)){
$this->login = true;
$res = explode("\r\n\r\n",$res,2);
preg_match("/_komadori_session=.+?;/",$res[0],$matches);
$this->cookie = $matches[0];
return true;
}else{
$this->login = false;
return false;
}
}
}
/*------------------ツイート関連------------------*/
/*
* $post->tweet("tweet text","リプライ元のid(なければnull)",true);
* //リプライを使用するときは2つ目の引数にリプライ元のツイートidを指定すれば辿ることができます。
* //3つ目の引数をtrueにすれば返り値でつぶやけたかどうか確認することが出来ます。
* //falseにすれば0.4秒ほど速くpostできますが、返り値がありません。連続でpostしたい時におすすめ
*/
public function tweet($tweet,$in_reply_to_status_id="",$response=true){
if(!$this->login)return false;
$socket = fsockopen("twtr.jp",80);
$post = http_build_query(array(
"text"=>$tweet,
"in_reply_to" =>$in_reply_to_status_id,
"authenticity_token"=>$this->authenticity_token
));
$request = array(
"POST /status/create HTTP/1.1",
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
'Cookie: '.$this->cookie,
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($post)
);
fwrite($socket, implode($request,"\r\n")."\r\n\r\n".$post);
//tweetの結果を知りたい時(+0.3秒かかります)
if($response == true){
ob_start();
fpassthru($socket);
$res = ob_get_clean();
fclose($socket);
return $this->check_home($res);
}
}
/*
* $post->reTweet($username,$status_id);
* //ユーザ名は違っていてもたしか動いたはず。
* //ステータスidにRTしたいツイートのidを入れてあげればできると思う
* //ktaiweb側での返り値がないので、RTできたかの確認は各自してください。
*/
public function reTweet($username,$status_id){
if(!$this->login)return false;
$socket = fsockopen("twtr.jp",80);
$post = http_build_query(array(
"screen_name"=>$username,
"id"=>$status_id,
"authenticity_token"=>$this->authenticity_token,
));
$request = array(
'POST /user/'.$username.'/status/retweet/'.$status_id.' HTTP/1.1',
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
'Cookie: '.$this->cookie,
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($post)
);
fwrite($socket, implode($request,"\r\n")."\r\n\r\n".$post);
}
/*
* $post->favorite($username,$status_id);
* //ユーザ名は違っていてもたしか動いたはず。
* //ステータスidにふぁぼりたいツイートのidを入れてあげればできると思う
* //ktaiweb側での返り値がないので、ふぁぼれたかの確認は各自してください。
*/
public function favorite($username,$status_id){
if(!$this->login)return false;
$socket = fsockopen("twtr.jp",80);
$post = http_build_query(array(
"authenticity_token"=>$this->authenticity_token,
));
$request = array(
'POST /favorite/create/'.$username.'/status/'.$status_id.' HTTP/1.1',
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
'Cookie: '.$this->cookie,
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($post)
);
fwrite($socket, implode($request,"\r\n")."\r\n\r\n".$post);
}
/*------------------タイムライン関連------------------*/
public function getTL($page=1){
if(!$this->login)return false;
$socket = fsockopen("twtr.jp",80);
$request = array(
'GET /home?page='.$page.' HTTP/1.1',
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
'Cookie: '.$this->cookie,
"\r\n"
);
fwrite($socket, join($request,"\r\n"));
ob_start();
fpassthru($socket);
$res = ob_get_clean();
$response = explode("\r\n\r\n",$res,2);
return $this->analyzeTL($response[1]);
}
//ここから先の関数はログイン処理等に使います
private function getAuthenticity_token($set = false){
$socket = fsockopen("twtr.jp",80);
$request = array(
'GET / HTTP/1.1',
'Host: twtr.jp',
'User-Agent: '.$this->userAgent,
"\r\n"
);
fwrite($socket, join($request,"\r\n"));
ob_start();
fpassthru($socket);
$res = ob_get_clean();
$res = explode("\r\n\r\n",$res,2);
//HTMLからauthenticity_tokenを取得
$token["dom"] = @DOMDocument::loadHTML($res[1]);
$token["xml"] = simplexml_import_dom($token["dom"]);
$token["token"] = $token["xml"]->xpath('/html/body/div[3]/form/div/input');
if($set != false){
$this->authenticity_token = (string)$token["token"][0]["value"];
}
return (string)$token["token"][0]["value"];
}
private function check_home($res){
preg_match("/^Location: http:\/\/twtr.jp\/(.+)\r\n/m",$res,$matches);
if(isset($matches[1]) && $matches[1]==="home"){
return true;
}else {
return false;
}
}
public function analyzeTL($body){
$mat = array();
preg_match_all("/<div class=\"(first|continue|separated)\".*?>(.*?)<\/div>.*?<\/div>.*?<\/div>/us",$body,$matches);
foreach ($matches[0] as $match){
preg_match_all("/<a href=\"http:\/\/twtr.jp\/user\/.+\/status\">(?P<screen_name>.*?)<\/a>\n\n (?P<text>.*?)\n\n\n <div class=\"meta\">\n (?P<meta>.*?)\n <div class=\"right\">.*?<a href=\"http:\/\/twtr.jp\/user\/.+?\/status\/(?P<status_id>.*?)\">.+?<\/a><\/div>.*?<\/div>.*?<\/div>/us", $match, $_matches);
if(isset($_matches["screen_name"][0]) && isset($_matches["text"][0]) && isset($_matches["meta"][0]) && isset($_matches["status_id"][0])){
$mat[] = array(
"screen_name" => $_matches["screen_name"][0],
"text" => $_matches["text"][0],
"meta" => $_matches["meta"][0],
"status_id" => $_matches["status_id"][0],
);
}
}
if(is_array($mat)){
return $mat;
}
}
private function aanalyzeTimeline($body) {
preg_match_all("/<div class=\"(first|separated).*?\">\n (.+?)<\/div>\n <\/div>\n<\/div>/us",mb_convert_encoding($body,'UTF-8'),$matches);
Foreach($matches[2] as $match) {
preg_match("/<a href=\"http:\/\/twtr.jp\/user\/.+\/status\">(?P<screen_name>.*?)<\/a>(?P<text>.*?)<div class=\"meta\">(?P<meta>.*?)<div class=\"right\">.*?<a href=\"http:\/\/twtr.jp\/user\/.+?\/status\/(?P<status_id>.*?)\">.+?<\/a><\/div>.*?<\/div>.*?<\/div>/us",$match,$_matches);
preg_match("/\s+(<img.*?\/>\n \n )?(.+?(前|以内))/us",$_matches["details"],$__matches);
If (preg_match("/\s+<br \/>(.+)がリツイート/us",$_matches["details"],$___matches)) {
$retweet = $___matches[1];
} Else {
$retweet = "";
}
$results[] = array(
"img"=>$_matches["img"],
"screen_name"=>$_matches["screen_name"],
"text"=>$_matches["text"],
"raw_text"=>strip_tags($_matches["text"]),
"status_id"=>$_matches["status_id"],
"created_at"=>$__matches[2],
"retweet"=>$retweet,
);
}
Foreach ($results as $result) {
If ($result["img"] != NULL) {
$_results[] = $result;
}
}
Return $_results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment