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