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