]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
OStatus feedsub fixlets:
[quix0rs-gnu-social.git] / plugins / OStatus / OStatusPlugin.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-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 /**
21  * @package OStatusPlugin
22  * @maintainer Brion Vibber <brion@status.net>
23  */
24
25 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
26
27 class FeedSubException extends Exception
28 {
29 }
30
31 class OStatusPlugin extends Plugin
32 {
33     /**
34      * Hook for RouterInitialized event.
35      *
36      * @param Net_URL_Mapper $m path-to-action mapper
37      * @return boolean hook return
38      */
39     function onRouterInitialized($m)
40     {
41         // Discovery actions
42         $m->connect('.well-known/host-meta',
43                     array('action' => 'hostmeta'));
44         $m->connect('main/webfinger',
45                     array('action' => 'webfinger'));
46         $m->connect('main/ostatus',
47                     array('action' => 'ostatusinit'));
48         $m->connect('main/ostatus?nickname=:nickname',
49                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
50         $m->connect('main/ostatussub',
51                     array('action' => 'ostatussub'));
52         $m->connect('main/ostatussub',
53                     array('action' => 'ostatussub'), array('feed' => '[A-Za-z0-9\.\/\:]+'));
54
55         // PuSH actions
56         $m->connect('main/push/hub', array('action' => 'pushhub'));
57
58         $m->connect('main/push/callback/:feed',
59                     array('action' => 'pushcallback'),
60                     array('feed' => '[0-9]+'));
61         $m->connect('settings/feedsub',
62                     array('action' => 'feedsubsettings'));
63
64         // Salmon endpoint
65         $m->connect('main/salmon/user/:id',
66                     array('action' => 'usersalmon'),
67                     array('id' => '[0-9]+'));
68         $m->connect('main/salmon/group/:id',
69                     array('action' => 'groupsalmon'),
70                     array('id' => '[0-9]+'));
71         return true;
72     }
73
74     /**
75      * Set up queue handlers for outgoing hub pushes
76      * @param QueueManager $qm
77      * @return boolean hook return
78      */
79     function onEndInitializeQueueManager(QueueManager $qm)
80     {
81         // Outgoing from our internal PuSH hub
82         $qm->connect('hubverify', 'HubVerifyQueueHandler');
83         $qm->connect('hubdistrib', 'HubDistribQueueHandler');
84         $qm->connect('hubout', 'HubOutQueueHandler');
85
86         // Incoming from a foreign PuSH hub
87         $qm->connect('pushinput', 'PushInputQueueHandler');
88         return true;
89     }
90
91     /**
92      * Put saved notices into the queue for pubsub distribution.
93      */
94     function onStartEnqueueNotice($notice, &$transports)
95     {
96         $transports[] = 'hubdistrib';
97         return true;
98     }
99
100     /**
101      * Set up a PuSH hub link to our internal link for canonical timeline
102      * Atom feeds for users and groups.
103      */
104     function onStartApiAtom($feed)
105     {
106         $id = null;
107
108         if ($feed instanceof AtomUserNoticeFeed) {
109             $salmonAction = 'usersalmon';
110             $user = $feed->getUser();
111             $id   = $user->id;
112             $profile = $user->getProfile();
113             $feed->setActivitySubject($profile->asActivityNoun('subject'));
114         } else if ($feed instanceof AtomGroupNoticeFeed) {
115             $salmonAction = 'groupsalmon';
116             $group = $feed->getGroup();
117             $id = $group->id;
118             $feed->setActivitySubject($group->asActivitySubject());
119         } else {
120             return true;
121         }
122
123         if (!empty($id)) {
124             $hub = common_config('ostatus', 'hub');
125             if (empty($hub)) {
126                 // Updates will be handled through our internal PuSH hub.
127                 $hub = common_local_url('pushhub');
128             }
129             $feed->addLink($hub, array('rel' => 'hub'));
130
131             // Also, we'll add in the salmon link
132             $salmon = common_local_url($salmonAction, array('id' => $id));
133             $feed->addLink($salmon, array('rel' => 'salmon'));
134         }
135
136         return true;
137     }
138
139     /**
140      * Add the feed settings page to the Connect Settings menu
141      *
142      * @param Action &$action The calling page
143      *
144      * @return boolean hook return
145      */
146     function onEndConnectSettingsNav(&$action)
147     {
148         $action_name = $action->trimmed('action');
149
150         $action->menuItem(common_local_url('feedsubsettings'),
151                           _m('Feeds'),
152                           _m('Feed subscription options'),
153                           $action_name === 'feedsubsettings');
154
155         return true;
156     }
157
158     /**
159      * Automatically load the actions and libraries used by the plugin
160      *
161      * @param Class $cls the class
162      *
163      * @return boolean hook return
164      *
165      */
166     function onAutoload($cls)
167     {
168         $base = dirname(__FILE__);
169         $lower = strtolower($cls);
170         $map = array('activityverb' => 'activity',
171                      'activityobject' => 'activity',
172                      'activityutils' => 'activity');
173         if (isset($map[$lower])) {
174             $lower = $map[$lower];
175         }
176         $files = array("$base/classes/$cls.php",
177                        "$base/lib/$lower.php");
178         if (substr($lower, -6) == 'action') {
179             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
180         }
181         foreach ($files as $file) {
182             if (file_exists($file)) {
183                 include_once $file;
184                 return false;
185             }
186         }
187         return true;
188     }
189
190     /**
191      * Add in an OStatus subscribe button
192      */
193     function onStartProfileRemoteSubscribe($output, $profile)
194     {
195         $cur = common_current_user();
196
197         if (empty($cur)) {
198             // Add an OStatus subscribe
199             $output->elementStart('li', 'entity_subscribe');
200             $url = common_local_url('ostatusinit',
201                                     array('nickname' => $profile->nickname));
202             $output->element('a', array('href' => $url,
203                                         'class' => 'entity_remote_subscribe'),
204                                 _m('Subscribe'));
205
206             $output->elementEnd('li');
207         }
208
209         return false;
210     }
211
212     /**
213      * Check if we've got remote replies to send via Salmon.
214      *
215      * @fixme push webfinger lookup & sending to a background queue
216      * @fixme also detect short-form name for remote subscribees where not ambiguous
217      */
218     function onEndNoticeSave($notice)
219     {
220         $count = preg_match_all('/(\w+\.)*\w+@(\w+\.)*\w+(\w+\-\w+)*\.\w+/', $notice->content, $matches);
221         if ($count) {
222             foreach ($matches[0] as $webfinger) {
223
224                 // FIXME: look up locally first
225
226                 // Check to see if we've got an actual webfinger
227                 $w = new Webfinger;
228
229                 $endpoint_uri = '';
230
231                 $result = $w->lookup($webfinger);
232                 if (empty($result)) {
233                     continue;
234                 }
235
236                 foreach ($result->links as $link) {
237                     if ($link['rel'] == 'salmon') {
238                         $endpoint_uri = $link['href'];
239                     }
240                 }
241
242                 if (empty($endpoint_uri)) {
243                     continue;
244                 }
245
246                 // FIXME: this needs to go out in a queue handler
247
248                 $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
249                 $xml .= $notice->asAtomEntry();
250
251                 $salmon = new Salmon();
252                 $salmon->post($endpoint_uri, $xml);
253             }
254         }
255     }
256
257     /**
258      * Notify remote server and garbage collect unused feeds on unsubscribe.
259      * @fixme send these operations to background queues
260      *
261      * @param User $user
262      * @param Profile $other
263      * @return hook return value
264      */
265     function onEndUnsubscribe($profile, $other)
266     {
267         $user = User::staticGet('id', $profile->id);
268
269         if (empty($user)) {
270             return true;
271         }
272
273         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
274
275         if (empty($oprofile)) {
276             return true;
277         }
278
279         // Drop the PuSH subscription if there are no other subscribers.
280
281         if ($other->subscriberCount() == 0) {
282             common_log(LOG_INFO, "Unsubscribing from now-unused feed $oprofile->feeduri");
283             $oprofile->unsubscribe();
284         }
285
286         $act = new Activity();
287
288         $act->verb = ActivityVerb::UNFOLLOW;
289
290         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
291                                   $profile->id,
292                                   $other->id,
293                                   common_date_iso8601(time()));
294
295         $act->time    = time();
296         $act->title   = _("Unfollow");
297         $act->content = sprintf(_("%s stopped following %s."),
298                                $profile->getBestName(),
299                                $other->getBestName());
300
301         $act->actor   = ActivityObject::fromProfile($profile);
302         $act->object  = ActivityObject::fromProfile($other);
303
304         $oprofile->notifyActivity($act);
305
306         return true;
307     }
308
309     /**
310      * Make sure necessary tables are filled out.
311      */
312     function onCheckSchema() {
313         $schema = Schema::get();
314         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
315         $schema->ensureTable('feedsub', FeedSub::schemaDef());
316         $schema->ensureTable('hubsub', HubSub::schemaDef());
317         return true;
318     }
319
320     function onEndShowStatusNetStyles($action) {
321         $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
322         return true;
323     }
324
325     function onEndShowStatusNetScripts($action) {
326         $action->script(common_path('plugins/OStatus/js/ostatus.js'));
327         return true;
328     }
329
330     /**
331      * Override the "from ostatus" bit in notice lists to link to the
332      * original post and show the domain it came from.
333      *
334      * @param Notice in $notice
335      * @param string out &$name
336      * @param string out &$url
337      * @param string out &$title
338      * @return mixed hook return code
339      */
340     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
341     {
342         if ($notice->source == 'ostatus') {
343             $bits = parse_url($notice->uri);
344             $domain = $bits['host'];
345
346             $name = $domain;
347             $url = $notice->uri;
348             $title = sprintf(_m("Sent from %s via OStatus"), $domain);
349             return false;
350         }
351     }
352
353     /**
354      * Send incoming PuSH feeds for OStatus endpoints in for processing.
355      *
356      * @param FeedSub $feedsub
357      * @param DOMDocument $feed
358      * @return mixed hook return code
359      */
360     function onStartFeedSubReceive($feedsub, $feed)
361     {
362         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
363         if ($oprofile) {
364             $oprofile->processFeed($feed);
365         } else {
366             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
367         }
368     }
369
370     function onEndSubscribe($subscriber, $other)
371     {
372         $user = User::staticGet('id', $subscriber->id);
373
374         if (empty($user)) {
375             return true;
376         }
377
378         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
379
380         if (empty($oprofile)) {
381             return true;
382         }
383
384         $act = new Activity();
385
386         $act->verb = ActivityVerb::FOLLOW;
387
388         $act->id   = TagURI::mint('follow:%d:%d:%s',
389                                   $subscriber->id,
390                                   $other->id,
391                                   common_date_iso8601(time()));
392
393         $act->time    = time();
394         $act->title   = _("Follow");
395         $act->content = sprintf(_("%s is now following %s."),
396                                $subscriber->getBestName(),
397                                $other->getBestName());
398
399         $act->actor   = ActivityObject::fromProfile($subscriber);
400         $act->object  = ActivityObject::fromProfile($other);
401
402         $oprofile->notifyActivity($act);
403
404         return true;
405     }
406
407     /**
408      * Notify remote users when their notices get favorited.
409      *
410      * @param Profile or User $profile of local user doing the faving
411      * @param Notice $notice being favored
412      * @return hook return value
413      */
414
415     function onEndFavorNotice(Profile $profile, Notice $notice)
416     {
417         $user = User::staticGet('id', $profile->id);
418
419         if (empty($user)) {
420             return true;
421         }
422
423         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
424
425         if (empty($oprofile)) {
426             return true;
427         }
428
429         $act = new Activity();
430
431         $act->verb = ActivityVerb::FAVORITE;
432         $act->id   = TagURI::mint('favor:%d:%d:%s',
433                                   $profile->id,
434                                   $notice->id,
435                                   common_date_iso8601(time()));
436
437         $act->time    = time();
438         $act->title   = _("Favor");
439         $act->content = sprintf(_("%s marked notice %s as a favorite."),
440                                $profile->getBestName(),
441                                $notice->uri);
442
443         $act->actor   = ActivityObject::fromProfile($profile);
444         $act->object  = ActivityObject::fromNotice($notice);
445
446         $oprofile->notifyActivity($act);
447
448         return true;
449     }
450
451     /**
452      * Notify remote users when their notices get de-favorited.
453      *
454      * @param Profile $profile Profile person doing the de-faving
455      * @param Notice  $notice  Notice being favored
456      *
457      * @return hook return value
458      */
459
460     function onEndDisfavorNotice(Profile $profile, Notice $notice)
461     {
462         $user = User::staticGet('id', $profile->id);
463
464         if (empty($user)) {
465             return true;
466         }
467
468         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
469
470         if (empty($oprofile)) {
471             return true;
472         }
473
474         $act = new Activity();
475
476         $act->verb = ActivityVerb::UNFAVORITE;
477         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
478                                   $profile->id,
479                                   $notice->id,
480                                   common_date_iso8601(time()));
481         $act->time    = time();
482         $act->title   = _("Disfavor");
483         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
484                                $profile->getBestName(),
485                                $notice->uri);
486
487         $act->actor   = ActivityObject::fromProfile($profile);
488         $act->object  = ActivityObject::fromNotice($notice);
489
490         $oprofile->notifyActivity($act);
491
492         return true;
493     }
494 }