]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.x
[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
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
261     // XXX: Make this an optional setting?
262
263     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
264
265     if (mb_strlen($statustxt) > 140) {
266         $noticeUrl = common_shorten_url($notice->uri);
267         $urlLen = mb_strlen($noticeUrl);
268         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
269     }
270
271     return $statustxt;
272 }
273
274 function remove_twitter_link($flink)
275 {
276     $user = $flink->getUser();
277
278     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
279                "user $user->nickname (user id: $user->id).");
280
281     $result = $flink->delete();
282
283     if (empty($result)) {
284         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
285                    "Foreign_link for $user->nickname (user id: $user->id)!");
286         common_log_db_error($flink, 'DELETE', __FILE__);
287     }
288
289     // Notify the user that her Twitter bridge is down
290
291     if (isset($user->email)) {
292
293         $result = mail_twitter_bridge_removed($user);
294
295         if (!$result) {
296
297             $msg = 'Unable to send email to notify ' .
298               "$user->nickname (user id: $user->id) " .
299               'that their Twitter bridge link was ' .
300               'removed!';
301
302             common_log(LOG_WARNING, $msg);
303         }
304     }
305
306 }
307
308 /**
309  * Send a mail message to notify a user that her Twitter bridge link
310  * has stopped working, and therefore has been removed.  This can
311  * happen when the user changes her Twitter password, or otherwise
312  * revokes access.
313  *
314  * @param User $user   user whose Twitter bridge link has been removed
315  *
316  * @return boolean success flag
317  */
318
319 function mail_twitter_bridge_removed($user)
320 {
321     common_init_locale($user->language);
322
323     $profile = $user->getProfile();
324
325     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
326
327     $site_name = common_config('site', 'name');
328
329     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
330         'link to Twitter has been disabled. We no longer seem to have ' .
331     'permission to update your Twitter status. (Did you revoke ' .
332     '%3$s\'s access?)' . "\n\n" .
333     'You can re-enable your Twitter bridge by visiting your ' .
334     "Twitter settings page:\n\n\t%2\$s\n\n" .
335         "Regards,\n%3\$s\n"),
336         $profile->getBestName(),
337         common_local_url('twittersettings'),
338         common_config('site', 'name'));
339
340     common_init_locale();
341     return mail_to_user($user, $subject, $body);
342 }
343