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