]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
OStatus: garbage collect unused PuSH subscriptions when the last local subscriber...
[quix0rs-gnu-social.git] / plugins / OStatus / OStatusPlugin.php
1 <?php
2 /*
3 StatusNet Plugin: 0.9
4 Plugin Name: FeedSub
5 Plugin URI: http://status.net/wiki/Feed_subscription
6 Description: FeedSub allows subscribing to real-time updates from external feeds supporting PubHubSubbub protocol.
7 Version: 0.1
8 Author: Brion Vibber <brion@status.net>
9 Author URI: http://status.net/
10 */
11
12 /*
13  * StatusNet - the distributed open-source microblogging tool
14  * Copyright (C) 2009, StatusNet, Inc.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU Affero General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU Affero General Public License for more details.
25  *
26  * You should have received a copy of the GNU Affero General Public License
27  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28  */
29
30 /**
31  * @package FeedSubPlugin
32  * @maintainer Brion Vibber <brion@status.net>
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
36
37 define('FEEDSUB_SERVICE', 100); // fixme -- avoid hardcoding these?
38
39 // We bundle the XML_Parse_Feed library...
40 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib');
41
42 class FeedSubException extends Exception
43 {
44 }
45
46 class OStatusPlugin extends Plugin
47 {
48     /**
49      * Hook for RouterInitialized event.
50      *
51      * @param Net_URL_Mapper $m path-to-action mapper
52      * @return boolean hook return
53      */
54     function onRouterInitialized($m)
55     {
56         // Discovery actions
57         $m->connect('.well-known/host-meta',
58                     array('action' => 'hostmeta'));
59         $m->connect('main/webfinger',
60                     array('action' => 'webfinger'));
61         $m->connect('main/ostatus',
62                     array('action' => 'ostatusinit'));
63         $m->connect('main/ostatus?nickname=:nickname',
64                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
65         $m->connect('main/ostatussub',
66                     array('action' => 'ostatussub'));          
67         $m->connect('main/ostatussub',
68                     array('action' => 'ostatussub'), array('feed' => '[A-Za-z0-9\.\/\:]+'));          
69
70         // PuSH actions
71         $m->connect('main/push/hub', array('action' => 'pushhub'));
72
73         $m->connect('main/push/callback/:feed',
74                     array('action' => 'pushcallback'),
75                     array('feed' => '[0-9]+'));
76         $m->connect('settings/feedsub',
77                     array('action' => 'feedsubsettings'));
78
79         // Salmon endpoint
80         $m->connect('main/salmon/user/:id',
81                     array('action' => 'salmon'),
82                     array('id' => '[0-9]+'));
83         return true;
84     }
85
86     /**
87      * Set up queue handlers for outgoing hub pushes
88      * @param QueueManager $qm
89      * @return boolean hook return
90      */
91     function onEndInitializeQueueManager(QueueManager $qm)
92     {
93         $qm->connect('hubverify', 'HubVerifyQueueHandler');
94         $qm->connect('hubdistrib', 'HubDistribQueueHandler');
95         $qm->connect('hubout', 'HubOutQueueHandler');
96         return true;
97     }
98
99     /**
100      * Put saved notices into the queue for pubsub distribution.
101      */
102     function onStartEnqueueNotice($notice, &$transports)
103     {
104         $transports[] = 'hubdistrib';
105         return true;
106     }
107
108     /**
109      * Set up a PuSH hub link to our internal link for canonical timeline
110      * Atom feeds for users and groups.
111      */
112     function onStartApiAtom(Action $action)
113     {
114         if ($action instanceof ApiTimelineUserAction || $action instanceof ApiTimelineGroupAction) {
115             $id = $action->arg('id');
116             if (strval(intval($id)) === strval($id)) {
117                 // Canonical form of id in URL? These are used for OStatus syndication.
118
119                 $hub = common_config('ostatus', 'hub');
120                 if (empty($hub)) {
121                     // Updates will be handled through our internal PuSH hub.
122                     $hub = common_local_url('pushhub');
123                 }
124                 $action->element('link', array('rel' => 'hub',
125                                                'href' => $hub));
126
127                 // Also, we'll add in the salmon link
128                 $action->element('link', array('rel' => 'salmon',
129                                                'href' => common_local_url('salmon')));
130             }
131         }
132         return true;
133     }
134     
135     /**
136      * Add the feed settings page to the Connect Settings menu
137      *
138      * @param Action &$action The calling page
139      *
140      * @return boolean hook return
141      */
142     function onEndConnectSettingsNav(&$action)
143     {
144         $action_name = $action->trimmed('action');
145
146         $action->menuItem(common_local_url('feedsubsettings'),
147                           _m('Feeds'),
148                           _m('Feed subscription options'),
149                           $action_name === 'feedsubsettings');
150
151         return true;
152     }
153
154     /**
155      * Automatically load the actions and libraries used by the plugin
156      *
157      * @param Class $cls the class
158      *
159      * @return boolean hook return
160      *
161      */
162     function onAutoload($cls)
163     {
164         $base = dirname(__FILE__);
165         $lower = strtolower($cls);
166         $files = array("$base/classes/$cls.php",
167                        "$base/lib/$lower.php");
168         if (substr($lower, -6) == 'action') {
169             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
170         }
171         foreach ($files as $file) {
172             if (file_exists($file)) {
173                 include_once $file;
174                 return false;
175             }
176         }
177         return true;
178     }
179
180     /**
181      * Add in an OStatus subscribe button
182      */
183     function onStartProfilePageActionsElements($output, $profile)
184     {
185         $cur = common_current_user();
186
187         if (empty($cur)) {
188             // Add an OStatus subscribe
189             $output->elementStart('li', 'entity_subscribe');
190             $url = common_local_url('ostatusinit',
191                                     array('nickname' => $profile->nickname));
192             $output->element('a', array('href' => $url,
193                                         'class' => 'entity_remote_subscribe'),
194                                 _('OStatus'));
195             
196             $output->elementEnd('li');
197         }
198     }
199
200     /**
201      * Check if we've got some Salmon stuff to send
202      */
203     function onEndNoticeSave($notice)
204     {
205         $count = preg_match_all('/(\w+\.)*\w+@(\w+\.)*\w+(\w+\-\w+)*\.\w+/', $notice->content, $matches);
206         if ($count) {
207             foreach ($matches[0] as $webfinger) {
208                 // Check to see if we've got an actual webfinger
209                 $w = new Webfinger;
210
211                 $endpoint_uri = '';
212                 
213                 $result = $w->lookup($webfinger);
214                 if (empty($result)) {
215                     continue;
216                 }
217                 
218                 foreach ($result->links as $link) {
219                     if ($link['rel'] == 'salmon') {
220                         $endpoint_uri = $link['href'];
221                     }
222                 }
223                 
224                 if (empty($endpoint_uri)) {
225                     continue;
226                 }
227
228                 $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
229                 $xml .= $notice->asAtomEntry();
230                
231                 $salmon = new Salmon();
232                 $salmon->post($endpoint_uri, $xml);
233             }
234         }
235     }
236     
237
238     /**
239      * Garbage collect unused feeds on unsubscribe
240      */
241     function onEndUnsubscribe($user, $other)
242     {
243         $feed = Feedinfo::staticGet('profile_id', $other->id);
244         if ($feed) {
245             $sub = new Subscription();
246             $sub->subscribed = $other->id;
247             $sub->limit(1);
248             if (!$sub->find(true)) {
249                 common_log(LOG_INFO, "Unsubscribing from now-unused feed $feed->feeduri on hub $feed->huburi");
250                 $feed->unsubscribe();
251             }
252         }
253         return true;
254     }
255
256     
257     function onCheckSchema() {
258         $schema = Schema::get();
259         $schema->ensureTable('feedinfo', Feedinfo::schemaDef());
260         $schema->ensureTable('hubsub', HubSub::schemaDef());
261         return true;
262     }
263 }