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