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