]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
push notices through the bridge if they're in reply to a twitter notice
[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     if (is_twitter_bound($notice, $flink)) {
149         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
150             return broadcast_oauth($notice, $flink);
151         } else {
152             return broadcast_basicauth($notice, $flink);
153         }
154     }
155
156     return true;
157 }
158
159 /**
160  * Pull any extra information from a notice that we should transfer over
161  * to Twitter beyond the notice text itself.
162  *
163  * @param Notice $notice
164  * @return array of key-value pairs for Twitter update submission
165  * @access private
166  */
167 function twitter_update_params($notice)
168 {
169     $params = array();
170     if ($notice->lat || $notice->lon) {
171         $params['lat'] = $notice->lat;
172         $params['long'] = $notice->lon;
173     }
174     return $params;
175 }
176
177 function broadcast_oauth($notice, $flink) {
178     $user = $flink->getUser();
179     $statustxt = format_status($notice);
180     $params = twitter_update_params($notice);
181
182     $token = TwitterOAuthClient::unpackToken($flink->credentials);
183     $client = new TwitterOAuthClient($token->key, $token->secret);
184     $status = null;
185
186     try {
187         $status = $client->statusesUpdate($statustxt, $params);
188     } catch (OAuthClientException $e) {
189         return process_error($e, $flink, $notice);
190     }
191
192     if (empty($status)) {
193
194         // This could represent a failure posting,
195         // or the Twitter API might just be behaving flakey.
196
197         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
198                           'trying to post notice %d for User %s (user id %d).',
199                           $notice->id,
200                           $user->nickname,
201                           $user->id);
202
203         common_log(LOG_WARNING, $errmsg);
204
205         return false;
206     }
207
208     // Notice crossed the great divide
209
210     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
211                    'OAuth for User %s (user id %d).',
212                    $notice->id,
213                    $user->nickname,
214                    $user->id);
215
216     common_log(LOG_INFO, $msg);
217
218     return true;
219 }
220
221 function broadcast_basicauth($notice, $flink)
222 {
223     $user = $flink->getUser();
224
225     $statustxt = format_status($notice);
226     $params = twitter_update_params($notice);
227
228     $client = new TwitterBasicAuthClient($flink);
229     $status = null;
230
231     try {
232         $status = $client->statusesUpdate($statustxt, $params);
233     } catch (BasicAuthException $e) {
234         return process_error($e, $flink, $notice);
235     }
236
237     if (empty($status)) {
238
239         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
240                           'trying to post notice %d for %s (user id %d).',
241                           $notice->id,
242                           $user->nickname,
243                           $user->id);
244
245         common_log(LOG_WARNING, $errmsg);
246
247         $errmsg = sprintf('No data returned by Twitter API when ' .
248                           'trying to post notice %d for %s (user id %d).',
249                           $notice->id,
250                           $user->nickname,
251                           $user->id);
252         common_log(LOG_WARNING, $errmsg);
253         return false;
254     }
255
256     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
257                    'HTTP basic auth for User %s (user id %d).',
258                    $notice->id,
259                    $user->nickname,
260                    $user->id);
261
262     common_log(LOG_INFO, $msg);
263
264     return true;
265 }
266
267 function process_error($e, $flink, $notice)
268 {
269     $user = $flink->getUser();
270     $code = $e->getCode();
271
272     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
273                       'User %s (user id: %d): %s.',
274                       $code,
275                       $notice->id,
276                       $user->nickname,
277                       $user->id,
278                       $e->getMessage());
279
280     common_log(LOG_WARNING, $logmsg);
281
282     switch($code) {
283      case 401:
284         // Probably a revoked or otherwise bad access token - nuke!
285         remove_twitter_link($flink);
286         return true;
287         break;
288      case 403:
289         // User has exceeder her rate limit -- toss the notice
290         return true;
291         break;
292      default:
293
294         // For every other case, it's probably some flakiness so try
295         // sending the notice again later (requeue).
296
297         return false;
298         break;
299     }
300 }
301
302 function format_status($notice)
303 {
304     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
305     $statustxt = preg_replace('/^@/', ' @', $notice->content);
306
307     // Convert !groups to #hashes
308
309     // XXX: Make this an optional setting?
310
311     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
312
313     if (mb_strlen($statustxt) > 140) {
314         $noticeUrl = common_shorten_url($notice->uri);
315         $urlLen = mb_strlen($noticeUrl);
316         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
317     }
318
319     return $statustxt;
320 }
321
322 function remove_twitter_link($flink)
323 {
324     $user = $flink->getUser();
325
326     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
327                "user $user->nickname (user id: $user->id).");
328
329     $result = $flink->safeDelete();
330
331     if (empty($result)) {
332         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
333                    "Foreign_link for $user->nickname (user id: $user->id)!");
334         common_log_db_error($flink, 'DELETE', __FILE__);
335     }
336
337     // Notify the user that her Twitter bridge is down
338
339     if (isset($user->email)) {
340
341         $result = mail_twitter_bridge_removed($user);
342
343         if (!$result) {
344
345             $msg = 'Unable to send email to notify ' .
346               "$user->nickname (user id: $user->id) " .
347               'that their Twitter bridge link was ' .
348               'removed!';
349
350             common_log(LOG_WARNING, $msg);
351         }
352     }
353
354 }
355
356 /**
357  * Send a mail message to notify a user that her Twitter bridge link
358  * has stopped working, and therefore has been removed.  This can
359  * happen when the user changes her Twitter password, or otherwise
360  * revokes access.
361  *
362  * @param User $user   user whose Twitter bridge link has been removed
363  *
364  * @return boolean success flag
365  */
366
367 function mail_twitter_bridge_removed($user)
368 {
369     $profile = $user->getProfile();
370
371     common_switch_locale($user->language);
372
373     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
374
375     $site_name = common_config('site', 'name');
376
377     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
378         'link to Twitter has been disabled. We no longer seem to have ' .
379     'permission to update your Twitter status. (Did you revoke ' .
380     '%3$s\'s access?)' . "\n\n" .
381     'You can re-enable your Twitter bridge by visiting your ' .
382     "Twitter settings page:\n\n\t%2\$s\n\n" .
383         "Regards,\n%3\$s\n"),
384         $profile->getBestName(),
385         common_local_url('twittersettings'),
386         common_config('site', 'name'));
387
388     common_switch_locale();
389     return mail_to_user($user, $subject, $body);
390 }
391