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