]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/synctwitterfriends.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.x
[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/twitterbasicauthclient.php';
37 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
38
39 /**
40  * Daemon to sync local friends with Twitter friends
41  *
42  * @category Twitter
43  * @package  StatusNet
44  * @author   Zach Copley <zach@status.net>
45  * @author   Evan Prodromou <evan@status.net>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://status.net/
48  */
49
50 class SyncTwitterFriendsDaemon extends ParallelizingDaemon
51 {
52     /**
53      *  Constructor
54      *
55      * @param string  $id           the name/id of this daemon
56      * @param int     $interval     sleep this long before doing everything again
57      * @param int     $max_children maximum number of child processes at a time
58      * @param boolean $debug        debug output flag
59      *
60      * @return void
61      *
62      **/
63
64     function __construct($id = null, $interval = 60,
65                          $max_children = 2, $debug = null)
66     {
67         parent::__construct($id, $interval, $max_children, $debug);
68     }
69
70     /**
71      * Name of this daemon
72      *
73      * @return string Name of the daemon.
74      */
75
76     function name()
77     {
78         return ('synctwitterfriends.' . $this->_id);
79     }
80
81     /**
82      * Find all the Twitter foreign links for users who have requested
83      * automatically subscribing to their Twitter friends locally.
84      *
85      * @return array flinks an array of Foreign_link objects
86      */
87     function getObjects()
88     {
89         $flinks = array();
90         $flink = new Foreign_link();
91
92         $conn = &$flink->getDatabaseConnection();
93
94         $flink->service = TWITTER_SERVICE;
95         $flink->orderBy('last_friendsync');
96         $flink->limit(25);  // sync this many users during this run
97         $flink->find();
98
99         while ($flink->fetch()) {
100             if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
101                 $flinks[] = clone($flink);
102             }
103         }
104
105         $conn->disconnect();
106
107         global $_DB_DATAOBJECT;
108         unset($_DB_DATAOBJECT['CONNECTIONS']);
109
110         return $flinks;
111     }
112
113     function childTask($flink) {
114
115         // Each child ps needs its own DB connection
116
117         // Note: DataObject::getDatabaseConnection() creates
118         // a new connection if there isn't one already
119
120         $conn = &$flink->getDatabaseConnection();
121
122         $this->subscribeTwitterFriends($flink);
123
124         $flink->last_friendsync = common_sql_now();
125         $flink->update();
126
127         $conn->disconnect();
128
129         // XXX: Couldn't find a less brutal way to blow
130         // away a cached connection
131
132         global $_DB_DATAOBJECT;
133         unset($_DB_DATAOBJECT['CONNECTIONS']);
134     }
135
136     function fetchTwitterFriends($flink)
137     {
138         $friends = array();
139
140         $client = null;
141
142         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
143             $token = TwitterOAuthClient::unpackToken($flink->credentials);
144             $client = new TwitterOAuthClient($token->key, $token->secret);
145             common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
146         } else {
147             $client = new TwitterBasicAuthClient($flink);
148             common_debug($this->name() . '- Grabbing friends IDs with basic auth.');
149         }
150
151         try {
152             $friends_ids = $client->friendsIds();
153         } catch (Exception $e) {
154             common_log(LOG_WARNING, $this->name() .
155                        ' - error getting friend ids: ' .
156                        $e->getMessage());
157             return $friends;
158         }
159
160         if (empty($friends_ids)) {
161             common_debug($this->name() .
162                          " - Twitter user $flink->foreign_id " .
163                          'doesn\'t have any friends!');
164             return $friends;
165         }
166
167         common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
168                      "$flink->foreign_id has " .
169                      count($friends_ids) . ' friends.');
170
171         // Calculate how many pages to get...
172         $pages = ceil(count($friends_ids) / 100);
173
174         if ($pages == 0) {
175             common_debug($this->name() . " - $user seems to have no friends.");
176         }
177
178         for ($i = 1; $i <= $pages; $i++) {
179
180         try {
181             $more_friends = $client->statusesFriends(null, null, null, $i);
182         } catch (Exception $e) {
183             common_log(LOG_WARNING, $this->name() .
184                        ' - cURL error getting Twitter statuses/friends ' .
185                        "page $i - " . $e->getCode() . ' - ' .
186                        $e->getMessage());
187         }
188
189             if (empty($more_friends)) {
190                 common_log(LOG_WARNING, $this->name() .
191                            " - Couldn't retrieve page $i " .
192                            "of Twitter user $flink->foreign_id friends.");
193                 continue;
194             } else {
195                 $friends = array_merge($friends, $more_friends);
196             }
197         }
198
199         return $friends;
200     }
201
202     function subscribeTwitterFriends($flink)
203     {
204         $friends = $this->fetchTwitterFriends($flink);
205
206         if (empty($friends)) {
207             common_debug($this->name() .
208                          ' - Couldn\'t get friends from Twitter for ' .
209                          "Twitter user $flink->foreign_id.");
210             return false;
211         }
212
213         $user = $flink->getUser();
214
215         foreach ($friends as $friend) {
216
217             $friend_name = $friend->screen_name;
218             $friend_id = (int) $friend->id;
219
220             // Update or create the Foreign_user record for each
221             // Twitter friend
222
223             if (!save_twitter_user($friend_id, $friend_name)) {
224                 common_log(LOG_WARNING, $this->name() .
225                            " - Couldn't save $screen_name's friend, $friend_name.");
226                 continue;
227             }
228
229             // Check to see if there's a related local user
230
231             $friend_flink = Foreign_link::getByForeignID($friend_id,
232                                                          TWITTER_SERVICE);
233
234             if (!empty($friend_flink)) {
235
236                 // Get associated user and subscribe her
237
238                 $friend_user = User::staticGet('id', $friend_flink->user_id);
239
240                 if (!empty($friend_user)) {
241                     $result = subs_subscribe_to($user, $friend_user);
242
243                     if ($result === true) {
244                         common_log(LOG_INFO,
245                                    $this->name() . ' - Subscribed ' .
246                                    "$friend_user->nickname to $user->nickname.");
247                     } else {
248                         common_debug($this->name() .
249                                      ' - Tried subscribing ' .
250                                      "$friend_user->nickname to $user->nickname - " .
251                                      $result);
252                     }
253                 }
254             }
255         }
256
257         return true;
258     }
259
260 }
261
262 $id    = null;
263 $debug = null;
264
265 if (have_option('i')) {
266     $id = get_option_value('i');
267 } else if (have_option('--id')) {
268     $id = get_option_value('--id');
269 } else if (count($args) > 0) {
270     $id = $args[0];
271 } else {
272     $id = null;
273 }
274
275 if (have_option('d') || have_option('debug')) {
276     $debug = true;
277 }
278
279 $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
280 $syncer->runOnce();
281