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