]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
99ca2ada6143003d7ffbd7da432604f1a93bf59e
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2010 StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) {
21     exit(1);
22 }
23
24 define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
25
26 require_once INSTALLDIR . '/plugins/TwitterBridge/twitterbasicauthclient.php';
27 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
28
29 function add_twitter_user($twitter_id, $screen_name)
30 {
31     // Clear out any bad old foreign_users with the new user's legit URL
32     // This can happen when users move around or fakester accounts get
33     // repoed, and things like that.
34
35     $luser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
36
37     if (!empty($luser)) {
38         $result = $luser->delete();
39         if ($result != false) {
40             common_log(
41                 LOG_INFO,
42                 "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
43             );
44         }
45     }
46
47     $fuser = new Foreign_user();
48
49     $fuser->nickname = $screen_name;
50     $fuser->uri = 'http://twitter.com/' . $screen_name;
51     $fuser->id = $twitter_id;
52     $fuser->service = TWITTER_SERVICE;
53     $fuser->created = common_sql_now();
54     $result = $fuser->insert();
55
56     if (empty($result)) {
57         common_log(LOG_WARNING,
58             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
59         common_log_db_error($fuser, 'INSERT', __FILE__);
60     } else {
61         common_log(LOG_INFO,
62                    "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
63     }
64
65     return $result;
66 }
67
68 // Creates or Updates a Twitter user
69 function save_twitter_user($twitter_id, $screen_name)
70 {
71     // Check to see whether the Twitter user is already in the system,
72     // and update its screen name and uri if so.
73
74     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
75
76     if (!empty($fuser)) {
77
78         // Delete old record if Twitter user changed screen name
79
80         if ($fuser->nickname != $screen_name) {
81             $oldname = $fuser->nickname;
82             $fuser->delete();
83             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
84                                          'for Twitter user %1$d - %2$s, was %3$s.',
85                                          $fuser->id,
86                                          $screen_name,
87                                          $oldname));
88         }
89
90     } else {
91
92         // Kill any old, invalid records for this screen name
93
94         $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
95
96         if (!empty($fuser)) {
97             $fuser->delete();
98             common_log(
99                 LOG_INFO,
100                 sprintf(
101                     'Twitter bridge - deteted old record for Twitter ' .
102                     'screen name "%s" belonging to Twitter ID %d.',
103                     $screen_name,
104                     $fuser->id
105                 )
106             );
107         }
108     }
109
110     return add_twitter_user($twitter_id, $screen_name);
111 }
112
113 function is_twitter_bound($notice, $flink) {
114
115     // Check to see if notice should go to Twitter
116     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
117
118         // If it's not a Twitter-style reply, or if the user WANTS to send replies,
119         // or if it's in reply to a twitter notice
120
121         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
122             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) ||
123             is_twitter_notice($notice->reply_to)) {
124             return true;
125         }
126     }
127
128     return false;
129 }
130
131 function is_twitter_notice($id)
132 {
133     $notice = Notice::staticGet('id', $id);
134
135     if (empty($notice)) {
136         // it's not any kind of notice, so it's definitely not a Twitter notice.
137         return false;
138     }
139
140     return ($notice->source == 'twitter');
141 }
142
143 function broadcast_twitter($notice)
144 {
145     $flink = Foreign_link::getByUserID($notice->profile_id,
146                                        TWITTER_SERVICE);
147
148     // Don't bother with basic auth, since it's no longer allowed
149
150     if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
151         if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
152             return retweet_notice($flink, Notice::staticGet('id', $notice->repeat_of));
153         } else if (is_twitter_bound($notice, $flink)) {
154             return broadcast_oauth($notice, $flink);
155         }
156     }
157
158     return true;
159 }
160
161 function retweet_notice($flink, $notice)
162 {
163     $token = TwitterOAuthClient::unpackToken($flink->credentials);
164     $client = new TwitterOAuthClient($token->key, $token->secret);
165
166     $id = twitter_status_id($notice);
167
168     try {
169         $status = $client->statusesRetweet($id);
170     } catch (OAuthClientException $e) {
171         return process_error($e, $flink, $notice);
172     }
173 }
174
175 function twitter_status_id($notice)
176 {
177     if ($notice->source == 'twitter' &&
178         preg_match('#^http://twitter.com/[\w_.]+/status/(\d+)$#', $notice->uri, $match)) {
179         return $match[1];
180     }
181
182     return null;
183 }
184
185 /**
186  * Pull any extra information from a notice that we should transfer over
187  * to Twitter beyond the notice text itself.
188  *
189  * @param Notice $notice
190  * @return array of key-value pairs for Twitter update submission
191  * @access private
192  */
193 function twitter_update_params($notice)
194 {
195     $params = array();
196     if ($notice->lat || $notice->lon) {
197         $params['lat'] = $notice->lat;
198         $params['long'] = $notice->lon;
199     }
200     return $params;
201 }
202
203 function broadcast_oauth($notice, $flink) {
204     $user = $flink->getUser();
205     $statustxt = format_status($notice);
206     $params = twitter_update_params($notice);
207
208     $token = TwitterOAuthClient::unpackToken($flink->credentials);
209     $client = new TwitterOAuthClient($token->key, $token->secret);
210     $status = null;
211
212     try {
213         $status = $client->statusesUpdate($statustxt, $params);
214     } catch (OAuthClientException $e) {
215         return process_error($e, $flink, $notice);
216     }
217
218     if (empty($status)) {
219
220         // This could represent a failure posting,
221         // or the Twitter API might just be behaving flakey.
222
223         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
224                           'trying to post notice %d for User %s (user id %d).',
225                           $notice->id,
226                           $user->nickname,
227                           $user->id);
228
229         common_log(LOG_WARNING, $errmsg);
230
231         return false;
232     }
233
234     // Notice crossed the great divide
235
236     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
237                    'OAuth for User %s (user id %d).',
238                    $notice->id,
239                    $user->nickname,
240                    $user->id);
241
242     common_log(LOG_INFO, $msg);
243
244     return true;
245 }
246
247 function process_error($e, $flink, $notice)
248 {
249     $user = $flink->getUser();
250     $code = $e->getCode();
251
252     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
253                       'User %s (user id: %d): %s.',
254                       $code,
255                       $notice->id,
256                       $user->nickname,
257                       $user->id,
258                       $e->getMessage());
259
260     common_log(LOG_WARNING, $logmsg);
261
262     switch($code) {
263      case 401:
264         // Probably a revoked or otherwise bad access token - nuke!
265         remove_twitter_link($flink);
266         return true;
267         break;
268      case 403:
269         // User has exceeder her rate limit -- toss the notice
270         return true;
271         break;
272      default:
273
274         // For every other case, it's probably some flakiness so try
275         // sending the notice again later (requeue).
276
277         return false;
278         break;
279     }
280 }
281
282 function format_status($notice)
283 {
284     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
285     $statustxt = preg_replace('/^@/', ' @', $notice->content);
286
287     // Convert !groups to #hashes
288
289     // XXX: Make this an optional setting?
290
291     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
292
293     if (mb_strlen($statustxt) > 140) {
294         $noticeUrl = common_shorten_url($notice->uri);
295         $urlLen = mb_strlen($noticeUrl);
296         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
297     }
298
299     return $statustxt;
300 }
301
302 function remove_twitter_link($flink)
303 {
304     $user = $flink->getUser();
305
306     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
307                "user $user->nickname (user id: $user->id).");
308
309     $result = $flink->safeDelete();
310
311     if (empty($result)) {
312         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
313                    "Foreign_link for $user->nickname (user id: $user->id)!");
314         common_log_db_error($flink, 'DELETE', __FILE__);
315     }
316
317     // Notify the user that her Twitter bridge is down
318
319     if (isset($user->email)) {
320
321         $result = mail_twitter_bridge_removed($user);
322
323         if (!$result) {
324
325             $msg = 'Unable to send email to notify ' .
326               "$user->nickname (user id: $user->id) " .
327               'that their Twitter bridge link was ' .
328               'removed!';
329
330             common_log(LOG_WARNING, $msg);
331         }
332     }
333
334 }
335
336 /**
337  * Send a mail message to notify a user that her Twitter bridge link
338  * has stopped working, and therefore has been removed.  This can
339  * happen when the user changes her Twitter password, or otherwise
340  * revokes access.
341  *
342  * @param User $user   user whose Twitter bridge link has been removed
343  *
344  * @return boolean success flag
345  */
346
347 function mail_twitter_bridge_removed($user)
348 {
349     $profile = $user->getProfile();
350
351     common_switch_locale($user->language);
352
353     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
354
355     $site_name = common_config('site', 'name');
356
357     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
358         'link to Twitter has been disabled. We no longer seem to have ' .
359     'permission to update your Twitter status. (Did you revoke ' .
360     '%3$s\'s access?)' . "\n\n" .
361     'You can re-enable your Twitter bridge by visiting your ' .
362     "Twitter settings page:\n\n\t%2\$s\n\n" .
363         "Regards,\n%3\$s\n"),
364         $profile->getBestName(),
365         common_local_url('twittersettings'),
366         common_config('site', 'name'));
367
368     common_switch_locale();
369     return mail_to_user($user, $subject, $body);
370 }
371