]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/twitter.php
Upstream changes to OAuth.php
[quix0rs-gnu-social.git] / lib / twitter.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, 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('LACONICA')) { exit(1); }
21
22 define("TWITTER_SERVICE", 1); // Twitter is foreign_service ID 1
23
24 function get_twitter_data($uri, $screen_name, $password)
25 {
26
27     $options = array(
28             CURLOPT_USERPWD => sprintf("%s:%s", $screen_name, $password),
29             CURLOPT_RETURNTRANSFER    => true,
30             CURLOPT_FAILONERROR        => true,
31             CURLOPT_HEADER            => false,
32             CURLOPT_FOLLOWLOCATION    => true,
33             CURLOPT_USERAGENT      => "Laconica",
34             CURLOPT_CONNECTTIMEOUT    => 120,
35             CURLOPT_TIMEOUT            => 120,
36             # Twitter is strict about accepting invalid "Expect" headers
37             CURLOPT_HTTPHEADER => array('Expect:')
38     );
39
40     $ch = curl_init($uri);
41     curl_setopt_array($ch, $options);
42     $data = curl_exec($ch);
43     $errmsg = curl_error($ch);
44
45     if ($errmsg) {
46         common_debug("Twitter bridge - cURL error: $errmsg - trying to load: $uri with user $screen_name.",
47             __FILE__);
48     }
49
50     curl_close($ch);
51
52     return $data;
53 }
54
55 function twitter_user_info($screen_name, $password)
56 {
57
58     $uri = "http://twitter.com/users/show/$screen_name.json";
59     $data = get_twitter_data($uri, $screen_name, $password);
60
61     if (!$data) {
62         return false;
63     }
64
65     $twit_user = json_decode($data);
66
67     if (!$twit_user) {
68         return false;
69     }
70
71     return $twit_user;
72 }
73
74 function update_twitter_user($fuser, $twitter_id, $screen_name)
75 {
76
77     $original = clone($fuser);
78     $fuser->nickname = $screen_name;
79     $fuser->uri = 'http://twitter.com/' . $screen_name;
80     $result = $fuser->updateKeys($original);
81
82     if (!$result) {
83         common_log_db_error($fuser, 'UPDATE', __FILE__);
84         return false;
85     }
86
87     return true;
88 }
89
90 function add_twitter_user($twitter_id, $screen_name)
91 {
92
93     // Otherwise, create a new Twitter user
94     $fuser = DB_DataObject::factory('foreign_user');
95
96     $fuser->nickname = $screen_name;
97     $fuser->uri = 'http://twitter.com/' . $screen_name;
98     $fuser->id = $twitter_id;
99     $fuser->service = TWITTER_SERVICE; // Twitter
100     $fuser->created = common_sql_now();
101     $result = $fuser->insert();
102
103     if (!$result) {
104         common_debug("Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
105         common_log_db_error($fuser, 'INSERT', __FILE__);
106         return false;
107     }
108
109     common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
110
111     return true;
112 }
113
114 // Creates or Updates a Twitter user
115 function save_twitter_user($twitter_id, $screen_name)
116 {
117
118     // Check to see whether the Twitter user is already in the system,
119     // and update its screen name and uri if so.
120     $fuser = Foreign_user::getForeignUser($twitter_id, 1);
121
122     if ($fuser) {
123
124         // Only update if Twitter screen name has changed
125         if ($fuser->nickname != $screen_name) {
126
127             common_debug('Twitter bridge - Updated nickname (and URI) for Twitter user ' .
128                 "$fuser->id to $screen_name, was $fuser->nickname");
129
130             return update_twitter_user($fuser, $twitter_id, $screen_name);
131         }
132
133     } else {
134         return add_twitter_user($twitter_id, $screen_name);
135     }
136
137     return true;
138 }
139
140 function retreive_twitter_friends($twitter_id, $screen_name, $password)
141 {
142
143     $uri = "http://twitter.com/statuses/friends/$twitter_id.json?page=";
144     $twitter_user = twitter_user_info($screen_name, $password);
145
146     // Calculate how many pages to get...
147     $pages = ceil($twitter_user->friends_count / 100);
148
149     if ($pages == 0) {
150         common_debug("Twitter bridge - Twitter user $screen_name has no friends! Lame.");
151     }
152
153     $friends = array();
154
155     for ($i = 1; $i <= $pages; $i++) {
156
157         $data = get_twitter_data($uri . $i, $screen_name, $password);
158
159         if (!$data) {
160             return null;
161         }
162
163         $more_friends = json_decode($data);
164
165         if (!$more_friends) {
166             return null;
167         }
168
169          $friends = array_merge($friends, $more_friends);
170     }
171
172     return $friends;
173 }
174
175 function save_twitter_friends($user, $twitter_id, $screen_name, $password)
176 {
177
178     $friends = retreive_twitter_friends($twitter_id, $screen_name, $password);
179
180     if (is_null($friends)) {
181         common_debug("Twitter bridge - Couldn't get friends data from Twitter.");
182         return false;
183     }
184
185     foreach ($friends as $friend) {
186
187         $friend_name = $friend->screen_name;
188         $friend_id = $friend->id;
189
190         // Update or create the Foreign_user record
191         if (!save_twitter_user($friend_id, $friend_name)) {
192             return false;
193         }
194
195         // Check to see if there's a related local user
196         $flink = Foreign_link::getByForeignID($friend_id, 1);
197
198         if ($flink) {
199
200             // Get associated user and subscribe her
201             $friend_user = User::staticGet('id', $flink->user_id);
202             subs_subscribe_to($user, $friend_user);
203             common_debug("Twitter bridge - subscribed $friend_user->nickname to $user->nickname.");
204         }
205     }
206
207     return true;
208 }
209
210 function is_twitter_bound($notice, $flink) {
211
212     // Check to see if notice should go to Twitter
213     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
214
215         // If it's not a Twitter-style reply, or if the user WANTS to send replies.
216         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
217             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
218                 return true;
219         }
220     }
221
222     return false;
223 }
224
225 function broadcast_twitter($notice)
226 {
227     global $config;
228     $success = true;
229
230     $flink = Foreign_link::getByUserID($notice->profile_id,
231         TWITTER_SERVICE);
232
233     // XXX: Not sure WHERE to check whether a notice should go to
234     // Twitter. Should we even put in the queue if it shouldn't? --Zach
235     if (is_twitter_bound($notice, $flink)) {
236
237         $fuser = $flink->getForeignUser();
238         $twitter_user = $fuser->nickname;
239         $twitter_password = $flink->credentials;
240         $uri = 'http://www.twitter.com/statuses/update.json';
241
242         // XXX: Hack to get around PHP cURL's use of @ being a a meta character
243         $statustxt = preg_replace('/^@/', ' @', $notice->content);
244
245         $options = array(
246             CURLOPT_USERPWD        => "$twitter_user:$twitter_password",
247             CURLOPT_POST           => true,
248             CURLOPT_POSTFIELDS     =>
249                 array(
250                         'status' => $statustxt,
251                         'source' => $config['integration']['source']
252                      ),
253             CURLOPT_RETURNTRANSFER => true,
254             CURLOPT_FAILONERROR    => true,
255             CURLOPT_HEADER         => false,
256             CURLOPT_FOLLOWLOCATION => true,
257             CURLOPT_USERAGENT      => "Laconica",
258             CURLOPT_CONNECTTIMEOUT => 120,  // XXX: How long should this be?
259             CURLOPT_TIMEOUT        => 120,
260
261             # Twitter is strict about accepting invalid "Expect" headers
262             CURLOPT_HTTPHEADER => array('Expect:')
263             );
264
265         $ch = curl_init($uri);
266         curl_setopt_array($ch, $options);
267         $data = curl_exec($ch);
268         $errmsg = curl_error($ch);
269
270         if ($errmsg) {
271             common_debug("cURL error: $errmsg - " .
272                 "trying to send notice for $twitter_user.",
273                          __FILE__);
274             $success = false;
275         }
276
277         curl_close($ch);
278
279         if (!$data) {
280             common_debug("No data returned by Twitter's " .
281                 "API trying to send update for $twitter_user",
282                          __FILE__);
283             $success = false;
284         }
285
286         // Twitter should return a status
287         $status = json_decode($data);
288
289         if (!$status->id) {
290             common_debug("Unexpected data returned by Twitter " .
291                 " API trying to send update for $twitter_user",
292                          __FILE__);
293             $success = false;
294         }
295     }
296
297     return $success;
298 }
299