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