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