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