]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Remove inline reply forms on click-away if they have initial text as well as if empty...
[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     $luser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
34
35     if (!empty($luser)) {
36         $result = $luser->delete();
37         if ($result != false) {
38             common_log(
39                 LOG_INFO,
40                 "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
41             );
42         }
43     }
44
45     $fuser = new Foreign_user();
46
47     $fuser->nickname = $screen_name;
48     $fuser->uri = 'http://twitter.com/' . $screen_name;
49     $fuser->id = $twitter_id;
50     $fuser->service = TWITTER_SERVICE;
51     $fuser->created = common_sql_now();
52     $result = $fuser->insert();
53
54     if (empty($result)) {
55         common_log(LOG_WARNING,
56             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
57         common_log_db_error($fuser, 'INSERT', __FILE__);
58     } else {
59         common_log(LOG_INFO,
60                    "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
61     }
62
63     return $result;
64 }
65
66 // Creates or Updates a Twitter user
67 function save_twitter_user($twitter_id, $screen_name)
68 {
69     // Check to see whether the Twitter user is already in the system,
70     // and update its screen name and uri if so.
71     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
72
73     if (!empty($fuser)) {
74
75         // Delete old record if Twitter user changed screen name
76
77         if ($fuser->nickname != $screen_name) {
78             $oldname = $fuser->nickname;
79             $fuser->delete();
80             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
81                                          'for Twitter user %1$d - %2$s, was %3$s.',
82                                          $fuser->id,
83                                          $screen_name,
84                                          $oldname));
85         }
86
87     } else {
88         // Kill any old, invalid records for this screen name
89         $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
90
91         if (!empty($fuser)) {
92             $fuser->delete();
93             common_log(
94                 LOG_INFO,
95                 sprintf(
96                     'Twitter bridge - deteted old record for Twitter ' .
97                     'screen name "%s" belonging to Twitter ID %d.',
98                     $screen_name,
99                     $fuser->id
100                 )
101             );
102         }
103     }
104
105     return add_twitter_user($twitter_id, $screen_name);
106 }
107
108 function is_twitter_bound($notice, $flink) {
109     // Check to see if notice should go to Twitter
110     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
111
112         // If it's not a Twitter-style reply, or if the user WANTS to send replies,
113         // or if it's in reply to a twitter notice
114         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
115             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) ||
116             is_twitter_notice($notice->reply_to)) {
117             return true;
118         }
119     }
120
121     return false;
122 }
123
124 function is_twitter_notice($id)
125 {
126     $n2s = Notice_to_status::staticGet('notice_id', $id);
127
128     return (!empty($n2s));
129 }
130
131 /**
132  * Pull the formatted status ID number from a Twitter status object
133  * returned via JSON from Twitter API.
134  *
135  * Encapsulates checking for the id_str attribute, which is required
136  * to read 64-bit "Snowflake" ID numbers on a 32-bit system -- the
137  * integer id attribute gets corrupted into a double-precision float,
138  * losing a few digits of precision.
139  *
140  * Warning: avoid performing arithmetic or direct comparisons with
141  * this number, as it may get coerced back to a double on 32-bit.
142  *
143  * @param object $status
144  * @param string $field base field name if not 'id'
145  * @return mixed id number as int or string
146  */
147 function twitter_id($status, $field='id')
148 {
149     $field_str = "{$field}_str";
150     if (isset($status->$field_str)) {
151         // String version of the id -- required on 32-bit systems
152         // since the 64-bit numbers get corrupted as ints.
153         return $status->$field_str;
154     } else {
155         return $status->$field;
156     }
157 }
158
159 /**
160  * Check if we need to broadcast a notice over the Twitter bridge, and
161  * do so if necessary. Will determine whether to do a straight post or
162  * a repeat/retweet
163  *
164  * This function is meant to be called directly from TwitterQueueHandler.
165  *
166  * @param Notice $notice
167  * @return boolean true if complete or successful, false if we should retry
168  */
169 function broadcast_twitter($notice)
170 {
171     $flink = Foreign_link::getByUserID($notice->profile_id,
172                                        TWITTER_SERVICE);
173
174     // Don't bother with basic auth, since it's no longer allowed
175     if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
176         if (is_twitter_bound($notice, $flink)) {
177             if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
178                 $retweet = retweet_notice($flink, Notice::staticGet('id', $notice->repeat_of));
179                 if (is_object($retweet)) {
180                     Notice_to_status::saveNew($notice->id, twitter_id($retweet));
181                     return true;
182                 } else {
183                     // Our error processing will have decided if we need to requeue
184                     // this or can discard safely.
185                     return $retweet;
186                 }
187             } else {
188                 return broadcast_oauth($notice, $flink);
189             }
190         }
191     }
192
193     return true;
194 }
195
196 /**
197  * Send a retweet to Twitter for a notice that has been previously bridged
198  * in or out.
199  *
200  * Warning: the return value is not guaranteed to be an object; some error
201  * conditions will return a 'true' which should be passed on to a calling
202  * queue handler.
203  *
204  * No local information about the resulting retweet is saved: it's up to
205  * caller to save new mappings etc if appropriate.
206  *
207  * @param Foreign_link $flink
208  * @param Notice $notice
209  * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
210  */
211 function retweet_notice($flink, $notice)
212 {
213     $token = TwitterOAuthClient::unpackToken($flink->credentials);
214     $client = new TwitterOAuthClient($token->key, $token->secret);
215
216     $id = twitter_status_id($notice);
217
218     if (empty($id)) {
219         common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
220         return null;
221     }
222
223     try {
224         $status = $client->statusesRetweet($id);
225         return $status;
226     } catch (OAuthClientException $e) {
227         return process_error($e, $flink, $notice);
228     }
229 }
230
231 function twitter_status_id($notice)
232 {
233     $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
234     if (empty($n2s)) {
235         return null;
236     } else {
237         return $n2s->status_id;
238     }
239 }
240
241 /**
242  * Pull any extra information from a notice that we should transfer over
243  * to Twitter beyond the notice text itself.
244  *
245  * @param Notice $notice
246  * @return array of key-value pairs for Twitter update submission
247  * @access private
248  */
249 function twitter_update_params($notice)
250 {
251     $params = array();
252     if ($notice->lat || $notice->lon) {
253         $params['lat'] = $notice->lat;
254         $params['long'] = $notice->lon;
255     }
256     if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
257         $reply = Notice::staticGet('id', $notice->reply_to);
258         $params['in_reply_to_status_id'] = twitter_status_id($reply);
259     }
260     return $params;
261 }
262
263 function broadcast_oauth($notice, $flink) {
264     $user = $flink->getUser();
265     $statustxt = format_status($notice);
266     $params = twitter_update_params($notice);
267
268     $token = TwitterOAuthClient::unpackToken($flink->credentials);
269     $client = new TwitterOAuthClient($token->key, $token->secret);
270     $status = null;
271
272     try {
273         $status = $client->statusesUpdate($statustxt, $params);
274         if (!empty($status)) {
275             Notice_to_status::saveNew($notice->id, twitter_id($status));
276         }
277     } catch (OAuthClientException $e) {
278         return process_error($e, $flink, $notice);
279     }
280
281     if (empty($status)) {
282
283         // This could represent a failure posting,
284         // or the Twitter API might just be behaving flakey.
285         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
286                           'trying to post notice %d for User %s (user id %d).',
287                           $notice->id,
288                           $user->nickname,
289                           $user->id);
290
291         common_log(LOG_WARNING, $errmsg);
292
293         return false;
294     }
295
296     // Notice crossed the great divide
297     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
298                    'OAuth for User %s (user id %d).',
299                    $notice->id,
300                    $user->nickname,
301                    $user->id);
302
303     common_log(LOG_INFO, $msg);
304
305     return true;
306 }
307
308 function process_error($e, $flink, $notice)
309 {
310     $user = $flink->getUser();
311     $code = $e->getCode();
312
313     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
314                       'User %s (user id: %d): %s.',
315                       $code,
316                       $notice->id,
317                       $user->nickname,
318                       $user->id,
319                       $e->getMessage());
320
321     common_log(LOG_WARNING, $logmsg);
322
323     switch($code) {
324      case 401:
325         // Probably a revoked or otherwise bad access token - nuke!
326         remove_twitter_link($flink);
327         return true;
328         break;
329      case 403:
330         // User has exceeder her rate limit -- toss the notice
331         return true;
332         break;
333      default:
334
335         // For every other case, it's probably some flakiness so try
336         // sending the notice again later (requeue).
337
338         return false;
339         break;
340     }
341 }
342
343 function format_status($notice)
344 {
345     // Start with the plaintext source of this notice...
346     $statustxt = $notice->content;
347
348     // Convert !groups to #hashes
349     // XXX: Make this an optional setting?
350     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
351
352     // Twitter still has a 140-char hardcoded max.
353     if (mb_strlen($statustxt) > 140) {
354         $noticeUrl = common_shorten_url($notice->uri);
355         $urlLen = mb_strlen($noticeUrl);
356         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
357     }
358
359     return $statustxt;
360 }
361
362 function remove_twitter_link($flink)
363 {
364     $user = $flink->getUser();
365
366     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
367                "user $user->nickname (user id: $user->id).");
368
369     $result = $flink->safeDelete();
370
371     if (empty($result)) {
372         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
373                    "Foreign_link for $user->nickname (user id: $user->id)!");
374         common_log_db_error($flink, 'DELETE', __FILE__);
375     }
376
377     // Notify the user that her Twitter bridge is down
378
379     if (isset($user->email)) {
380         $result = mail_twitter_bridge_removed($user);
381
382         if (!$result) {
383             $msg = 'Unable to send email to notify ' .
384               "$user->nickname (user id: $user->id) " .
385               'that their Twitter bridge link was ' .
386               'removed!';
387
388             common_log(LOG_WARNING, $msg);
389         }
390     }
391 }
392
393 /**
394  * Send a mail message to notify a user that her Twitter bridge link
395  * has stopped working, and therefore has been removed.  This can
396  * happen when the user changes her Twitter password, or otherwise
397  * revokes access.
398  *
399  * @param User $user   user whose Twitter bridge link has been removed
400  *
401  * @return boolean success flag
402  */
403 function mail_twitter_bridge_removed($user)
404 {
405     $profile = $user->getProfile();
406
407     common_switch_locale($user->language);
408
409     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
410
411     $site_name = common_config('site', 'name');
412
413     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
414         'link to Twitter has been disabled. We no longer seem to have ' .
415     'permission to update your Twitter status. Did you maybe revoke ' .
416     '%3$s\'s access?' . "\n\n" .
417     'You can re-enable your Twitter bridge by visiting your ' .
418     "Twitter settings page:\n\n\t%2\$s\n\n" .
419         "Regards,\n%3\$s"),
420         $profile->getBestName(),
421         common_local_url('twittersettings'),
422         common_config('site', 'name'));
423
424     common_switch_locale();
425     return mail_to_user($user, $subject, $body);
426 }