]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[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      * Automatically load the actions and libraries used by the plugin
141      *
142      * @param Class $cls the class
143      *
144      * @return boolean hook return
145      *
146      */
147     function onAutoload($cls)
148     {
149         $base = dirname(__FILE__);
150         $lower = strtolower($cls);
151         $map = array('activityverb' => 'activity',
152                      'activityobject' => 'activity',
153                      'activityutils' => 'activity');
154         if (isset($map[$lower])) {
155             $lower = $map[$lower];
156         }
157         $files = array("$base/classes/$cls.php",
158                        "$base/lib/$lower.php");
159         if (substr($lower, -6) == 'action') {
160             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
161         }
162         foreach ($files as $file) {
163             if (file_exists($file)) {
164                 include_once $file;
165                 return false;
166             }
167         }
168         return true;
169     }
170
171     /**
172      * Add in an OStatus subscribe button
173      */
174     function onStartProfileRemoteSubscribe($output, $profile)
175     {
176         $cur = common_current_user();
177
178         if (empty($cur)) {
179             // Add an OStatus subscribe
180             $output->elementStart('li', 'entity_subscribe');
181             $url = common_local_url('ostatusinit',
182                                     array('nickname' => $profile->nickname));
183             $output->element('a', array('href' => $url,
184                                         'class' => 'entity_remote_subscribe'),
185                                 _m('Subscribe'));
186
187             $output->elementEnd('li');
188         }
189
190         return false;
191     }
192
193     /**
194      * Check if we've got remote replies to send via Salmon.
195      *
196      * @fixme push webfinger lookup & sending to a background queue
197      * @fixme also detect short-form name for remote subscribees where not ambiguous
198      */
199
200     function onEndNoticeSave($notice)
201     {
202         $mentioned = $notice->getReplies();
203
204         foreach ($mentioned as $profile) {
205
206             $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
207
208             if (!empty($oprofile) && !empty($oprofile->salmonuri)) {
209
210                 // FIXME: this needs to go out in a queue handler
211
212                 $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
213                 $xml .= $notice->asAtomEntry();
214
215                 $salmon = new Salmon();
216                 $salmon->post($oprofile->salmonuri, $xml);
217             }
218         }
219     }
220
221     /**
222      *
223      */
224
225     function onEndFindMentions($sender, $text, &$mentions)
226     {
227         preg_match_all('/(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)/',
228                        $text,
229                        $wmatches,
230                        PREG_OFFSET_CAPTURE);
231
232         foreach ($wmatches[1] as $wmatch) {
233
234             $webfinger = $wmatch[0];
235
236             $oprofile = Ostatus_profile::ensureWebfinger($webfinger);
237
238             if (!empty($oprofile)) {
239
240                 $profile = $oprofile->localProfile();
241
242                 $mentions[] = array('mentioned' => array($profile),
243                                     'text' => $wmatch[0],
244                                     'position' => $wmatch[1],
245                                     'url' => $profile->profileurl);
246             }
247         }
248
249         return true;
250     }
251
252     /**
253      * Notify remote server and garbage collect unused feeds on unsubscribe.
254      * @fixme send these operations to background queues
255      *
256      * @param User $user
257      * @param Profile $other
258      * @return hook return value
259      */
260     function onEndUnsubscribe($profile, $other)
261     {
262         $user = User::staticGet('id', $profile->id);
263
264         if (empty($user)) {
265             return true;
266         }
267
268         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
269
270         if (empty($oprofile)) {
271             return true;
272         }
273
274         // Drop the PuSH subscription if there are no other subscribers.
275
276         if ($other->subscriberCount() == 0) {
277             common_log(LOG_INFO, "Unsubscribing from now-unused feed $oprofile->feeduri");
278             $oprofile->unsubscribe();
279         }
280
281         $act = new Activity();
282
283         $act->verb = ActivityVerb::UNFOLLOW;
284
285         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
286                                   $profile->id,
287                                   $other->id,
288                                   common_date_iso8601(time()));
289
290         $act->time    = time();
291         $act->title   = _("Unfollow");
292         $act->content = sprintf(_("%s stopped following %s."),
293                                $profile->getBestName(),
294                                $other->getBestName());
295
296         $act->actor   = ActivityObject::fromProfile($profile);
297         $act->object  = ActivityObject::fromProfile($other);
298
299         $oprofile->notifyActivity($act);
300
301         return true;
302     }
303
304     /**
305      * Make sure necessary tables are filled out.
306      */
307     function onCheckSchema() {
308         $schema = Schema::get();
309         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
310         $schema->ensureTable('feedsub', FeedSub::schemaDef());
311         $schema->ensureTable('hubsub', HubSub::schemaDef());
312         return true;
313     }
314
315     function onEndShowStatusNetStyles($action) {
316         $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
317         return true;
318     }
319
320     function onEndShowStatusNetScripts($action) {
321         $action->script(common_path('plugins/OStatus/js/ostatus.js'));
322         return true;
323     }
324
325     /**
326      * Override the "from ostatus" bit in notice lists to link to the
327      * original post and show the domain it came from.
328      *
329      * @param Notice in $notice
330      * @param string out &$name
331      * @param string out &$url
332      * @param string out &$title
333      * @return mixed hook return code
334      */
335     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
336     {
337         if ($notice->source == 'ostatus') {
338             $bits = parse_url($notice->uri);
339             $domain = $bits['host'];
340
341             $name = $domain;
342             $url = $notice->uri;
343             $title = sprintf(_m("Sent from %s via OStatus"), $domain);
344             return false;
345         }
346     }
347
348     /**
349      * Send incoming PuSH feeds for OStatus endpoints in for processing.
350      *
351      * @param FeedSub $feedsub
352      * @param DOMDocument $feed
353      * @return mixed hook return code
354      */
355     function onStartFeedSubReceive($feedsub, $feed)
356     {
357         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
358         if ($oprofile) {
359             $oprofile->processFeed($feed);
360         } else {
361             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
362         }
363     }
364
365     function onEndSubscribe($subscriber, $other)
366     {
367         $user = User::staticGet('id', $subscriber->id);
368
369         if (empty($user)) {
370             return true;
371         }
372
373         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
374
375         if (empty($oprofile)) {
376             return true;
377         }
378
379         $act = new Activity();
380
381         $act->verb = ActivityVerb::FOLLOW;
382
383         $act->id   = TagURI::mint('follow:%d:%d:%s',
384                                   $subscriber->id,
385                                   $other->id,
386                                   common_date_iso8601(time()));
387
388         $act->time    = time();
389         $act->title   = _("Follow");
390         $act->content = sprintf(_("%s is now following %s."),
391                                $subscriber->getBestName(),
392                                $other->getBestName());
393
394         $act->actor   = ActivityObject::fromProfile($subscriber);
395         $act->object  = ActivityObject::fromProfile($other);
396
397         $oprofile->notifyActivity($act);
398
399         return true;
400     }
401
402     /**
403      * Notify remote users when their notices get favorited.
404      *
405      * @param Profile or User $profile of local user doing the faving
406      * @param Notice $notice being favored
407      * @return hook return value
408      */
409
410     function onEndFavorNotice(Profile $profile, Notice $notice)
411     {
412         $user = User::staticGet('id', $profile->id);
413
414         if (empty($user)) {
415             return true;
416         }
417
418         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
419
420         if (empty($oprofile)) {
421             return true;
422         }
423
424         $act = new Activity();
425
426         $act->verb = ActivityVerb::FAVORITE;
427         $act->id   = TagURI::mint('favor:%d:%d:%s',
428                                   $profile->id,
429                                   $notice->id,
430                                   common_date_iso8601(time()));
431
432         $act->time    = time();
433         $act->title   = _("Favor");
434         $act->content = sprintf(_("%s marked notice %s as a favorite."),
435                                $profile->getBestName(),
436                                $notice->uri);
437
438         $act->actor   = ActivityObject::fromProfile($profile);
439         $act->object  = ActivityObject::fromNotice($notice);
440
441         $oprofile->notifyActivity($act);
442
443         return true;
444     }
445
446     /**
447      * Notify remote users when their notices get de-favorited.
448      *
449      * @param Profile $profile Profile person doing the de-faving
450      * @param Notice  $notice  Notice being favored
451      *
452      * @return hook return value
453      */
454
455     function onEndDisfavorNotice(Profile $profile, Notice $notice)
456     {
457         $user = User::staticGet('id', $profile->id);
458
459         if (empty($user)) {
460             return true;
461         }
462
463         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
464
465         if (empty($oprofile)) {
466             return true;
467         }
468
469         $act = new Activity();
470
471         $act->verb = ActivityVerb::UNFAVORITE;
472         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
473                                   $profile->id,
474                                   $notice->id,
475                                   common_date_iso8601(time()));
476         $act->time    = time();
477         $act->title   = _("Disfavor");
478         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
479                                $profile->getBestName(),
480                                $notice->uri);
481
482         $act->actor   = ActivityObject::fromProfile($profile);
483         $act->object  = ActivityObject::fromNotice($notice);
484
485         $oprofile->notifyActivity($act);
486
487         return true;
488     }
489 }