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