OSDN Git Service

embrj
[embrj/master.git] / lib / twitese.php
1 <?php
2         set_time_limit(15);
3         if(!isset($_SESSION)){
4                 session_start();
5         }
6         include_once('mobile_device_detect.php');
7         mobile_device_detect(true,true,true,true,true,true,'https://t.orzdream.com/',false);
8         include_once('config.php');
9         include_once('utility.php');
10         include_once('twitteroauth.php');
11         include_once('oauth_lib.php');
12
13         function refreshProfile(){
14                 $t = getTwitter();
15                 $user = $t->veverify();
16                 $time = $_SERVER['REQUEST_TIME']+3600*24*365;
17                 setcookie('friends_count', $user->friends_count, $time, '/');
18                 setcookie('statuses_count', $user->statuses_count, $time, '/');
19                 setcookie('followers_count', $user->followers_count, $time, '/');
20                 setcookie('imgurl', getAvatar($user->profile_image_url), $time, '/');
21                 setcookie('name', $user->screen_name, $time, '/');
22                 setcookie('listed_count', $user->listed_count, $time, '/');
23         }
24
25         function getDefCookie($name, $default="") {
26                 if (getCookie($name)) return getCookie($name);
27                 else return $default;
28         }
29         function format_time($time){
30                 date_default_timezone_set('UTC');
31                 return strtotime($time);
32         }
33         function formatText($text) {
34                 //如果开启了魔术引号\" \' 转回来
35                 if (get_magic_quotes_gpc()) {
36                         $text = stripslashes($text);
37                 }
38
39                 //添加url链接
40                 $urlReg = '/(((http|https|ftp):\/\/){1}([[:alnum:]\-\.])+(\.)(([[:alnum:]]){2,4})?([[:alnum:]\/+=%#&@\:\;_\.~\?\!\-\,]*))/i';
41                 $text = preg_replace($urlReg, '<a href="\1" target="_blank" rel="noreferrer">\1</a>', $text);
42
43                 //添加@链接
44                 $atReg = '/\B@{1}(([a-zA-Z0-9\_\.\-])+)/i';
45                 $text = preg_replace($atReg,    '<a href="user.php?id=\1" target="_blank">\0</a>', $text);
46
47                 //添加 list 链接
48                 $listReg = '/(\<a[\w+=\:\%\#\&\.~\?\"\'\/\- ]+\>@{1}([a-zA-Z0-9_\.\-]+)<\/a\>([\/a-zA-Z0-9_\.\-]+))/i';
49                 $text = preg_replace($listReg,  '<a href="list.php?id=\2\3" target="_blank">@\2\3</a>', $text);
50
51                 //添加标签链接
52                 $tagReg = "/\B(\#{1}([\w]*[\pN\pC\pL]+[\w]*))([\s]*)/u";
53                 $text = preg_replace($tagReg, '<a target="_blank" href="search.php?q=%23\2">#<span class="hashtag">\2</span></a>\3', $text);
54
55                 $text = formatTweetID($text);
56
57                 return $text;
58         }
59
60         function formatEntities(&$entities,$html){
61                 $user_mentions = $entities->user_mentions;
62                 $hashtags = $entities->hashtags;
63                 $urls = $entities->urls;
64                 if(count($user_mentions) > 0) {
65                         foreach($user_mentions as $user_mention) {
66                                 $name = $user_mention->screen_name;
67                                 $html = str_replace("@$name","<a href=\"user.php?id=$name\" target=\"_blank\">@$name</a>",$html);
68                         }
69                 }
70                 if(count($hashtags) > 0) {
71                         foreach($hashtags as $hashtag) {
72                                 $text = $hashtag->text;
73                                 $html = str_replace("#$text","<a target=\"_blank\" href=\"search.php?q=%23$text\">#<span class=\"hashtag\">$text</span></a>",$html);
74                         }       
75                 }
76                 if(count($urls) > 0) {
77                         $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
78                         foreach($urls as $url) {
79                                 $exp = is_null($url->expanded_url) ? $url->url : $url->expanded_url;
80                                 if(substr($url->url,0,4) != 'http') $url->url = 'http://'.$url->url;
81                                 if(isset($url->display_url)) {
82                                         $dis = $url->display_url;
83                                 } else {
84                                         $tmp = explode('://', $url->url);
85                                         $dis = $tmp[1];
86                                 }
87                                 $html = str_replace($url->url,"<a href=\"$exp\" target=\"_blank\" rel=\"noreferrer\" class=\"tweet_url\">$dis</a>",$html);
88                         }       
89                 }
90                 if(isset($entities->media)) {
91                         $medias = $entities->media;
92                         foreach($medias as $media) {
93                                 $url = $media->media_url_https;
94                                 if (getcookie('p_avatar') == 'true') {
95                                                 $url = 'img.php?imgurl='.$url;
96                                 }
97                                 $html = str_replace($media->url,"<a href=\"$url\" target=\"_blank\" rel=\"noreferrer\">$media->display_url</a>",$html);
98                         }
99                 }
100                 return $html;
101         }
102
103         function formatTweetID($text){
104                 $reg = '/(\<a[\w+=@\:\%\#\&\.~\?\"\'\/\-\! ]+\>[\S]+<\/a\>)/i';
105                 preg_match_all($reg, $text, $tmpMatches);
106                 if(count($tmpMatches) > 0){
107                         $text = preg_replace($reg, '$_holder_$', $text);
108                 }
109                 preg_match_all('/([\d]{10,})/', $text, $matches);
110                 if(count($matches) > 0){
111                         $matches = array_unique($matches[0]);
112                         foreach($matches as $match){
113                                 $text = str_replace($match, '<a title="We think it\'s a tweet ID, isn\'t it?" href="status.php?id='.$match.'" target="_blank">'.$match.'</a>', $text);
114                         }
115                         $tmpReg = '/\$_holder_\$/i';
116                         foreach($tmpMatches[0] as $match){
117                                 $text = preg_replace($tmpReg, $match, $text, 1);
118                         }
119                 }
120                 return $text;
121         }
122
123         function processCurl($url,$postdata=false,$header=false)
124         {
125                 $ch = curl_init($url);
126
127                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
128                 curl_setopt($ch, CURLOPT_VERBOSE, 1);
129                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
130                 curl_setopt($ch, CURLOPT_TIMEOUT,120);
131                 
132                 if($postdata !== false) {
133                         curl_setopt ($ch, CURLOPT_POST, true);
134                         curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
135                 }
136                 
137                 if($header !== false) {
138                         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
139                 }
140                 
141                 $response = curl_exec($ch);
142                 $responseInfo=curl_getinfo($ch);
143                 curl_close($ch);
144                 if( intval( $responseInfo['http_code'] ) == 200 )
145                         return $response;               
146                 else
147                         return false;
148         }
149
150         function objectifyXml( $data ){
151
152                 if( function_exists('simplexml_load_string') ) {
153                         $obj = simplexml_load_string( $data );
154                 }
155                 if (isset($obj->error) || !$obj) return false;
156                 else return $obj;
157
158                 return false;
159         }
160
161         function objectifyJson($data){
162                 if(function_exists("json_decode")){
163                         $obj = json_decode($data);
164                 }
165                 if(!isset($obj->error) || $obj){
166                         return $obj;
167                 }
168                 return false;
169         }
170
171
172         function imageUpload($image){
173                 $t = getTwitter();
174                 $signingurl = API_URL.'/account/verify_credentials.json';
175                 $request = OAuthRequest::from_consumer_and_token($t->consumer, $t->token, 'GET', $signingurl, array());
176                 $request->sign_request($t->sha1_method, $t->consumer, $t->token);
177                 $r_header = $request->to_header("https://api.twitter.com/");
178                 
179                 $url = 'http://img.ly/api/2/upload.json';
180                 $postdata = array('media' => $image);           
181                 $ch = curl_init($url);          
182                 if($postdata !== false)
183                 {
184                         curl_setopt ($ch, CURLOPT_POST, true);
185                         curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
186                 }
187                 curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Service-Provider: '.$signingurl,'X-Verify-Credentials-'.$r_header)); 
188                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
189                 curl_setopt($ch, CURLOPT_USERAGENT, 'embr');
190                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
191                 curl_setopt($ch, CURLOPT_TIMEOUT,120);
192                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
193
194                 $response = curl_exec($ch);
195                 $response_info=curl_getinfo($ch);
196                 curl_close($ch);
197                 
198                 if ($response_info['http_code'] == 200) {
199                         return objectifyJson($response);
200                 } else {
201                         return $response_info['http_code'];
202                 }
203         }
204         
205         function getTwitter() {
206                 if(loginStatus()){
207                         $access_token = $_SESSION['access_token'] ? $_SESSION['access_token'] : null;
208                         $oauth_token = $access_token ? $access_token['oauth_token'] : $_COOKIE['oauth_token'];
209                         $oauth_token_secret = $access_token ? $access_token['oauth_token_secret'] : $_COOKIE['oauth_token_secret'];
210                         $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
211                         return $oauth;
212                 }
213                 return null;
214         }
215
216    function loginStatus() {
217            if(isset($_SESSION['login_status'])){
218               return $_SESSION['login_status'] == 'verified' ? true : false;
219            }elseif(getEncryptCookie("oauth_token") != "" && getEncryptCookie("oauth_token_secret") != "" && getEncryptCookie("user_id") != "" && getEncryptCookie("twitese_name") != ""){
220               $access_token = array("oauth_token" => getEncryptCookie("oauth_token"), "oauth_token_secret" => getEncryptCookie("oauth_token_secret"), "user_id" => getEncryptCookie("user_id"), "screen_name" => getEncryptCookie("twitese_name"));
221               $_SESSION['access_token'] = $access_token;
222               $_SESSION['login_status'] = 'verified';
223               refreshProfile();
224               return true;
225            }
226            return false;
227    }
228
229         function getAvatar($profileImg){
230                 if (getcookie('p_avatar') == 'true') {
231                                 return 'img.php?imgurl='.$profileImg;
232                 }
233                 return preg_replace('/https?:\/\/\w+([0-9])\.twimg\.com/i','https://s3.amazonaws.com/twitter_production',$profileImg);
234         }
235
236         // $target: can't be current user
237         // $source: use the current user as the source user implicitly if not specified
238         // 9 => no relationship
239         // 1 => fo each other
240         // 2 => $source fo $target
241         // 3 => $target fo $source
242         // 4 => $source blocking $target
243         function getRelationship($target, $source = false){
244                 $relationship = getTwitter()->relationship($target, $source)->relationship;
245                 $target = $relationship->target;
246                 $source = $relationship->source;
247                 if($source->blocking != null){
248                         return 4;
249                 }
250                 if($source->following == true && $target->following == true){
251                         return 1;
252                 }
253                 if($source->following == true && $target->following == false){
254                         return 2;
255                 }
256                 if($source->following == false && $target->following == true){
257                         return 3;
258                 }
259                 return 9;
260         }
261         
262         function urlshorten($url, $type='goo.gl'){
263                 switch($type){
264                         case 'goo.gl':
265                         $data = json_encode(array('longUrl' => $url));
266                         $api = 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyDsX2BAo9Jc2yG3Pq1VbLQALqdrtDFvXkg';
267                         $header = array('Content-type: application/json');
268                         $result = objectifyJson(processCurl($api,$data,$header))->id;
269                         break;
270                         case 'zi.mu':
271                         $api = 'http://zi.mu/api.php?format=simple&action=shorturl&url=';
272                         $result = objectifyJson(processCurl($api.rawurlencode($url)));
273                         break;
274                         default:
275                         break;
276                 }
277                 return $result;
278         }
279
280         function expandRedirect($shorturl, &$hops) {
281                 if (count($hops) >= 10) {
282                         return false;
283                 }
284                 $head = array_change_key_case(get_headers($shorturl, TRUE), CASE_LOWER);
285                 if (!isset($head['location']) || empty($head['location'])) {
286                         return $shorturl;
287                 }
288                 $prevhop = $shorturl;
289                 foreach((array)$head['location'] as $redir) {
290                         if (substr($redir, 0, 1)=='/' || preg_match('/[\.\/]'.preg_quote(parse_url($prevhop, PHP_URL_HOST)).'$/', parse_url($redir, PHP_URL_HOST))) {
291                                 return $prevhop;
292                         }
293                         $hops[] = $prevhop;
294                         $prevhop = $redir;
295                 }
296                 return expandRedirect($redir, $hops);
297         }
298 ?>