]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/ostatusqueuehandler.php
Don't accept non-objects before testing with "instanceof".
[quix0rs-gnu-social.git] / plugins / OStatus / lib / ostatusqueuehandler.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 /**
25  * Prepare PuSH and Salmon distributions for an outgoing message.
26  *
27  * @package OStatusPlugin
28  * @author Brion Vibber <brion@status.net>
29  */
30 class OStatusQueueHandler extends QueueHandler
31 {
32     // If we have more than this many subscribing sites on a single feed,
33     // break up the PuSH distribution into smaller batches which will be
34     // rolled into the queue progressively. This reduces disruption to
35     // other, shorter activities being enqueued while we work.
36     const MAX_UNBATCHED = 50;
37
38     // Each batch (a 'hubprep' entry) will have this many items.
39     // Selected to provide a balance between queue packet size
40     // and number of batches that will end up getting processed.
41     // For 20,000 target sites, 1000 should work acceptably.
42     const BATCH_SIZE = 1000;
43
44     function transport()
45     {
46         return 'ostatus';
47     }
48
49     function handle($notice)
50     {
51         assert($notice instanceof Notice);
52
53         $this->notice = $notice;
54         $this->user = User::getKV('id', $notice->profile_id);
55
56         try {
57             $profile = $this->notice->getProfile();
58         } catch (Exception $e) {
59             common_log(LOG_ERR, "Can't get profile for notice; skipping: " . $e->getMessage());
60             return true;
61         }
62
63         if ($notice->isLocal()) {
64             // Notices generated on remote sites will have already
65             // been pushed to user's subscribers by their origin sites.
66             $this->pushUser();
67         }
68
69         foreach ($notice->getAttentionProfiles() as $target) {
70             common_debug("OSTATUS [{$this->notice->getID()}]: Attention target profile {$target->getNickname()} ({$target->getID()})");
71             if ($target->isGroup()) {
72                 common_debug("OSTATUS [{$this->notice->getID()}]: {$target->getID()} is a group");
73                 $oprofile = Ostatus_profile::getKV('group_id', $target->getGroup()->getID());
74                 if (!$oprofile instanceof Ostatus_profile) {
75                     // we don't save profiles like this yet, but in the future
76                     $oprofile = Ostatus_profile::getKV('profile_id', $target->getID());
77                 }
78                 if ($oprofile instanceof Ostatus_profile) {
79                     // remote group
80                     if ($notice->isLocal()) {
81                         common_debug("OSTATUS [{$this->notice->getID()}]: notice is local and remote group with profile ID {$target->getID()} gets a ping");
82                         $this->pingReply($oprofile);
83                     }
84                 } else {
85                     common_debug("OSTATUS [{$this->notice->getID()}]: local group with profile id {$target->getID()} gets pushed out");
86                     // local group
87                     $this->pushGroup($target->getGroup());
88                 }
89             } elseif ($notice->isLocal()) {
90                 // Notices generated on other sites will have already
91                 // pinged their reply-targets, so only do these things
92                 // if the target is not a group and the notice is locally generated
93
94                 $oprofile = Ostatus_profile::getKV('profile_id', $target->getID());
95                 if ($oprofile instanceof Ostatus_profile) {
96                     common_debug("OSTATUS [{$this->notice->getID()}]: Notice is local and {$target->getID()} is remote profile, getting pingReply");
97                     $this->pingReply($oprofile);
98                 }
99             }
100         }
101
102         if ($notice->isLocal()) {
103             try {
104                 $parent = $this->notice->getParent();
105                 foreach($parent->getAttentionProfiles() as $related) {
106                     if ($related->isGroup()) {
107                         // don't ping groups in parent notices since we might not be a member of them,
108                         // though it could be useful if we study this and use it correctly
109                         continue;
110                     }
111                     common_debug("OSTATUS [{$this->notice->getID()}]: parent notice {$parent->getID()} has related profile id=={$related->getID()}");
112                     // FIXME: don't ping twice in case someone is in both notice attention spans!
113                     $oprofile = Ostatus_profile::getKV('profile_id', $related->getID());
114                     if ($oprofile instanceof Ostatus_profile) {
115                         $this->pingReply($oprofile);
116                     }
117                 }
118             } catch (NoParentNoticeException $e) {
119                 // nothing to do then
120             }
121
122             foreach ($notice->getProfileTags() as $ptag) {
123                 $oprofile = Ostatus_profile::getKV('peopletag_id', $ptag->id);
124                 if (!$oprofile) {
125                     $this->pushPeopletag($ptag);
126                 }
127             }
128         }
129
130         return true;
131     }
132
133     function pushUser()
134     {
135         if ($this->user) {
136             common_debug("OSTATUS [{$this->notice->getID()}]: pushing feed for local user {$this->user->getID()}");
137             // For local posts, ping the PuSH hub to update their feed.
138             // http://identi.ca/api/statuses/user_timeline/1.atom
139             $feed = common_local_url('ApiTimelineUser',
140                                      array('id' => $this->user->id,
141                                            'format' => 'atom'));
142             $this->pushFeed($feed, array($this, 'userFeedForNotice'));
143         }
144     }
145
146     function pushGroup(User_group $group)
147     {
148         common_debug("OSTATUS [{$this->notice->getID()}]: pushing group '{$group->getNickname()}' profile_id={$group->profile_id}");
149         // For a local group, ping the PuSH hub to update its feed.
150         // Updates may come from either a local or a remote user.
151         $feed = common_local_url('ApiTimelineGroup',
152                                  array('id' => $group->getID(),
153                                        'format' => 'atom'));
154         $this->pushFeed($feed, array($this, 'groupFeedForNotice'), $group->getID());
155     }
156
157     function pushPeopletag($ptag)
158     {
159         common_debug("OSTATUS [{$this->notice->getID()}]: pushing peopletag '{$ptag->id}'");
160         // For a local people tag, ping the PuSH hub to update its feed.
161         // Updates may come from either a local or a remote user.
162         $feed = common_local_url('ApiTimelineList',
163                                  array('id' => $ptag->id,
164                                        'user' => $ptag->tagger,
165                                        'format' => 'atom'));
166         $this->pushFeed($feed, array($this, 'peopletagFeedForNotice'), $ptag);
167     }
168
169     function pingReply(Ostatus_profile $oprofile)
170     {
171         if ($this->user) {
172             common_debug("OSTATUS [{$this->notice->getID()}]: pinging reply to {$oprofile->localProfile()->getNickname()} for local user '{$this->user->getID()}'");
173             // For local posts, send a Salmon ping to the mentioned
174             // remote user or group.
175             // @fixme as an optimization we can skip this if the
176             // remote profile is subscribed to the author.
177             $oprofile->notifyDeferred($this->notice, $this->user->getProfile());
178         }
179     }
180
181     /**
182      * @param string $feed URI to the feed
183      * @param callable $callback function to generate Atom feed update if needed
184      *        any additional params are passed to the callback.
185      */
186     function pushFeed($feed, $callback)
187     {
188         $hub = common_config('ostatus', 'hub');
189         if ($hub) {
190             $this->pushFeedExternal($feed, $hub);
191         }
192
193         $sub = new HubSub();
194         $sub->topic = $feed;
195         if ($sub->find()) {
196             $args = array_slice(func_get_args(), 2);
197             $atom = call_user_func_array($callback, $args);
198             $this->pushFeedInternal($atom, $sub);
199         } else {
200             common_log(LOG_INFO, "No PuSH subscribers for $feed");
201         }
202         return true;
203     }
204
205     /**
206      * Ping external hub about this update.
207      * The hub will pull the feed and check for new items later.
208      * Not guaranteed safe in an environment with database replication.
209      *
210      * @param string $feed feed topic URI
211      * @param string $hub PuSH hub URI
212      * @fixme can consolidate pings for user & group posts
213      */
214     function pushFeedExternal($feed, $hub)
215     {
216         $client = new HTTPClient();
217         try {
218             $data = array('hub.mode' => 'publish',
219                           'hub.url' => $feed);
220             $response = $client->post($hub, array(), $data);
221             if ($response->getStatus() == 204) {
222                 common_log(LOG_INFO, "PuSH ping to hub $hub for $feed ok");
223                 return true;
224             } else {
225                 common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed with HTTP " .
226                                     $response->getStatus() . ': ' .
227                                     $response->getBody());
228             }
229         } catch (Exception $e) {
230             common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed: " . $e->getMessage());
231             return false;
232         }
233     }
234
235     /**
236      * Queue up direct feed update pushes to subscribers on our internal hub.
237      * If there are a large number of subscriber sites, intermediate bulk
238      * distribution triggers may be queued.
239      *
240      * @param string $atom update feed, containing only new/changed items
241      * @param HubSub $sub open query of subscribers
242      */
243     function pushFeedInternal($atom, $sub)
244     {
245         common_log(LOG_INFO, "Preparing $sub->N PuSH distribution(s) for $sub->topic");
246         $n = 0;
247         $batch = array();
248         while ($sub->fetch()) {
249             $n++;
250             if ($n < self::MAX_UNBATCHED) {
251                 $sub->distribute($atom);
252             } else {
253                 $batch[] = $sub->callback;
254                 if (count($batch) >= self::BATCH_SIZE) {
255                     $sub->bulkDistribute($atom, $batch);
256                     $batch = array();
257                 }
258             }
259         }
260         if (count($batch) > 0) {
261             $sub->bulkDistribute($atom, $batch);
262         }
263     }
264
265     /**
266      * Build a single-item version of the sending user's Atom feed.
267      * @return string
268      */
269     function userFeedForNotice()
270     {
271         $atom = new AtomUserNoticeFeed($this->user);
272         $atom->addEntryFromNotice($this->notice);
273         $feed = $atom->getString();
274
275         return $feed;
276     }
277
278     function groupFeedForNotice($group_id)
279     {
280         $group = User_group::getKV('id', $group_id);
281
282         $atom = new AtomGroupNoticeFeed($group);
283         $atom->addEntryFromNotice($this->notice);
284         $feed = $atom->getString();
285
286         return $feed;
287     }
288
289     function peopletagFeedForNotice($ptag)
290     {
291         $atom = new AtomListNoticeFeed($ptag);
292         $atom->addEntryFromNotice($this->notice);
293         $feed = $atom->getString();
294
295         return $feed;
296     }
297 }