]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Merge branch 'master' of git@gitorious.org:statusnet/mainline into testing
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, 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
32     $new_uri = 'http://twitter.com/' . $screen_name;
33
34     // Clear out any bad old foreign_users with the new user's legit URL
35     // This can happen when users move around or fakester accounts get
36     // repoed, and things like that.
37
38     $luser = new Foreign_user();
39     $luser->uri = $new_uri;
40     $luser->service = TWITTER_SERVICE;
41     $result = $luser->delete();
42
43     if (empty($result)) {
44         common_log(LOG_WARNING,
45             "Twitter bridge - removed invalid Twitter user squatting on uri: $new_uri");
46     }
47
48     $luser->free();
49     unset($luser);
50
51     // Otherwise, create a new Twitter user
52
53     $fuser = new Foreign_user();
54
55     $fuser->nickname = $screen_name;
56     $fuser->uri = 'http://twitter.com/' . $screen_name;
57     $fuser->id = $twitter_id;
58     $fuser->service = TWITTER_SERVICE;
59     $fuser->created = common_sql_now();
60     $result = $fuser->insert();
61
62     if (empty($result)) {
63         common_log(LOG_WARNING,
64             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
65         common_log_db_error($fuser, 'INSERT', __FILE__);
66     } else {
67         common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
68     }
69
70     return $result;
71 }
72
73 // Creates or Updates a Twitter user
74 function save_twitter_user($twitter_id, $screen_name)
75 {
76     // Check to see whether the Twitter user is already in the system,
77     // and update its screen name and uri if so.
78
79     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
80
81     if (!empty($fuser)) {
82
83         $result = true;
84
85         // Delete old record if Twitter user changed screen name
86
87         if ($fuser->nickname != $screen_name) {
88             $oldname = $fuser->nickname;
89             $fuser->delete();
90             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
91                                          'for Twitter user %1$d - %2$s, was %3$s.',
92                                          $fuser->id,
93                                          $screen_name,
94                                          $oldname));
95         }
96
97         return add_twitter_user($twitter_id, $screen_name);
98     }
99 }
100
101 function is_twitter_bound($notice, $flink) {
102
103     // Check to see if notice should go to Twitter
104     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
105
106         // If it's not a Twitter-style reply, or if the user WANTS to send replies.
107         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
108             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
109             return true;
110         }
111     }
112
113     return false;
114 }
115
116 function broadcast_twitter($notice)
117 {
118     $flink = Foreign_link::getByUserID($notice->profile_id,
119                                        TWITTER_SERVICE);
120
121     if (is_twitter_bound($notice, $flink)) {
122         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
123             return broadcast_oauth($notice, $flink);
124         } else {
125             return broadcast_basicauth($notice, $flink);
126         }
127     }
128
129     return true;
130 }
131
132 function broadcast_oauth($notice, $flink) {
133     $user = $flink->getUser();
134     $statustxt = format_status($notice);
135     $token = TwitterOAuthClient::unpackToken($flink->credentials);
136     $client = new TwitterOAuthClient($token->key, $token->secret);
137     $status = null;
138
139     try {
140         $status = $client->statusesUpdate($statustxt);
141     } catch (OAuthClientException $e) {
142         return process_error($e, $flink, $notice);
143     }
144
145     if (empty($status)) {
146
147         // This could represent a failure posting,
148         // or the Twitter API might just be behaving flakey.
149
150         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
151                           'trying to post notice %d for User %s (user id %d).',
152                           $notice->id,
153                           $user->nickname,
154                           $user->id);
155
156         common_log(LOG_WARNING, $errmsg);
157
158         return false;
159     }
160
161     // Notice crossed the great divide
162
163     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
164                    'OAuth for User %s (user id %d).',
165                    $notice->id,
166                    $user->nickname,
167                    $user->id);
168
169     common_log(LOG_INFO, $msg);
170
171     return true;
172 }
173
174 function broadcast_basicauth($notice, $flink)
175 {
176     $user = $flink->getUser();
177
178     $statustxt = format_status($notice);
179
180     $client = new TwitterBasicAuthClient($flink);
181     $status = null;
182
183     try {
184         $status = $client->statusesUpdate($statustxt);
185     } catch (BasicAuthException $e) {
186         return process_error($e, $flink, $notice);
187     }
188
189     if (empty($status)) {
190
191         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
192                           'trying to post notice %d for %s (user id %d).',
193                           $notice->id,
194                           $user->nickname,
195                           $user->id);
196
197         common_log(LOG_WARNING, $errmsg);
198
199         $errmsg = sprintf('No data returned by Twitter API when ' .
200                           'trying to post notice %d for %s (user id %d).',
201                           $notice->id,
202                           $user->nickname,
203                           $user->id);
204         common_log(LOG_WARNING, $errmsg);
205         return false;
206     }
207
208     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
209                    'HTTP basic auth for User %s (user id %d).',
210                    $notice->id,
211                    $user->nickname,
212                    $user->id);
213
214     common_log(LOG_INFO, $msg);
215
216     return true;
217 }
218
219 function process_error($e, $flink, $notice)
220 {
221     $user = $flink->getUser();
222     $code = $e->getCode();
223
224     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
225                       'User %s (user id: %d): %s.',
226                       $code,
227                       $notice->id,
228                       $user->nickname,
229                       $user->id,
230                       $e->getMessage());
231
232     common_log(LOG_WARNING, $logmsg);
233
234     switch($code) {
235      case 401:
236         // Probably a revoked or otherwise bad access token - nuke!
237         remove_twitter_link($flink);
238         return true;
239         break;
240      case 403:
241         // User has exceeder her rate limit -- toss the notice
242         return true;
243         break;
244      default:
245
246         // For every other case, it's probably some flakiness so try
247         // sending the notice again later (requeue).
248
249         return false;
250         break;
251     }
252 }
253
254 function format_status($notice)
255 {
256     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
257     $statustxt = preg_replace('/^@/', ' @', $notice->content);
258
259     // Convert !groups to #hashes
260     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
261
262     return $statustxt;
263 }
264
265 function remove_twitter_link($flink)
266 {
267     $user = $flink->getUser();
268
269     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
270                "user $user->nickname (user id: $user->id).");
271
272     $result = $flink->delete();
273
274     if (empty($result)) {
275         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
276                    "Foreign_link for $user->nickname (user id: $user->id)!");
277         common_log_db_error($flink, 'DELETE', __FILE__);
278     }
279
280     // Notify the user that her Twitter bridge is down
281
282     if (isset($user->email)) {
283
284         $result = mail_twitter_bridge_removed($user);
285
286         if (!$result) {
287
288             $msg = 'Unable to send email to notify ' .
289               "$user->nickname (user id: $user->id) " .
290               'that their Twitter bridge link was ' .
291               'removed!';
292
293             common_log(LOG_WARNING, $msg);
294         }
295     }
296
297 }
298
299 /**
300  * Send a mail message to notify a user that her Twitter bridge link
301  * has stopped working, and therefore has been removed.  This can
302  * happen when the user changes her Twitter password, or otherwise
303  * revokes access.
304  *
305  * @param User $user   user whose Twitter bridge link has been removed
306  *
307  * @return boolean success flag
308  */
309
310 function mail_twitter_bridge_removed($user)
311 {
312     common_init_locale($user->language);
313
314     $profile = $user->getProfile();
315
316     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
317
318     $site_name = common_config('site', 'name');
319
320     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
321         'link to Twitter has been disabled. We no longer seem to have ' .
322     'permission to update your Twitter status. (Did you revoke ' .
323     '%3$s\'s access?)' . "\n\n" .
324     'You can re-enable your Twitter bridge by visiting your ' .
325     "Twitter settings page:\n\n\t%2\$s\n\n" .
326         "Regards,\n%3\$s\n"),
327         $profile->getBestName(),
328         common_local_url('twittersettings'),
329         common_config('site', 'name'));
330
331     common_init_locale();
332     return mail_to_user($user, $subject, $body);
333 }
334