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