]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Mastodon replies 201 Created for salmon slaps.
[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  * OStatusPlugin implementation for GNU Social
22  *
23  * Depends on: WebFinger plugin
24  *
25  * @package OStatusPlugin
26  * @maintainer Brion Vibber <brion@status.net>
27  */
28
29 if (!defined('GNUSOCIAL')) { exit(1); }
30
31 class OStatusPlugin extends Plugin
32 {
33     /**
34      * Hook for RouterInitialized event.
35      *
36      * @param URLMapper $m path-to-action mapper
37      * @return boolean hook return
38      */
39     public function onRouterInitialized(URLMapper $m)
40     {
41         // Discovery actions
42         $m->connect('main/ostatustag',
43                     array('action' => 'ostatustag'));
44         $m->connect('main/ostatustag?nickname=:nickname',
45                     array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
46         $m->connect('main/ostatus/nickname/:nickname',
47                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
48         $m->connect('main/ostatus/group/:group',
49                   array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
50         $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
51                   array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
52                                                           'peopletag' => '[A-Za-z0-9_-]+'));
53         $m->connect('main/ostatus',
54                     array('action' => 'ostatusinit'));
55
56         // Remote subscription actions
57         $m->connect('main/ostatussub',
58                     array('action' => 'ostatussub'));
59         $m->connect('main/ostatusgroup',
60                     array('action' => 'ostatusgroup'));
61         $m->connect('main/ostatuspeopletag',
62                     array('action' => 'ostatuspeopletag'));
63
64         // WebSub actions
65         $m->connect('main/push/hub', array('action' => 'pushhub'));
66
67         $m->connect('main/push/callback/:feed',
68                     array('action' => 'pushcallback'),
69                     array('feed' => '[0-9]+'));
70
71         // Salmon endpoint
72         $m->connect('main/salmon/user/:id',
73                     array('action' => 'usersalmon'),
74                     array('id' => '[0-9]+'));
75         $m->connect('main/salmon/group/:id',
76                     array('action' => 'groupsalmon'),
77                     array('id' => '[0-9]+'));
78         $m->connect('main/salmon/peopletag/:id',
79                     array('action' => 'peopletagsalmon'),
80                     array('id' => '[0-9]+'));
81         return true;
82     }
83
84     /**
85      * Set up queue handlers for outgoing hub pushes
86      * @param QueueManager $qm
87      * @return boolean hook return
88      */
89     function onEndInitializeQueueManager(QueueManager $qm)
90     {
91         // Prepare outgoing distributions after notice save.
92         $qm->connect('ostatus', 'OStatusQueueHandler');
93
94         // Outgoing from our internal WebSub hub
95         $qm->connect('hubconf', 'HubConfQueueHandler');
96         $qm->connect('hubprep', 'HubPrepQueueHandler');
97
98         $qm->connect('hubout', 'HubOutQueueHandler');
99
100         // Outgoing Salmon replies (when we don't need a return value)
101         $qm->connect('salmon', 'SalmonQueueHandler');
102
103         // Incoming from a foreign WebSub hub
104         $qm->connect('pushin', 'PushInQueueHandler');
105
106         // Re-subscribe feeds that need renewal
107         $qm->connect('pushrenew', 'PushRenewQueueHandler');
108         return true;
109     }
110
111     /**
112      * Put saved notices into the queue for pubsub distribution.
113      */
114     function onStartEnqueueNotice($notice, &$transports)
115     {
116         if ($notice->inScope(null) && $notice->getProfile()->hasRight(Right::PUBLICNOTICE)) {
117             // put our transport first, in case there's any conflict (like OMB)
118             array_unshift($transports, 'ostatus');
119             $this->log(LOG_INFO, "OSTATUS [{$notice->getID()}]: queued for OStatus processing");
120         } else {
121             // FIXME: we don't do privacy-controlled OStatus updates yet.
122             // once that happens, finer grain of control here.
123             $this->log(LOG_NOTICE, "OSTATUS [{$notice->getID()}]: Not queueing because of privacy; scope = {$notice->scope}");
124         }
125         return true;
126     }
127
128     /**
129      * Set up a WebSub hub link to our internal link for canonical timeline
130      * Atom feeds for users and groups.
131      */
132     function onStartApiAtom($feed)
133     {
134         $id = null;
135
136         if ($feed instanceof AtomUserNoticeFeed) {
137             $salmonAction = 'usersalmon';
138             $user = $feed->getUser();
139             $id   = $user->id;
140             $profile = $user->getProfile();
141         } else if ($feed instanceof AtomGroupNoticeFeed) {
142             $salmonAction = 'groupsalmon';
143             $group = $feed->getGroup();
144             $id = $group->id;
145         } else if ($feed instanceof AtomListNoticeFeed) {
146             $salmonAction = 'peopletagsalmon';
147             $peopletag = $feed->getList();
148             $id = $peopletag->id;
149         } else {
150             return true;
151         }
152
153         if (!empty($id)) {
154             $hub = common_config('ostatus', 'hub');
155             if (empty($hub)) {
156                 // Updates will be handled through our internal WebSub hub.
157                 $hub = common_local_url('pushhub');
158             }
159             $feed->addLink($hub, array('rel' => 'hub'));
160
161             // Also, we'll add in the salmon link
162             $salmon = common_local_url($salmonAction, array('id' => $id));
163             $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
164
165             // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
166             $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
167             $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
168         }
169
170         return true;
171     }
172
173     /**
174      * Add in an OStatus subscribe button
175      */
176     function onStartProfileRemoteSubscribe($output, $profile)
177     {
178         $this->onStartProfileListItemActionElements($output, $profile);
179         return false;
180     }
181
182     function onStartGroupSubscribe($widget, $group)
183     {
184         $cur = common_current_user();
185
186         if (empty($cur)) {
187             $widget->out->elementStart('li', 'entity_subscribe');
188
189             $url = common_local_url('ostatusinit',
190                                     array('group' => $group->nickname));
191             $widget->out->element('a', array('href' => $url,
192                                              'class' => 'entity_remote_subscribe'),
193                                 // TRANS: Link to subscribe to a remote entity.
194                                 _m('Subscribe'));
195
196             $widget->out->elementEnd('li');
197             return false;
198         }
199
200         return true;
201     }
202
203     function onStartSubscribePeopletagForm($output, $peopletag)
204     {
205         $cur = common_current_user();
206
207         if (empty($cur)) {
208             $output->elementStart('li', 'entity_subscribe');
209             $profile = $peopletag->getTagger();
210             $url = common_local_url('ostatusinit',
211                                     array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
212             $output->element('a', array('href' => $url,
213                                         'class' => 'entity_remote_subscribe'),
214                                 // TRANS: Link to subscribe to a remote entity.
215                                 _m('Subscribe'));
216
217             $output->elementEnd('li');
218             return false;
219         }
220
221         return true;
222     }
223
224     /*
225      * If the field being looked for is URI look for the profile
226      */
227     function onStartProfileCompletionSearch($action, $profile, $search_engine) {
228         if ($action->field == 'uri') {
229             $profile->joinAdd(array('id', 'user:id'));
230             $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
231             $profile->query();
232
233             $validate = new Validate();
234
235             if ($profile->N == 0) {
236                 try {
237                     if ($validate->email($q)) {
238                         $oprofile = Ostatus_profile::ensureWebfinger($q);
239                     } else if ($validate->uri($q)) {
240                         $oprofile = Ostatus_profile::ensureProfileURL($q);
241                     } else {
242                         // TRANS: Exception in OStatus when invalid URI was entered.
243                         throw new Exception(_m('Invalid URI.'));
244                     }
245                     return $this->filter(array($oprofile->localProfile()));
246
247                 } catch (Exception $e) {
248                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
249                 // TRANS: and example.net, as these are official standard domain names for use in examples.
250                     $this->msg = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
251                     return array();
252                 }
253             }
254             return false;
255         }
256         return true;
257     }
258
259     /**
260      * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
261      *
262      * @return  array   The matching IDs (without @ or acct:) and each respective position in the given string.
263      */
264     static function extractWebfingerIds($text)
265     {
266         $wmatches = array();
267         // Maybe this should harmonize with lib/nickname.php and Nickname::WEBFINGER_FMT
268         $result = preg_match_all('/(?<!\S)@((?:\w+[\w\-\_\.]*)?\w+@'.URL_REGEX_DOMAIN_NAME.')/',
269                        $text,
270                        $wmatches,
271                        PREG_OFFSET_CAPTURE);
272         if ($result === false) {
273             common_log(LOG_ERR, __METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error=='.preg_last_error().').');
274         } elseif (count($wmatches)) {
275             common_debug(sprintf('Found %d matches for WebFinger IDs: %s', count($wmatches), _ve($wmatches)));
276         }
277         return $wmatches[1];
278     }
279
280     /**
281      * Profile URL matches: @example.com/mublog/user
282      *
283      * @return  array   The matching URLs (without @ or acct:) and each respective position in the given string.
284      */
285     static function extractUrlMentions($text)
286     {
287         $wmatches = array();
288         // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
289         // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
290         $result = preg_match_all('/(?:^|\s+)@('.URL_REGEX_DOMAIN_NAME.'(?:\/['.URL_REGEX_VALID_PATH_CHARS.']*)*)/',
291                        $text,
292                        $wmatches,
293                        PREG_OFFSET_CAPTURE);
294         if ($result === false) {
295             common_log(LOG_ERR, __METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error=='.preg_last_error().').');
296         } elseif (count($wmatches)) {
297             common_debug(sprintf('Found %d matches for profile URL mentions: %s', count($wmatches), _ve($wmatches)));
298         }
299         return $wmatches[1];
300     }
301
302     /**
303      * Find any explicit remote mentions. Accepted forms:
304      *   Webfinger: @user@example.com
305      *   Profile link: @example.com/mublog/user
306      * @param Profile $sender
307      * @param string $text input markup text
308      * @param array &$mention in/out param: set of found mentions
309      * @return boolean hook return value
310      */
311     function onEndFindMentions(Profile $sender, $text, &$mentions)
312     {
313         $matches = array();
314
315         foreach (self::extractWebfingerIds($text) as $wmatch) {
316             list($target, $pos) = $wmatch;
317             $this->log(LOG_INFO, "Checking webfinger '$target'");
318             $profile = null;
319             try {
320                 $oprofile = Ostatus_profile::ensureWebfinger($target);
321                 if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
322                     continue;
323                 }
324                 $profile = $oprofile->localProfile();
325             } catch (OStatusShadowException $e) {
326                 // This means we got a local user in the webfinger lookup
327                 $profile = $e->profile;
328             } catch (Exception $e) {
329                 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
330                 continue;
331             }
332
333             assert($profile instanceof Profile);
334
335             $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
336                     ? $profile->getNickname()   // TODO: we could do getBestName() or getFullname() here
337                     : $target;
338             $url = $profile->getUri();
339             if (!common_valid_http_url($url)) {
340                 $url = $profile->getUrl();
341             }
342             $matches[$pos] = array('mentioned' => array($profile),
343                                    'type' => 'mention',
344                                    'text' => $text,
345                                    'position' => $pos,
346                                    'length' => mb_strlen($target),
347                                    'url' => $url);
348         }
349
350         foreach (self::extractUrlMentions($text) as $wmatch) {
351             list($target, $pos) = $wmatch;
352             $schemes = array('https', 'http');
353             foreach ($schemes as $scheme) {
354                 $url = "$scheme://$target";
355                 $this->log(LOG_INFO, "Checking profile address '$url'");
356                 try {
357                     $oprofile = Ostatus_profile::ensureProfileURL($url);
358                     if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
359                         $profile = $oprofile->localProfile();
360                         $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
361                                 $profile->nickname : $target;
362                         $matches[$pos] = array('mentioned' => array($profile),
363                                                'type' => 'mention',
364                                                'text' => $text,
365                                                'position' => $pos,
366                                                'length' => mb_strlen($target),
367                                                'url' => $profile->getUrl());
368                         break;
369                     }
370                 } catch (Exception $e) {
371                     $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
372                 }
373             }
374         }
375
376         foreach ($mentions as $i => $other) {
377             // If we share a common prefix with a local user, override it!
378             $pos = $other['position'];
379             if (isset($matches[$pos])) {
380                 $mentions[$i] = $matches[$pos];
381                 unset($matches[$pos]);
382             }
383         }
384         foreach ($matches as $mention) {
385             $mentions[] = $mention;
386         }
387
388         return true;
389     }
390
391     /**
392      * Allow remote profile references to be used in commands:
393      *   sub update@status.net
394      *   whois evan@identi.ca
395      *   reply http://identi.ca/evan hey what's up
396      *
397      * @param Command $command
398      * @param string $arg
399      * @param Profile &$profile
400      * @return hook return code
401      */
402     function onStartCommandGetProfile($command, $arg, &$profile)
403     {
404         $oprofile = $this->pullRemoteProfile($arg);
405         if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
406             try {
407                 $profile = $oprofile->localProfile();
408             } catch (NoProfileException $e) {
409                 // No locally stored profile found for remote profile
410                 return true;
411             }
412             return false;
413         } else {
414             return true;
415         }
416     }
417
418     /**
419      * Allow remote group references to be used in commands:
420      *   join group+statusnet@identi.ca
421      *   join http://identi.ca/group/statusnet
422      *   drop identi.ca/group/statusnet
423      *
424      * @param Command $command
425      * @param string $arg
426      * @param User_group &$group
427      * @return hook return code
428      */
429     function onStartCommandGetGroup($command, $arg, &$group)
430     {
431         $oprofile = $this->pullRemoteProfile($arg);
432         if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
433             $group = $oprofile->localGroup();
434             return false;
435         } else {
436             return true;
437         }
438     }
439
440     protected function pullRemoteProfile($arg)
441     {
442         $oprofile = null;
443         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
444             // webfinger lookup
445             try {
446                 return Ostatus_profile::ensureWebfinger($arg);
447             } catch (Exception $e) {
448                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
449                                     $arg . ': ' . $e->getMessage());
450             }
451         }
452
453         // Look for profile URLs, with or without scheme:
454         $urls = array();
455         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
456             $urls[] = $arg;
457         }
458         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
459             $schemes = array('http', 'https');
460             foreach ($schemes as $scheme) {
461                 $urls[] = "$scheme://$arg";
462             }
463         }
464
465         foreach ($urls as $url) {
466             try {
467                 return Ostatus_profile::ensureProfileURL($url);
468             } catch (Exception $e) {
469                 common_log(LOG_ERR, 'Profile lookup failed for ' .
470                                     $arg . ': ' . $e->getMessage());
471             }
472         }
473         return null;
474     }
475
476     function onEndProfileSettingsActions($out) {
477         $siteName = common_config('site', 'name');
478         $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('ostatussub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
479         $out->elementStart('li');
480         $out->element('a',
481                       array('href' => 'javascript:'.$js),
482                       // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
483                       _('Add to Firefox as feedreader'));
484         $out->elementEnd('li');
485     }
486
487     /**
488      * Make sure necessary tables are filled out.
489      */
490     function onCheckSchema() {
491         $schema = Schema::get();
492         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
493         $schema->ensureTable('feedsub', FeedSub::schemaDef());
494         $schema->ensureTable('hubsub', HubSub::schemaDef());
495         $schema->ensureTable('magicsig', Magicsig::schemaDef());
496         return true;
497     }
498
499     public function onEndShowStylesheets(Action $action) {
500         $action->cssLink($this->path('theme/base/css/ostatus.css'));
501         return true;
502     }
503
504     function onEndShowStatusNetScripts($action) {
505         $action->script($this->path('js/ostatus.js'));
506         return true;
507     }
508
509     /**
510      * Override the "from ostatus" bit in notice lists to link to the
511      * original post and show the domain it came from.
512      *
513      * @param Notice in $notice
514      * @param string out &$name
515      * @param string out &$url
516      * @param string out &$title
517      * @return mixed hook return code
518      */
519     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
520     {
521         // If we don't handle this, keep the event handler going
522         if (!in_array($notice->source, array('ostatus', 'share'))) {
523             return true;
524         }
525
526         try {
527             $url = $notice->getUrl();
528             // If getUrl() throws exception, $url is never set
529             
530             $bits = parse_url($url);
531             $domain = $bits['host'];
532             if (substr($domain, 0, 4) == 'www.') {
533                 $name = substr($domain, 4);
534             } else {
535                 $name = $domain;
536             }
537
538             // TRANS: Title. %s is a domain name.
539             $title = sprintf(_m('Sent from %s via OStatus'), $domain);
540
541             // Abort event handler, we have a name and URL!
542             return false;
543         } catch (InvalidUrlException $e) {
544             // This just means we don't have the notice source data
545             return true;
546         }
547     }
548
549     /**
550      * Send incoming WebSub feeds for OStatus endpoints in for processing.
551      *
552      * @param FeedSub $feedsub
553      * @param DOMDocument $feed
554      * @return mixed hook return code
555      */
556     function onStartFeedSubReceive($feedsub, $feed)
557     {
558         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
559         if ($oprofile instanceof Ostatus_profile) {
560             $oprofile->processFeed($feed, 'push');
561         } else {
562             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
563         }
564     }
565
566     /**
567      * Tell the FeedSub infrastructure whether we have any active OStatus
568      * usage for the feed; if not it'll be able to garbage-collect the
569      * feed subscription.
570      *
571      * @param FeedSub $feedsub
572      * @param integer $count in/out
573      * @return mixed hook return code
574      */
575     function onFeedSubSubscriberCount($feedsub, &$count)
576     {
577         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
578         if ($oprofile instanceof Ostatus_profile) {
579             $count += $oprofile->subscriberCount();
580         }
581         return true;
582     }
583
584     /**
585      * When about to subscribe to a remote user, start a server-to-server
586      * WebSub subscription if needed. If we can't establish that, abort.
587      *
588      * @fixme If something else aborts later, we could end up with a stray
589      *        WebSub subscription. This is relatively harmless, though.
590      *
591      * @param Profile $profile  subscriber
592      * @param Profile $other    subscribee
593      *
594      * @return hook return code
595      *
596      * @throws Exception
597      */
598     function onStartSubscribe(Profile $profile, Profile $other)
599     {
600         if (!$profile->isLocal()) {
601             return true;
602         }
603
604         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
605         if (!$oprofile instanceof Ostatus_profile) {
606             return true;
607         }
608
609         $oprofile->subscribe();
610     }
611
612     /**
613      * Having established a remote subscription, send a notification to the
614      * remote OStatus profile's endpoint.
615      *
616      * @param Profile $profile  subscriber
617      * @param Profile $other    subscribee
618      *
619      * @return hook return code
620      *
621      * @throws Exception
622      */
623     function onEndSubscribe(Profile $profile, Profile $other)
624     {
625         if (!$profile->isLocal()) {
626             return true;
627         }
628
629         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
630         if (!$oprofile instanceof Ostatus_profile) {
631             return true;
632         }
633
634         $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
635                                            'subscribed' => $other->id));
636
637         $act = $sub->asActivity();
638
639         $oprofile->notifyActivity($act, $profile);
640
641         return true;
642     }
643
644     /**
645      * Notify remote server and garbage collect unused feeds on unsubscribe.
646      * @todo FIXME: Send these operations to background queues
647      *
648      * @param User $user
649      * @param Profile $other
650      * @return hook return value
651      */
652     function onEndUnsubscribe(Profile $profile, Profile $other)
653     {
654         if (!$profile->isLocal()) {
655             return true;
656         }
657
658         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
659         if (!$oprofile instanceof Ostatus_profile) {
660             return true;
661         }
662
663         // Drop the WebSub subscription if there are no other subscribers.
664         $oprofile->garbageCollect();
665
666         $act = new Activity();
667
668         $act->verb = ActivityVerb::UNFOLLOW;
669
670         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
671                                   $profile->id,
672                                   $other->id,
673                                   common_date_iso8601(time()));
674
675         $act->time    = time();
676         // TRANS: Title for unfollowing a remote profile.
677         $act->title   = _m('TITLE','Unfollow');
678         // TRANS: Success message for unsubscribe from user attempt through OStatus.
679         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
680         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
681                                $profile->getBestName(),
682                                $other->getBestName());
683
684         $act->actor   = $profile->asActivityObject();
685         $act->objects[] = $other->asActivityObject();
686
687         $oprofile->notifyActivity($act, $profile);
688
689         return true;
690     }
691
692     /**
693      * When one of our local users tries to join a remote group,
694      * notify the remote server. If the notification is rejected,
695      * deny the join.
696      *
697      * @param User_group $group
698      * @param Profile    $profile
699      *
700      * @return mixed hook return value
701      * @throws Exception of various kinds, some from $oprofile->subscribe();
702      */
703     function onStartJoinGroup($group, $profile)
704     {
705         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
706         if (!$oprofile instanceof Ostatus_profile) {
707             return true;
708         }
709
710         $oprofile->subscribe();
711
712         // NOTE: we don't use Group_member::asActivity() since that record
713         // has not yet been created.
714
715         $act = new Activity();
716         $act->id = TagURI::mint('join:%d:%d:%s',
717                                 $profile->id,
718                                 $group->id,
719                                 common_date_iso8601(time()));
720
721         $act->actor = $profile->asActivityObject();
722         $act->verb = ActivityVerb::JOIN;
723         $act->objects[] = $oprofile->asActivityObject();
724
725         $act->time = time();
726         // TRANS: Title for joining a remote groep.
727         $act->title = _m('TITLE','Join');
728         // TRANS: Success message for subscribe to group attempt through OStatus.
729         // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
730         $act->content = sprintf(_m('%1$s has joined group %2$s.'),
731                                 $profile->getBestName(),
732                                 $oprofile->getBestName());
733
734         if ($oprofile->notifyActivity($act, $profile)) {
735             return true;
736         } else {
737             $oprofile->garbageCollect();
738             // TRANS: Exception thrown when joining a remote group fails.
739             throw new Exception(_m('Failed joining remote group.'));
740         }
741     }
742
743     /**
744      * When one of our local users leaves a remote group, notify the remote
745      * server.
746      *
747      * @fixme Might be good to schedule a resend of the leave notification
748      * if it failed due to a transitory error. We've canceled the local
749      * membership already anyway, but if the remote server comes back up
750      * it'll be left with a stray membership record.
751      *
752      * @param User_group $group
753      * @param Profile $profile
754      *
755      * @return mixed hook return value
756      */
757     function onEndLeaveGroup($group, $profile)
758     {
759         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
760         if (!$oprofile instanceof Ostatus_profile) {
761             return true;
762         }
763
764         // Drop the WebSub subscription if there are no other subscribers.
765         $oprofile->garbageCollect();
766
767         $member = $profile;
768
769         $act = new Activity();
770         $act->id = TagURI::mint('leave:%d:%d:%s',
771                                 $member->id,
772                                 $group->id,
773                                 common_date_iso8601(time()));
774
775         $act->actor = $member->asActivityObject();
776         $act->verb = ActivityVerb::LEAVE;
777         $act->objects[] = $oprofile->asActivityObject();
778
779         $act->time = time();
780         // TRANS: Title for leaving a remote group.
781         $act->title = _m('TITLE','Leave');
782         // TRANS: Success message for unsubscribe from group attempt through OStatus.
783         // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
784         $act->content = sprintf(_m('%1$s has left group %2$s.'),
785                                 $member->getBestName(),
786                                 $oprofile->getBestName());
787
788         $oprofile->notifyActivity($act, $member);
789     }
790
791     /**
792      * When one of our local users tries to subscribe to a remote peopletag,
793      * notify the remote server. If the notification is rejected,
794      * deny the subscription.
795      *
796      * @param Profile_list $peopletag
797      * @param User         $user
798      *
799      * @return mixed hook return value
800      * @throws Exception of various kinds, some from $oprofile->subscribe();
801      */
802
803     function onStartSubscribePeopletag($peopletag, $user)
804     {
805         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
806         if (!$oprofile instanceof Ostatus_profile) {
807             return true;
808         }
809
810         $oprofile->subscribe();
811
812         $sub = $user->getProfile();
813         $tagger = Profile::getKV($peopletag->tagger);
814
815         $act = new Activity();
816         $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
817                                 $sub->id,
818                                 $peopletag->id,
819                                 common_date_iso8601(time()));
820
821         $act->actor = $sub->asActivityObject();
822         $act->verb = ActivityVerb::FOLLOW;
823         $act->objects[] = $oprofile->asActivityObject();
824
825         $act->time = time();
826         // TRANS: Title for following a remote list.
827         $act->title = _m('TITLE','Follow list');
828         // TRANS: Success message for remote list follow through OStatus.
829         // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
830         $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
831                                 $sub->getBestName(),
832                                 $oprofile->getBestName(),
833                                 $tagger->getBestName());
834
835         if ($oprofile->notifyActivity($act, $sub)) {
836             return true;
837         } else {
838             $oprofile->garbageCollect();
839             // TRANS: Exception thrown when subscription to remote list fails.
840             throw new Exception(_m('Failed subscribing to remote list.'));
841         }
842     }
843
844     /**
845      * When one of our local users unsubscribes to a remote peopletag, notify the remote
846      * server.
847      *
848      * @param Profile_list $peopletag
849      * @param User         $user
850      *
851      * @return mixed hook return value
852      */
853
854     function onEndUnsubscribePeopletag($peopletag, $user)
855     {
856         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
857         if (!$oprofile instanceof Ostatus_profile) {
858             return true;
859         }
860
861         // Drop the WebSub subscription if there are no other subscribers.
862         $oprofile->garbageCollect();
863
864         $sub = Profile::getKV($user->id);
865         $tagger = Profile::getKV($peopletag->tagger);
866
867         $act = new Activity();
868         $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
869                                 $sub->id,
870                                 $peopletag->id,
871                                 common_date_iso8601(time()));
872
873         $act->actor = $member->asActivityObject();
874         $act->verb = ActivityVerb::UNFOLLOW;
875         $act->objects[] = $oprofile->asActivityObject();
876
877         $act->time = time();
878         // TRANS: Title for unfollowing a remote list.
879         $act->title = _m('Unfollow list');
880         // TRANS: Success message for remote list unfollow through OStatus.
881         // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
882         $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
883                                 $sub->getBestName(),
884                                 $oprofile->getBestName(),
885                                 $tagger->getBestName());
886
887         $oprofile->notifyActivity($act, $user);
888     }
889
890     /**
891      * Notify remote users when their notices get favorited.
892      *
893      * @param Profile or User $profile of local user doing the faving
894      * @param Notice $notice being favored
895      * @return hook return value
896      */
897     function onEndFavorNotice(Profile $profile, Notice $notice)
898     {
899         // Only distribute local users' favor actions, remote users
900         // will have already distributed theirs.
901         if (!$profile->isLocal()) {
902             return true;
903         }
904
905         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
906         if (!$oprofile instanceof Ostatus_profile) {
907             return true;
908         }
909
910         $fav = Fave::pkeyGet(array('user_id' => $profile->id,
911                                    'notice_id' => $notice->id));
912
913         if (!$fav instanceof Fave) {
914             // That's weird.
915             // TODO: Make pkeyGet throw exception, since this is a critical failure.
916             return true;
917         }
918
919         $act = $fav->asActivity();
920
921         $oprofile->notifyActivity($act, $profile);
922
923         return true;
924     }
925
926     /**
927      * Notify remote user it has got a new people tag
928      *   - tag verb is queued
929      *   - the subscription is done immediately if not present
930      *
931      * @param Profile_tag $ptag the people tag that was created
932      * @return hook return value
933      * @throws Exception of various kinds, some from $oprofile->subscribe();
934      */
935     function onEndTagProfile($ptag)
936     {
937         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
938         if (!$oprofile instanceof Ostatus_profile) {
939             return true;
940         }
941
942         $plist = $ptag->getMeta();
943         if ($plist->private) {
944             return true;
945         }
946
947         $act = new Activity();
948
949         $tagger = $plist->getTagger();
950         $tagged = Profile::getKV('id', $ptag->tagged);
951
952         $act->verb = ActivityVerb::TAG;
953         $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
954                                   $plist->tagger, $plist->id,
955                                   common_date_iso8601(time()));
956         $act->time = time();
957         // TRANS: Title for listing a remote profile.
958         $act->title = _m('TITLE','List');
959         // TRANS: Success message for remote list addition through OStatus.
960         // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
961         $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
962                                 $tagger->getBestName(),
963                                 $tagged->getBestName(),
964                                 $plist->getBestName());
965
966         $act->actor  = $tagger->asActivityObject();
967         $act->objects = array($tagged->asActivityObject());
968         $act->target = ActivityObject::fromPeopletag($plist);
969
970         $oprofile->notifyDeferred($act, $tagger);
971
972         // initiate a WebSub subscription for the person being tagged
973         $oprofile->subscribe();
974         return true;
975     }
976
977     /**
978      * Notify remote user that a people tag has been removed
979      *   - untag verb is queued
980      *   - the subscription is undone immediately if not required
981      *     i.e garbageCollect()'d
982      *
983      * @param Profile_tag $ptag the people tag that was deleted
984      * @return hook return value
985      */
986     function onEndUntagProfile($ptag)
987     {
988         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
989         if (!$oprofile instanceof Ostatus_profile) {
990             return true;
991         }
992
993         $plist = $ptag->getMeta();
994         if ($plist->private) {
995             return true;
996         }
997
998         $act = new Activity();
999
1000         $tagger = $plist->getTagger();
1001         $tagged = Profile::getKV('id', $ptag->tagged);
1002
1003         $act->verb = ActivityVerb::UNTAG;
1004         $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
1005                                   $plist->tagger, $plist->id,
1006                                   common_date_iso8601(time()));
1007         $act->time = time();
1008         // TRANS: Title for unlisting a remote profile.
1009         $act->title = _m('TITLE','Unlist');
1010         // TRANS: Success message for remote list removal through OStatus.
1011         // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1012         $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1013                                 $tagger->getBestName(),
1014                                 $tagged->getBestName(),
1015                                 $plist->getBestName());
1016
1017         $act->actor  = $tagger->asActivityObject();
1018         $act->objects = array($tagged->asActivityObject());
1019         $act->target = ActivityObject::fromPeopletag($plist);
1020
1021         $oprofile->notifyDeferred($act, $tagger);
1022
1023         // unsubscribe to WebSub feed if no more required
1024         $oprofile->garbageCollect();
1025
1026         return true;
1027     }
1028
1029     /**
1030      * Notify remote users when their notices get de-favorited.
1031      *
1032      * @param Profile $profile Profile person doing the de-faving
1033      * @param Notice  $notice  Notice being favored
1034      *
1035      * @return hook return value
1036      */
1037     function onEndDisfavorNotice(Profile $profile, Notice $notice)
1038     {
1039         // Only distribute local users' disfavor actions, remote users
1040         // will have already distributed theirs.
1041         if (!$profile->isLocal()) {
1042             return true;
1043         }
1044
1045         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1046         if (!$oprofile instanceof Ostatus_profile) {
1047             return true;
1048         }
1049
1050         $act = new Activity();
1051
1052         $act->verb = ActivityVerb::UNFAVORITE;
1053         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
1054                                   $profile->id,
1055                                   $notice->id,
1056                                   common_date_iso8601(time()));
1057         $act->time    = time();
1058         // TRANS: Title for unliking a remote notice.
1059         $act->title   = _m('Unlike');
1060         // TRANS: Success message for remove a favorite notice through OStatus.
1061         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1062         $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1063                                $profile->getBestName(),
1064                                $notice->getUrl());
1065
1066         $act->actor   = $profile->asActivityObject();
1067         $act->objects[]  = $notice->asActivityObject();
1068
1069         $oprofile->notifyActivity($act, $profile);
1070
1071         return true;
1072     }
1073
1074     function onStartGetProfileUri($profile, &$uri)
1075     {
1076         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1077         if ($oprofile instanceof Ostatus_profile) {
1078             $uri = $oprofile->uri;
1079             return false;
1080         }
1081         return true;
1082     }
1083
1084     function onStartUserGroupHomeUrl($group, &$url)
1085     {
1086         return $this->onStartUserGroupPermalink($group, $url);
1087     }
1088
1089     function onStartUserGroupPermalink($group, &$url)
1090     {
1091         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1092         if ($oprofile instanceof Ostatus_profile) {
1093             // @fixme this should probably be in the user_group table
1094             // @fixme this uri not guaranteed to be a profile page
1095             $url = $oprofile->uri;
1096             return false;
1097         }
1098     }
1099
1100     function onStartShowSubscriptionsContent($action)
1101     {
1102         $this->showEntityRemoteSubscribe($action);
1103
1104         return true;
1105     }
1106
1107     function onStartShowUserGroupsContent($action)
1108     {
1109         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1110
1111         return true;
1112     }
1113
1114     function onEndShowSubscriptionsMiniList($action)
1115     {
1116         $this->showEntityRemoteSubscribe($action);
1117
1118         return true;
1119     }
1120
1121     function onEndShowGroupsMiniList($action)
1122     {
1123         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1124
1125         return true;
1126     }
1127
1128     function showEntityRemoteSubscribe($action, $target='ostatussub')
1129     {
1130         if (!$action->getScoped() instanceof Profile) {
1131             // early return if we're not logged in
1132             return true;
1133         }
1134
1135         if ($action->getScoped()->sameAs($action->getTarget())) {
1136             $action->elementStart('div', 'entity_actions');
1137             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1138                                              'class' => 'entity_subscribe'));
1139             $action->element('a', array('href' => common_local_url($target),
1140                                         'class' => 'entity_remote_subscribe'),
1141                                 // TRANS: Link text for link to remote subscribe.
1142                                 _m('Remote'));
1143             $action->elementEnd('p');
1144             $action->elementEnd('div');
1145         }
1146     }
1147
1148     /**
1149      * Ping remote profiles with updates to this profile.
1150      * Salmon pings are queued for background processing.
1151      */
1152     function onEndBroadcastProfile(Profile $profile)
1153     {
1154         $user = User::getKV('id', $profile->id);
1155
1156         // Find foreign accounts I'm subscribed to that support Salmon pings.
1157         //
1158         // @fixme we could run updates through the WebSub feed too,
1159         // in which case we can skip Salmon pings to folks who
1160         // are also subscribed to me.
1161         $sql = "SELECT * FROM ostatus_profile " .
1162                "WHERE profile_id IN " .
1163                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1164                "OR group_id IN " .
1165                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1166         $oprofile = new Ostatus_profile();
1167         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1168
1169         if ($oprofile->N == 0) {
1170             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1171             return true;
1172         }
1173
1174         $act = new Activity();
1175
1176         $act->verb = ActivityVerb::UPDATE_PROFILE;
1177         $act->id   = TagURI::mint('update-profile:%d:%s',
1178                                   $profile->id,
1179                                   common_date_iso8601(time()));
1180         $act->time    = time();
1181         // TRANS: Title for activity.
1182         $act->title   = _m('Profile update');
1183         // TRANS: Ping text for remote profile update through OStatus.
1184         // TRANS: %s is user that updated their profile.
1185         $act->content = sprintf(_m('%s has updated their profile page.'),
1186                                $profile->getBestName());
1187
1188         $act->actor   = $profile->asActivityObject();
1189         $act->objects[]  = $act->actor;
1190
1191         while ($oprofile->fetch()) {
1192             $oprofile->notifyDeferred($act, $profile);
1193         }
1194
1195         return true;
1196     }
1197
1198     function onEndShowAccountProfileBlock(HTMLOutputter $out, Profile $profile)
1199     {
1200         if ($profile->isLocal()) {
1201             return true;
1202         }
1203         try {
1204             $oprofile = Ostatus_profile::fromProfile($profile);
1205         } catch (NoResultException $e) {
1206             // Not a remote Ostatus_profile! Maybe some other network
1207             // that has imported a non-local user?
1208             return true;
1209         }
1210         try {
1211             $feedsub = $oprofile->getFeedSub();
1212         } catch (NoResultException $e) {
1213             // No WebSub subscription has been attempted or exists for this profile
1214             // which is the case, say for remote profiles that are only included
1215             // via mentions or repeat/share.
1216             return true;
1217         }
1218
1219         $websub_states = [
1220                 'subscribe' => _m('Pending'),
1221                 'active'    => _m('Active'),
1222                 'nohub'     => _m('Polling'),
1223                 'inactive'  => _m('Inactive'),
1224             ];
1225         $out->elementStart('dl', 'entity_tags ostatus_profile');
1226         $out->element('dt', null, _m('WebSub'));
1227         $out->element('dd', null, $websub_states[$feedsub->sub_state]);
1228         $out->elementEnd('dl');
1229     }
1230
1231     // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1232     function onStartProfileListItemActionElements($item)
1233     {
1234         if (common_logged_in()) {
1235             // only non-logged in users get to see the "remote subscribe" form
1236             return true;
1237         } elseif (!$item->getTarget()->isLocal()) {
1238             // we can (for now) only provide remote subscribe forms for local users
1239             return true;
1240         }
1241
1242         if ($item instanceof ProfileAction) {
1243             $output = $item;
1244         } elseif ($item instanceof Widget) {
1245             $output = $item->out;
1246         } else {
1247             // Bad $item class, don't know how to use this for outputting!
1248             throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1249         }
1250
1251         // Add an OStatus subscribe
1252         $output->elementStart('li', 'entity_subscribe');
1253         $url = common_local_url('ostatusinit',
1254                                 array('nickname' => $item->getTarget()->getNickname()));
1255         $output->element('a', array('href' => $url,
1256                                     'class' => 'entity_remote_subscribe'),
1257                           // TRANS: Link text for a user to subscribe to an OStatus user.
1258                          _m('Subscribe'));
1259         $output->elementEnd('li');
1260
1261         $output->elementStart('li', 'entity_tag');
1262         $url = common_local_url('ostatustag',
1263                                 array('nickname' => $item->getTarget()->getNickname()));
1264         $output->element('a', array('href' => $url,
1265                                     'class' => 'entity_remote_tag'),
1266                           // TRANS: Link text for a user to list an OStatus user.
1267                          _m('List'));
1268         $output->elementEnd('li');
1269
1270         return true;
1271     }
1272
1273     function onPluginVersion(array &$versions)
1274     {
1275         $versions[] = array('name' => 'OStatus',
1276                             'version' => GNUSOCIAL_VERSION,
1277                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1278                             'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/OStatus',
1279                             // TRANS: Plugin description.
1280                             'rawdescription' => _m('Follow people across social networks that implement '.
1281                                '<a href="http://ostatus.org/">OStatus</a>.'));
1282
1283         return true;
1284     }
1285
1286     /**
1287      * Utility function to check if the given URI is a canonical group profile
1288      * page, and if so return the ID number.
1289      *
1290      * @param string $url
1291      * @return mixed int or false
1292      */
1293     public static function localGroupFromUrl($url)
1294     {
1295         $group = User_group::getKV('uri', $url);
1296         if ($group instanceof User_group) {
1297             if ($group->isLocal()) {
1298                 return $group->id;
1299             }
1300         } else {
1301             // To find local groups which haven't had their uri fields filled out...
1302             // If the domain has changed since a subscriber got the URI, it'll
1303             // be broken.
1304             $template = common_local_url('groupbyid', array('id' => '31337'));
1305             $template = preg_quote($template, '/');
1306             $template = str_replace('31337', '(\d+)', $template);
1307             if (preg_match("/$template/", $url, $matches)) {
1308                 return intval($matches[1]);
1309             }
1310         }
1311         return false;
1312     }
1313
1314     public function onStartProfileGetAtomFeed($profile, &$feed)
1315     {
1316         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1317
1318         if (!$oprofile instanceof Ostatus_profile) {
1319             return true;
1320         }
1321
1322         $feed = $oprofile->feeduri;
1323         return false;
1324     }
1325
1326     function onStartGetProfileFromURI($uri, &$profile)
1327     {
1328         // Don't want to do Web-based discovery on our own server,
1329         // so we check locally first. This duplicates the functionality
1330         // in the Profile class, since the plugin always runs before
1331         // that local lookup, but since we return false it won't run double.
1332
1333         $user = User::getKV('uri', $uri);
1334         if ($user instanceof User) {
1335             $profile = $user->getProfile();
1336             return false;
1337         } else {
1338             $group = User_group::getKV('uri', $uri);
1339             if ($group instanceof User_group) {
1340                 $profile = $group->getProfile();
1341                 return false;
1342             }
1343         }
1344
1345         // Now, check remotely
1346         try {
1347             $oprofile = Ostatus_profile::ensureProfileURI($uri);
1348             $profile = $oprofile->localProfile();
1349             return !($profile instanceof Profile);  // localProfile won't throw exception but can return null
1350         } catch (Exception $e) {
1351             return true; // It's not an OStatus profile as far as we know, continue event handling
1352         }
1353     }
1354
1355     function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1356     {
1357         $salmon_url = null;
1358         $actor = $target->getProfile();
1359         if ($actor->isLocal()) {
1360             $profiletype = $this->profileTypeString($actor);
1361             $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $actor->getID()));
1362         } else {
1363             try {
1364                 $oprofile = Ostatus_profile::fromProfile($actor);
1365                 $salmon_url = $oprofile->salmonuri;
1366             } catch (Exception $e) {
1367                 // Even though it's not a local user, we couldn't get an Ostatus_profile?!
1368             }
1369         }
1370         // Ostatus_profile salmon URL may be empty
1371         if (!empty($salmon_url)) {
1372             $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1373         }
1374         return true;
1375     }
1376
1377     function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1378     {
1379         if ($target->getObjectType() === ActivityObject::PERSON) {
1380             $this->addWebFingerPersonLinks($xrd, $target);
1381         } elseif ($target->getObjectType() === ActivityObject::GROUP) {
1382             $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1383                             common_local_url('ApiTimelineGroup',
1384                                 array('id' => $target->getGroup()->getID(), 'format' => 'atom')),
1385                             'application/atom+xml');
1386
1387         }
1388
1389         // Salmon
1390         $profiletype = $this->profileTypeString($target);
1391         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1392
1393         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1394
1395         // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1396         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1397         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1398
1399         // TODO - finalize where the redirect should go on the publisher
1400         $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1401                               common_local_url('ostatussub') . '?profile={uri}',
1402                               null, // type not set
1403                               true); // isTemplate
1404
1405         return true;
1406     }
1407
1408     protected function profileTypeString(Profile $target)
1409     {
1410         // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1411         switch ($target->getObjectType()) {
1412         case ActivityObject::PERSON:
1413             return 'user';
1414         case ActivityObject::GROUP:
1415             return 'group';
1416         default:
1417             throw new ServerException('Unknown profile type for WebFinger profile links');
1418         }
1419     }
1420
1421     protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1422     {
1423         $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1424                             common_local_url('ApiTimelineUser',
1425                                 array('id' => $target->id, 'format' => 'atom')),
1426                             'application/atom+xml');
1427
1428         // Get this profile's keypair
1429         $magicsig = Magicsig::getKV('user_id', $target->id);
1430         if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1431             $magicsig = Magicsig::generate($target->getUser());
1432         }
1433
1434         if (!$magicsig instanceof Magicsig) {
1435             return false;   // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1436         }
1437         if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1438             $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1439                                 'data:application/magic-public-key,'. $magicsig->toString());
1440             // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1441             Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1442         }
1443     }
1444
1445     public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1446     {
1447         list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
1448     }
1449
1450     // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1451     static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1452     {
1453         try {
1454             $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1455             $profile = $oprofile->checkAuthorship($activity);
1456         } catch (Exception $e) {
1457             common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1458             $profile = null;
1459             return false;
1460         }
1461         return true;
1462     }
1463
1464     public function onProfileDeleteRelated($profile, &$related)
1465     {
1466         // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1467         $related[] = 'Ostatus_profile';
1468
1469         // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1470         $magicsig = Magicsig::getKV('user_id', $profile->id);
1471         if ($magicsig instanceof Magicsig) {
1472             $magicsig->delete();
1473         }
1474         return true;
1475     }
1476
1477     public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
1478     {
1479         try {
1480             $envxml = $magic_env->toXML($target);
1481         } catch (Exception $e) {
1482             common_log(LOG_ERR, sprintf('Could not generate Magic Envelope XML for profile id=='.$target->getID().': '.$e->getMessage()));
1483             return false;
1484         }
1485
1486         $headers = array('Content-Type: application/magic-envelope+xml');
1487
1488         try {
1489             $client = new HTTPClient();
1490             $client->setBody($envxml);
1491             $response = $client->post($endpoint_uri, $headers);
1492         } catch (Exception $e) {
1493             common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
1494             return false;
1495         }
1496         if ($response->getStatus() === 422) {
1497             common_debug(sprintf('Salmon (from profile %d) endpoint %s returned status %s. We assume it is a Diaspora seed; will adapt and try again if that plugin is enabled!', $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus()));
1498             return true;
1499         }
1500
1501         // The different kinds of accepted responses...
1502         // 200 OK means it's all ok
1503         // 201 Created is what Mastodon returns when it's ok
1504         // 202 Accepted is what we get from Diaspora, also good
1505         if (!in_array($response->getStatus(), array(200, 201, 202))) {
1506             common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
1507                                 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
1508             return true;
1509         }
1510
1511         // Since we completed the salmon slap, we discontinue the event
1512         return false;
1513     }
1514
1515     public function onCronDaily()
1516     {
1517         try {
1518             $sub = FeedSub::renewalCheck();
1519         } catch (NoResultException $e) {
1520             common_log(LOG_INFO, "There were no expiring feeds.");
1521             return;
1522         }
1523
1524         $qm = QueueManager::get();
1525         while ($sub->fetch()) {
1526             $item = array('feedsub_id' => $sub->id);
1527             $qm->enqueue($item, 'pushrenew');
1528         }
1529     }
1530 }