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