]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitter.php
e049dc8df0115106cffddca7eca072d544161b24
[quix0rs-gnu-social.git] / lib / 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 function update_twitter_user($twitter_id, $screen_name)
27 {
28     $uri = 'http://twitter.com/' . $screen_name;
29     $fuser = new Foreign_user();
30
31     $fuser->query('BEGIN');
32
33     // Dropping down to SQL because regular DB_DataObject udpate stuff doesn't seem
34     // to work so good with tables that have multiple column primary keys
35
36     // Any time we update the uri for a forein user we have to make sure there
37     // are no dupe entries first -- unique constraint on the uri column
38
39     $qry = 'UPDATE foreign_user set uri = \'\' WHERE uri = ';
40     $qry .= '\'' . $uri . '\'' . ' AND service = ' . TWITTER_SERVICE;
41
42     $fuser->query($qry);
43
44     // Update the user
45
46     $qry = 'UPDATE foreign_user SET nickname = ';
47     $qry .= '\'' . $screen_name . '\'' . ', uri = \'' . $uri . '\' ';
48     $qry .= 'WHERE id = ' . $twitter_id . ' AND service = ' . TWITTER_SERVICE;
49
50     $fuser->query('COMMIT');
51
52     $fuser->free();
53     unset($fuser);
54
55     return true;
56 }
57
58 function add_twitter_user($twitter_id, $screen_name)
59 {
60
61     $new_uri = 'http://twitter.com/' . $screen_name;
62
63     // Clear out any bad old foreign_users with the new user's legit URL
64     // This can happen when users move around or fakester accounts get
65     // repoed, and things like that.
66
67     $luser = new Foreign_user();
68     $luser->uri = $new_uri;
69     $luser->service = TWITTER_SERVICE;
70     $result = $luser->delete();
71
72     if (empty($result)) {
73         common_log(LOG_WARNING,
74             "Twitter bridge - removed invalid Twitter user squatting on uri: $new_uri");
75     }
76
77     $luser->free();
78     unset($luser);
79
80     // Otherwise, create a new Twitter user
81
82     $fuser = new Foreign_user();
83
84     $fuser->nickname = $screen_name;
85     $fuser->uri = 'http://twitter.com/' . $screen_name;
86     $fuser->id = $twitter_id;
87     $fuser->service = TWITTER_SERVICE;
88     $fuser->created = common_sql_now();
89     $result = $fuser->insert();
90
91     if (empty($result)) {
92         common_log(LOG_WARNING,
93             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
94         common_log_db_error($fuser, 'INSERT', __FILE__);
95     } else {
96         common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
97     }
98
99     return $result;
100 }
101
102 // Creates or Updates a Twitter user
103 function save_twitter_user($twitter_id, $screen_name)
104 {
105
106     // Check to see whether the Twitter user is already in the system,
107     // and update its screen name and uri if so.
108
109     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
110
111     if (!empty($fuser)) {
112
113         $result = true;
114
115         // Only update if Twitter screen name has changed
116
117         if ($fuser->nickname != $screen_name) {
118             $result = update_twitter_user($twitter_id, $screen_name);
119
120             common_debug('Twitter bridge - Updated nickname (and URI) for Twitter user ' .
121                 "$fuser->id to $screen_name, was $fuser->nickname");
122         }
123
124         return $result;
125
126     } else {
127         return add_twitter_user($twitter_id, $screen_name);
128     }
129
130     $fuser->free();
131     unset($fuser);
132
133     return true;
134 }
135
136 function is_twitter_bound($notice, $flink) {
137
138     // Check to see if notice should go to Twitter
139     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
140
141         // If it's not a Twitter-style reply, or if the user WANTS to send replies.
142         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
143             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
144             return true;
145         }
146     }
147
148     return false;
149 }
150
151 function broadcast_twitter($notice)
152 {
153     $flink = Foreign_link::getByUserID($notice->profile_id,
154                                        TWITTER_SERVICE);
155
156     if (is_twitter_bound($notice, $flink)) {
157         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
158             return broadcast_oauth($notice, $flink);
159         } else {
160             return broadcast_basicauth($notice, $flink);
161         }
162     }
163
164     return true;
165 }
166
167 function broadcast_oauth($notice, $flink) {
168
169     $user = $flink->getUser();
170     $statustxt = format_status($notice);
171     $token = TwitterOAuthClient::unpackToken($flink->credentials);
172     $client = new TwitterOAuthClient($token->key, $token->secret);
173     $status = null;
174
175     try {
176         $status = $client->statusesUpdate($statustxt);
177     } catch (OAuthClientCurlException $e) {
178
179         if ($e->getMessage() == 'The requested URL returned error: 401') {
180
181             $errmsg = sprintf('User %1$s (user id: %2$s) has an invalid ' .
182                               'Twitter OAuth access token.',
183                               $user->nickname, $user->id);
184             common_log(LOG_WARNING, $errmsg);
185
186             // Bad auth token! We need to delete the foreign_link
187             // to Twitter and inform the user.
188
189             remove_twitter_link($flink);
190             return true;
191
192         } else {
193
194             // Some other error happened, so we should probably
195             // try to send again later.
196
197             $errmsg = sprintf('cURL error trying to send notice to Twitter ' .
198                               'for user %1$s (user id: %2$s) - ' .
199                               'code: %3$s message: $4$s.',
200                               $user->nickname, $user->id,
201                               $e->getCode(), $e->getMessage());
202             common_log(LOG_WARNING, $errmsg);
203
204             return false;
205         }
206     }
207
208     if (empty($status)) {
209
210         // This could represent a failure posting,
211         // or the Twitter API might just be behaving flakey.
212
213         $errmsg = sprintf('No data returned by Twitter API when ' .
214                          'trying to send update for %1$s (user id %2$s).',
215                          $user->nickname, $user->id);
216         common_log(LOG_WARNING, $errmsg);
217
218         return false;
219     }
220
221     // Notice crossed the great divide
222
223     $msg = sprintf('Twitter bridge posted notice %s to Twitter using OAuth.',
224                    $notice->id);
225     common_log(LOG_INFO, $msg);
226
227     return true;
228 }
229
230 function broadcast_basicauth($notice, $flink)
231 {
232     $user = $flink->getUser();
233
234     $statustxt = format_status($notice);
235
236     $client = new TwitterBasicAuthClient($flink);
237     $status = null;
238
239     try {
240         $status = $client->statusesUpdate($statustxt);
241     } catch (BasicAuthCurlException $e) {
242
243         if ($e->getMessage() == 'The requested URL returned error: 401') {
244
245             $errmsg = sprintf('User %1$s (user id: %2$s) has an invalid ' .
246                               'Twitter screen_name/password combo.',
247                               $user->nickname, $user->id);
248             common_log(LOG_WARNING, $errmsg);
249
250             remove_twitter_link($flink);
251             return true;
252
253         } else {
254
255             $errmsg = sprintf('cURL error trying to send notice to Twitter ' .
256                               'for user %1$s (user id: %2$s) - ' .
257                               'code: %3$s message: $4$s.',
258                               $user->nickname, $user->id,
259                               $e->getCode(), $e->getMessage());
260             common_log(LOG_WARNING, $errmsg);
261
262             return false;
263         }
264     }
265
266     if (empty($status)) {
267
268         $errmsg = sprintf('No data returned by Twitter API when ' .
269                          'trying to send update for %1$s (user id %2$s).',
270                          $user->nickname, $user->id);
271         common_log(LOG_WARNING, $errmsg);
272
273         return false;
274     }
275
276     $msg = sprintf('Twitter bridge posted notice %s to Twitter using basic auth.',
277                    $notice->id);
278     common_log(LOG_INFO, $msg);
279
280     return true;
281
282 }
283
284 function format_status($notice)
285 {
286     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
287     return preg_replace('/^@/', ' @', $notice->content);
288 }
289
290 function remove_twitter_link($flink)
291 {
292     $user = $flink->getUser();
293
294     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
295                "user $user->nickname (user id: $user->id).");
296
297     $result = $flink->delete();
298
299     if (empty($result)) {
300         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
301                    "Foreign_link for $user->nickname (user id: $user->id)!");
302         common_log_db_error($flink, 'DELETE', __FILE__);
303     }
304
305     // Notify the user that her Twitter bridge is down
306
307     if (isset($user->email)) {
308
309         $result = mail_twitter_bridge_removed($user);
310
311         if (!$result) {
312
313             $msg = 'Unable to send email to notify ' .
314               "$user->nickname (user id: $user->id) " .
315               'that their Twitter bridge link was ' .
316               'removed!';
317
318             common_log(LOG_WARNING, $msg);
319         }
320     }
321
322 }