]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Merge branch 'sitemap' of gitorious.org:~evan/statusnet/evans-mainline into sitemap
[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         $result = true;
79
80         // Delete old record if Twitter user changed screen name
81
82         if ($fuser->nickname != $screen_name) {
83             $oldname = $fuser->nickname;
84             $fuser->delete();
85             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
86                                          'for Twitter user %1$d - %2$s, was %3$s.',
87                                          $fuser->id,
88                                          $screen_name,
89                                          $oldname));
90         }
91     }
92
93     return add_twitter_user($twitter_id, $screen_name);
94 }
95
96 function is_twitter_bound($notice, $flink) {
97
98     // Check to see if notice should go to Twitter
99     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
100
101         // If it's not a Twitter-style reply, or if the user WANTS to send replies.
102         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
103             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
104             return true;
105         }
106     }
107
108     return false;
109 }
110
111 function broadcast_twitter($notice)
112 {
113     $flink = Foreign_link::getByUserID($notice->profile_id,
114                                        TWITTER_SERVICE);
115
116     if (is_twitter_bound($notice, $flink)) {
117         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
118             return broadcast_oauth($notice, $flink);
119         } else {
120             return broadcast_basicauth($notice, $flink);
121         }
122     }
123
124     return true;
125 }
126
127 /**
128  * Pull any extra information from a notice that we should transfer over
129  * to Twitter beyond the notice text itself.
130  *
131  * @param Notice $notice
132  * @return array of key-value pairs for Twitter update submission
133  * @access private
134  */
135 function twitter_update_params($notice)
136 {
137     $params = array();
138     if ($notice->lat || $notice->lon) {
139         $params['lat'] = $notice->lat;
140         $params['long'] = $notice->lon;
141     }
142     return $params;
143 }
144
145
146 function broadcast_oauth($notice, $flink) {
147     $user = $flink->getUser();
148     $statustxt = format_status($notice);
149     $params = twitter_update_params($notice);
150
151     $token = TwitterOAuthClient::unpackToken($flink->credentials);
152     $client = new TwitterOAuthClient($token->key, $token->secret);
153     $status = null;
154
155     try {
156         $status = $client->statusesUpdate($statustxt, $params);
157     } catch (OAuthClientException $e) {
158         return process_error($e, $flink, $notice);
159     }
160
161     if (empty($status)) {
162
163         // This could represent a failure posting,
164         // or the Twitter API might just be behaving flakey.
165
166         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
167                           'trying to post notice %d for User %s (user id %d).',
168                           $notice->id,
169                           $user->nickname,
170                           $user->id);
171
172         common_log(LOG_WARNING, $errmsg);
173
174         return false;
175     }
176
177     // Notice crossed the great divide
178
179     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
180                    'OAuth for User %s (user id %d).',
181                    $notice->id,
182                    $user->nickname,
183                    $user->id);
184
185     common_log(LOG_INFO, $msg);
186
187     return true;
188 }
189
190 function broadcast_basicauth($notice, $flink)
191 {
192     $user = $flink->getUser();
193
194     $statustxt = format_status($notice);
195     $params = twitter_update_params($notice);
196
197     $client = new TwitterBasicAuthClient($flink);
198     $status = null;
199
200     try {
201         $status = $client->statusesUpdate($statustxt, $params);
202     } catch (BasicAuthException $e) {
203         return process_error($e, $flink, $notice);
204     }
205
206     if (empty($status)) {
207
208         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
209                           'trying to post notice %d for %s (user id %d).',
210                           $notice->id,
211                           $user->nickname,
212                           $user->id);
213
214         common_log(LOG_WARNING, $errmsg);
215
216         $errmsg = sprintf('No data returned by Twitter API when ' .
217                           'trying to post notice %d for %s (user id %d).',
218                           $notice->id,
219                           $user->nickname,
220                           $user->id);
221         common_log(LOG_WARNING, $errmsg);
222         return false;
223     }
224
225     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
226                    'HTTP basic auth for User %s (user id %d).',
227                    $notice->id,
228                    $user->nickname,
229                    $user->id);
230
231     common_log(LOG_INFO, $msg);
232
233     return true;
234 }
235
236 function process_error($e, $flink, $notice)
237 {
238     $user = $flink->getUser();
239     $code = $e->getCode();
240
241     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
242                       'User %s (user id: %d): %s.',
243                       $code,
244                       $notice->id,
245                       $user->nickname,
246                       $user->id,
247                       $e->getMessage());
248
249     common_log(LOG_WARNING, $logmsg);
250
251     switch($code) {
252      case 401:
253         // Probably a revoked or otherwise bad access token - nuke!
254         remove_twitter_link($flink);
255         return true;
256         break;
257      case 403:
258         // User has exceeder her rate limit -- toss the notice
259         return true;
260         break;
261      default:
262
263         // For every other case, it's probably some flakiness so try
264         // sending the notice again later (requeue).
265
266         return false;
267         break;
268     }
269 }
270
271 function format_status($notice)
272 {
273     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
274     $statustxt = preg_replace('/^@/', ' @', $notice->content);
275
276     // Convert !groups to #hashes
277
278     // XXX: Make this an optional setting?
279
280     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
281
282     if (mb_strlen($statustxt) > 140) {
283         $noticeUrl = common_shorten_url($notice->uri);
284         $urlLen = mb_strlen($noticeUrl);
285         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
286     }
287
288     return $statustxt;
289 }
290
291 function remove_twitter_link($flink)
292 {
293     $user = $flink->getUser();
294
295     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
296                "user $user->nickname (user id: $user->id).");
297
298     $result = $flink->safeDelete();
299
300     if (empty($result)) {
301         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
302                    "Foreign_link for $user->nickname (user id: $user->id)!");
303         common_log_db_error($flink, 'DELETE', __FILE__);
304     }
305
306     // Notify the user that her Twitter bridge is down
307
308     if (isset($user->email)) {
309
310         $result = mail_twitter_bridge_removed($user);
311
312         if (!$result) {
313
314             $msg = 'Unable to send email to notify ' .
315               "$user->nickname (user id: $user->id) " .
316               'that their Twitter bridge link was ' .
317               'removed!';
318
319             common_log(LOG_WARNING, $msg);
320         }
321     }
322
323 }
324
325 /**
326  * Send a mail message to notify a user that her Twitter bridge link
327  * has stopped working, and therefore has been removed.  This can
328  * happen when the user changes her Twitter password, or otherwise
329  * revokes access.
330  *
331  * @param User $user   user whose Twitter bridge link has been removed
332  *
333  * @return boolean success flag
334  */
335
336 function mail_twitter_bridge_removed($user)
337 {
338     $profile = $user->getProfile();
339
340     common_switch_locale($user->language);
341
342     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
343
344     $site_name = common_config('site', 'name');
345
346     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
347         'link to Twitter has been disabled. We no longer seem to have ' .
348     'permission to update your Twitter status. (Did you revoke ' .
349     '%3$s\'s access?)' . "\n\n" .
350     'You can re-enable your Twitter bridge by visiting your ' .
351     "Twitter settings page:\n\n\t%2\$s\n\n" .
352         "Regards,\n%3\$s\n"),
353         $profile->getBestName(),
354         common_local_url('twittersettings'),
355         common_config('site', 'name'));
356
357     common_switch_locale();
358     return mail_to_user($user, $subject, $body);
359 }
360