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