]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/synctwitterfriends.php
remove require_once for disappeared TwitterBasicAuthClient
[quix0rs-gnu-social.git] / plugins / TwitterBridge / daemons / synctwitterfriends.php
1 #!/usr/bin/env php
2 <?php
3 /*
4  * StatusNet - the distributed open-source microblogging tool
5  * Copyright (C) 2008, 2009, StatusNet, Inc.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
22
23 $shortoptions = 'di::';
24 $longoptions = array('id::', 'debug');
25
26 $helptext = <<<END_OF_TRIM_HELP
27 Batch script for synching local friends with Twitter friends.
28   -i --id              Identity (default 'generic')
29   -d --debug           Debug (lots of log output)
30
31 END_OF_TRIM_HELP;
32
33 require_once INSTALLDIR . '/scripts/commandline.inc';
34 require_once INSTALLDIR . '/lib/parallelizingdaemon.php';
35 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
36 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
37
38 /**
39  * Daemon to sync local friends with Twitter friends
40  *
41  * @category Twitter
42  * @package  StatusNet
43  * @author   Zach Copley <zach@status.net>
44  * @author   Evan Prodromou <evan@status.net>
45  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46  * @link     http://status.net/
47  */
48
49 class SyncTwitterFriendsDaemon extends ParallelizingDaemon
50 {
51     /**
52      *  Constructor
53      *
54      * @param string  $id           the name/id of this daemon
55      * @param int     $interval     sleep this long before doing everything again
56      * @param int     $max_children maximum number of child processes at a time
57      * @param boolean $debug        debug output flag
58      *
59      * @return void
60      *
61      **/
62
63     function __construct($id = null, $interval = 60,
64                          $max_children = 2, $debug = null)
65     {
66         parent::__construct($id, $interval, $max_children, $debug);
67     }
68
69     /**
70      * Name of this daemon
71      *
72      * @return string Name of the daemon.
73      */
74
75     function name()
76     {
77         return ('synctwitterfriends.' . $this->_id);
78     }
79
80     /**
81      * Find all the Twitter foreign links for users who have requested
82      * automatically subscribing to their Twitter friends locally.
83      *
84      * @return array flinks an array of Foreign_link objects
85      */
86     function getObjects()
87     {
88         $flinks = array();
89         $flink = new Foreign_link();
90
91         $conn = &$flink->getDatabaseConnection();
92
93         $flink->service = TWITTER_SERVICE;
94         $flink->orderBy('last_friendsync');
95         $flink->limit(25);  // sync this many users during this run
96         $flink->find();
97
98         while ($flink->fetch()) {
99             if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
100                 $flinks[] = clone($flink);
101             }
102         }
103
104         $conn->disconnect();
105
106         global $_DB_DATAOBJECT;
107         unset($_DB_DATAOBJECT['CONNECTIONS']);
108
109         return $flinks;
110     }
111
112     function childTask($flink) {
113
114         // Each child ps needs its own DB connection
115
116         // Note: DataObject::getDatabaseConnection() creates
117         // a new connection if there isn't one already
118
119         $conn = &$flink->getDatabaseConnection();
120
121         $this->subscribeTwitterFriends($flink);
122
123         $flink->last_friendsync = common_sql_now();
124         $flink->update();
125
126         $conn->disconnect();
127
128         // XXX: Couldn't find a less brutal way to blow
129         // away a cached connection
130
131         global $_DB_DATAOBJECT;
132         unset($_DB_DATAOBJECT['CONNECTIONS']);
133     }
134
135     function fetchTwitterFriends($flink)
136     {
137         $friends = array();
138
139         $client = null;
140
141         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
142             $token = TwitterOAuthClient::unpackToken($flink->credentials);
143             $client = new TwitterOAuthClient($token->key, $token->secret);
144             common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
145         } else {
146             common_debug("Skipping Twitter friends for {$flink->user_id} since not OAuth.");
147             return $friends;
148         }
149
150         try {
151             $friends_ids = $client->friendsIds();
152         } catch (Exception $e) {
153             common_log(LOG_WARNING, $this->name() .
154                        ' - error getting friend ids: ' .
155                        $e->getMessage());
156             return $friends;
157         }
158
159         if (empty($friends_ids)) {
160             common_debug($this->name() .
161                          " - Twitter user $flink->foreign_id " .
162                          'doesn\'t have any friends!');
163             return $friends;
164         }
165
166         common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
167                      "$flink->foreign_id has " .
168                      count($friends_ids) . ' friends.');
169
170         // Calculate how many pages to get...
171         $pages = ceil(count($friends_ids) / 100);
172
173         if ($pages == 0) {
174             common_debug($this->name() . " - $user seems to have no friends.");
175         }
176
177         for ($i = 1; $i <= $pages; $i++) {
178
179         try {
180             $more_friends = $client->statusesFriends(null, null, null, $i);
181         } catch (Exception $e) {
182             common_log(LOG_WARNING, $this->name() .
183                        ' - cURL error getting Twitter statuses/friends ' .
184                        "page $i - " . $e->getCode() . ' - ' .
185                        $e->getMessage());
186         }
187
188             if (empty($more_friends)) {
189                 common_log(LOG_WARNING, $this->name() .
190                            " - Couldn't retrieve page $i " .
191                            "of Twitter user $flink->foreign_id friends.");
192                 continue;
193             } else {
194                 $friends = array_merge($friends, $more_friends);
195             }
196         }
197
198         return $friends;
199     }
200
201     function subscribeTwitterFriends($flink)
202     {
203         $friends = $this->fetchTwitterFriends($flink);
204
205         if (empty($friends)) {
206             common_debug($this->name() .
207                          ' - Couldn\'t get friends from Twitter for ' .
208                          "Twitter user $flink->foreign_id.");
209             return false;
210         }
211
212         $user = $flink->getUser();
213
214         foreach ($friends as $friend) {
215
216             $friend_name = $friend->screen_name;
217             $friend_id = (int) $friend->id;
218
219             // Update or create the Foreign_user record for each
220             // Twitter friend
221
222             if (!save_twitter_user($friend_id, $friend_name)) {
223                 common_log(LOG_WARNING, $this->name() .
224                            " - Couldn't save $screen_name's friend, $friend_name.");
225                 continue;
226             }
227
228             // Check to see if there's a related local user
229
230             $friend_flink = Foreign_link::getByForeignID($friend_id,
231                                                          TWITTER_SERVICE);
232
233             if (!empty($friend_flink)) {
234
235                 // Get associated user and subscribe her
236
237                 $friend_user = User::staticGet('id', $friend_flink->user_id);
238
239                 if (!empty($friend_user)) {
240                     $result = subs_subscribe_to($user, $friend_user);
241
242                     if ($result === true) {
243                         common_log(LOG_INFO,
244                                    $this->name() . ' - Subscribed ' .
245                                    "$friend_user->nickname to $user->nickname.");
246                     } else {
247                         common_debug($this->name() .
248                                      ' - Tried subscribing ' .
249                                      "$friend_user->nickname to $user->nickname - " .
250                                      $result);
251                     }
252                 }
253             }
254         }
255
256         return true;
257     }
258
259 }
260
261 $id    = null;
262 $debug = null;
263
264 if (have_option('i')) {
265     $id = get_option_value('i');
266 } else if (have_option('--id')) {
267     $id = get_option_value('--id');
268 } else if (count($args) > 0) {
269     $id = $args[0];
270 } else {
271     $id = null;
272 }
273
274 if (have_option('d') || have_option('debug')) {
275     $debug = true;
276 }
277
278 $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
279 $syncer->runOnce();
280