]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitter.php
Better check to see if the XML prolog should be outputted for XML
[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         return process_error($e, $flink);
179     }
180
181     if (empty($status)) {
182
183         // This could represent a failure posting,
184         // or the Twitter API might just be behaving flakey.
185
186         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
187                           'trying to send update for %1$s (user id %2$s).',
188                           $user->nickname, $user->id);
189         common_log(LOG_WARNING, $errmsg);
190
191         return false;
192     }
193
194     // Notice crossed the great divide
195
196     $msg = sprintf('Twitter bridge - posted notice %s to Twitter using OAuth.',
197                    $notice->id);
198     common_log(LOG_INFO, $msg);
199
200     return true;
201 }
202
203 function broadcast_basicauth($notice, $flink)
204 {
205     $user = $flink->getUser();
206
207     $statustxt = format_status($notice);
208
209     $client = new TwitterBasicAuthClient($flink);
210     $status = null;
211
212     try {
213         $status = $client->statusesUpdate($statustxt);
214     } catch (BasicAuthCurlException $e) {
215         return process_error($e, $flink);
216     }
217
218     if (empty($status)) {
219
220         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
221                           'trying to send update for %1$s (user id %2$s).',
222                           $user->nickname, $user->id);
223         common_log(LOG_WARNING, $errmsg);
224
225         return false;
226     }
227
228     $msg = sprintf('Twitter bridge - posted notice %s to Twitter using basic auth.',
229                    $notice->id);
230     common_log(LOG_INFO, $msg);
231
232     return true;
233 }
234
235 function process_error($e, $flink)
236 {
237     $user        = $flink->getUser();
238     $errmsg      = $e->getMessage();
239     $delivered   = false;
240
241     switch($errmsg) {
242      case 'The requested URL returned error: 401':
243         $logmsg = sprintf('Twiter bridge - User %1$s (user id: %2$s) has an invalid ' .
244                           'Twitter screen_name/password combo or an invalid acesss token.',
245                           $user->nickname, $user->id);
246         $delivered = true;
247         remove_twitter_link($flink);
248         break;
249      case 'The requested URL returned error: 403':
250         $logmsg = sprintf('Twitter bridge - User %1$s (user id: %2$s) has exceeded ' .
251                           'his/her Twitter request limit.',
252                           $user->nickname, $user->id);
253         break;
254      default:
255         $logmsg = sprintf('Twitter bridge - 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         break;
261     }
262
263     common_log(LOG_WARNING, $logmsg);
264
265     return $delivered;
266 }
267
268 function format_status($notice)
269 {
270     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
271     return preg_replace('/^@/', ' @', $notice->content);
272 }
273
274 function remove_twitter_link($flink)
275 {
276     $user = $flink->getUser();
277
278     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
279                "user $user->nickname (user id: $user->id).");
280
281     $result = $flink->delete();
282
283     if (empty($result)) {
284         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
285                    "Foreign_link for $user->nickname (user id: $user->id)!");
286         common_log_db_error($flink, 'DELETE', __FILE__);
287     }
288
289     // Notify the user that her Twitter bridge is down
290
291     if (isset($user->email)) {
292
293         $result = mail_twitter_bridge_removed($user);
294
295         if (!$result) {
296
297             $msg = 'Unable to send email to notify ' .
298               "$user->nickname (user id: $user->id) " .
299               'that their Twitter bridge link was ' .
300               'removed!';
301
302             common_log(LOG_WARNING, $msg);
303         }
304     }
305
306 }