]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Merge branch 'testing' 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     // 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     $result = $luser->delete();
37
38     if ($result != false) {
39         common_log(LOG_INFO,
40             "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id).");
41     }
42
43     $fuser = new Foreign_user();
44
45     $fuser->nickname = $screen_name;
46     $fuser->uri = 'http://twitter.com/' . $screen_name;
47     $fuser->id = $twitter_id;
48     $fuser->service = TWITTER_SERVICE;
49     $fuser->created = common_sql_now();
50     $result = $fuser->insert();
51
52     if (empty($result)) {
53         common_log(LOG_WARNING,
54             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
55         common_log_db_error($fuser, 'INSERT', __FILE__);
56     } else {
57         common_log(LOG_INFO,
58                    "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
59     }
60
61     return $result;
62 }
63
64 // Creates or Updates a Twitter user
65 function save_twitter_user($twitter_id, $screen_name)
66 {
67     // Check to see whether the Twitter user is already in the system,
68     // and update its screen name and uri if so.
69
70     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
71
72     if (!empty($fuser)) {
73
74         $result = true;
75
76         // Delete old record if Twitter user changed screen name
77
78         if ($fuser->nickname != $screen_name) {
79             $oldname = $fuser->nickname;
80             $fuser->delete();
81             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
82                                          'for Twitter user %1$d - %2$s, was %3$s.',
83                                          $fuser->id,
84                                          $screen_name,
85                                          $oldname));
86         }
87     }
88
89     return add_twitter_user($twitter_id, $screen_name);
90 }
91
92 function is_twitter_bound($notice, $flink) {
93
94     // Check to see if notice should go to Twitter
95     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
96
97         // If it's not a Twitter-style reply, or if the user WANTS to send replies.
98         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
99             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
100             return true;
101         }
102     }
103
104     return false;
105 }
106
107 function broadcast_twitter($notice)
108 {
109     $flink = Foreign_link::getByUserID($notice->profile_id,
110                                        TWITTER_SERVICE);
111
112     if (is_twitter_bound($notice, $flink)) {
113         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
114             return broadcast_oauth($notice, $flink);
115         } else {
116             return broadcast_basicauth($notice, $flink);
117         }
118     }
119
120     return true;
121 }
122
123 function broadcast_oauth($notice, $flink) {
124     $user = $flink->getUser();
125     $statustxt = format_status($notice);
126     $token = TwitterOAuthClient::unpackToken($flink->credentials);
127     $client = new TwitterOAuthClient($token->key, $token->secret);
128     $status = null;
129
130     try {
131         $status = $client->statusesUpdate($statustxt);
132     } catch (OAuthClientException $e) {
133         return process_error($e, $flink, $notice);
134     }
135
136     if (empty($status)) {
137
138         // This could represent a failure posting,
139         // or the Twitter API might just be behaving flakey.
140
141         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
142                           'trying to post notice %d for User %s (user id %d).',
143                           $notice->id,
144                           $user->nickname,
145                           $user->id);
146
147         common_log(LOG_WARNING, $errmsg);
148
149         return false;
150     }
151
152     // Notice crossed the great divide
153
154     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
155                    'OAuth for User %s (user id %d).',
156                    $notice->id,
157                    $user->nickname,
158                    $user->id);
159
160     common_log(LOG_INFO, $msg);
161
162     return true;
163 }
164
165 function broadcast_basicauth($notice, $flink)
166 {
167     $user = $flink->getUser();
168
169     $statustxt = format_status($notice);
170
171     $client = new TwitterBasicAuthClient($flink);
172     $status = null;
173
174     try {
175         $status = $client->statusesUpdate($statustxt);
176     } catch (BasicAuthException $e) {
177         return process_error($e, $flink, $notice);
178     }
179
180     if (empty($status)) {
181
182         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
183                           'trying to post notice %d for %s (user id %d).',
184                           $notice->id,
185                           $user->nickname,
186                           $user->id);
187
188         common_log(LOG_WARNING, $errmsg);
189
190         $errmsg = sprintf('No data returned by Twitter API when ' .
191                           'trying to post notice %d for %s (user id %d).',
192                           $notice->id,
193                           $user->nickname,
194                           $user->id);
195         common_log(LOG_WARNING, $errmsg);
196         return false;
197     }
198
199     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
200                    'HTTP basic auth for User %s (user id %d).',
201                    $notice->id,
202                    $user->nickname,
203                    $user->id);
204
205     common_log(LOG_INFO, $msg);
206
207     return true;
208 }
209
210 function process_error($e, $flink, $notice)
211 {
212     $user = $flink->getUser();
213     $code = $e->getCode();
214
215     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
216                       'User %s (user id: %d): %s.',
217                       $code,
218                       $notice->id,
219                       $user->nickname,
220                       $user->id,
221                       $e->getMessage());
222
223     common_log(LOG_WARNING, $logmsg);
224
225     switch($code) {
226      case 401:
227         // Probably a revoked or otherwise bad access token - nuke!
228         remove_twitter_link($flink);
229         return true;
230         break;
231      case 403:
232         // User has exceeder her rate limit -- toss the notice
233         return true;
234         break;
235      default:
236
237         // For every other case, it's probably some flakiness so try
238         // sending the notice again later (requeue).
239
240         return false;
241         break;
242     }
243 }
244
245 function format_status($notice)
246 {
247     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
248     $statustxt = preg_replace('/^@/', ' @', $notice->content);
249
250     // Convert !groups to #hashes
251
252     // XXX: Make this an optional setting?
253
254     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
255
256     if (mb_strlen($statustxt) > 140) {
257         $noticeUrl = common_shorten_url($notice->uri);
258         $urlLen = mb_strlen($noticeUrl);
259         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
260     }
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