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