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