]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Rebuilt HTTPClient class as an extension of PEAR HTTP_Request2 package, adding redire...
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, 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     // Convert !groups to #hashes
174     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
175     $token = TwitterOAuthClient::unpackToken($flink->credentials);
176     $client = new TwitterOAuthClient($token->key, $token->secret);
177     $status = null;
178
179     try {
180         $status = $client->statusesUpdate($statustxt);
181     } catch (OAuthClientCurlException $e) {
182         return process_error($e, $flink);
183     }
184
185     if (empty($status)) {
186
187         // This could represent a failure posting,
188         // or the Twitter API might just be behaving flakey.
189
190         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
191                           'trying to send update for %1$s (user id %2$s).',
192                           $user->nickname, $user->id);
193         common_log(LOG_WARNING, $errmsg);
194
195         return false;
196     }
197
198     // Notice crossed the great divide
199
200     $msg = sprintf('Twitter bridge - posted notice %s to Twitter using OAuth.',
201                    $notice->id);
202     common_log(LOG_INFO, $msg);
203
204     return true;
205 }
206
207 function broadcast_basicauth($notice, $flink)
208 {
209     $user = $flink->getUser();
210
211     $statustxt = format_status($notice);
212
213     $client = new TwitterBasicAuthClient($flink);
214     $status = null;
215
216     try {
217         $status = $client->statusesUpdate($statustxt);
218     } catch (HTTP_Request2_Exception $e) {
219         return process_error($e, $flink);
220     }
221
222     if (empty($status)) {
223
224         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
225                           'trying to send update for %1$s (user id %2$s).',
226                           $user->nickname, $user->id);
227         common_log(LOG_WARNING, $errmsg);
228
229             $errmsg = sprintf('No data returned by Twitter API when ' .
230                              'trying to send update for %1$s (user id %2$s).',
231                              $user->nickname, $user->id);
232             common_log(LOG_WARNING, $errmsg);
233         return false;
234     }
235
236     $msg = sprintf('Twitter bridge - posted notice %s to Twitter using basic auth.',
237                    $notice->id);
238     common_log(LOG_INFO, $msg);
239
240     return true;
241 }
242
243 function process_error($e, $flink)
244 {
245     $user        = $flink->getUser();
246     $errmsg      = $e->getMessage();
247     $delivered   = false;
248
249     switch($errmsg) {
250      case 'The requested URL returned error: 401':
251         $logmsg = sprintf('Twiter bridge - User %1$s (user id: %2$s) has an invalid ' .
252                           'Twitter screen_name/password combo or an invalid acesss token.',
253                           $user->nickname, $user->id);
254         $delivered = true;
255         remove_twitter_link($flink);
256         break;
257      case 'The requested URL returned error: 403':
258         $logmsg = sprintf('Twitter bridge - User %1$s (user id: %2$s) has exceeded ' .
259                           'his/her Twitter request limit.',
260                           $user->nickname, $user->id);
261         break;
262      default:
263         $logmsg = sprintf('Twitter bridge - cURL error trying to send notice to Twitter ' .
264                           'for user %1$s (user id: %2$s) - ' .
265                           'code: %3$s message: %4$s.',
266                           $user->nickname, $user->id,
267                           $e->getCode(), $e->getMessage());
268         break;
269     }
270
271     common_log(LOG_WARNING, $logmsg);
272
273     return $delivered;
274 }
275
276 function format_status($notice)
277 {
278     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
279     return preg_replace('/^@/', ' @', $notice->content);
280 }
281
282 function remove_twitter_link($flink)
283 {
284     $user = $flink->getUser();
285
286     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
287                "user $user->nickname (user id: $user->id).");
288
289     $result = $flink->delete();
290
291     if (empty($result)) {
292         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
293                    "Foreign_link for $user->nickname (user id: $user->id)!");
294         common_log_db_error($flink, 'DELETE', __FILE__);
295     }
296
297     // Notify the user that her Twitter bridge is down
298
299     if (isset($user->email)) {
300
301         $result = mail_twitter_bridge_removed($user);
302
303         if (!$result) {
304
305             $msg = 'Unable to send email to notify ' .
306               "$user->nickname (user id: $user->id) " .
307               'that their Twitter bridge link was ' .
308               'removed!';
309
310             common_log(LOG_WARNING, $msg);
311         }
312     }
313
314 }
315
316 /**
317  * Send a mail message to notify a user that her Twitter bridge link
318  * has stopped working, and therefore has been removed.  This can
319  * happen when the user changes her Twitter password, or otherwise
320  * revokes access.
321  *
322  * @param User $user   user whose Twitter bridge link has been removed
323  *
324  * @return boolean success flag
325  */
326
327 function mail_twitter_bridge_removed($user)
328 {
329     common_init_locale($user->language);
330
331     $profile = $user->getProfile();
332
333     $subject = sprintf(_('Your Twitter bridge has been disabled.'));
334
335     $site_name = common_config('site', 'name');
336
337     $body = sprintf(_('Hi, %1$s. We\'re sorry to inform you that your ' .
338         'link to Twitter has been disabled. We no longer seem to have ' .
339     'permission to update your Twitter status. (Did you revoke ' .
340     '%3$s\'s access?)' . "\n\n" .
341     'You can re-enable your Twitter bridge by visiting your ' .
342     "Twitter settings page:\n\n\t%2\$s\n\n" .
343         "Regards,\n%3\$s\n"),
344         $profile->getBestName(),
345         common_local_url('twittersettings'),
346         common_config('site', 'name'));
347
348     common_init_locale();
349     return mail_to_user($user, $subject, $body);
350 }
351