]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Implemented WebFinger and replaced our XRD with PEAR XML_XRD
[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/');
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
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 (os user?)
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($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                                                'text' => $target,
358                                                'position' => $pos,
359                                                'url' => $profile->profileurl);
360                     }
361                 } catch (Exception $e) {
362                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
363                 }
364             }
365         }
366
367         // Profile matches: @example.com/mublog/user
368         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
369                        $text,
370                        $wmatches,
371                        PREG_OFFSET_CAPTURE)) {
372             foreach ($wmatches[1] as $wmatch) {
373                 list($target, $pos) = $wmatch;
374                 $schemes = array('http', 'https');
375                 foreach ($schemes as $scheme) {
376                     $url = "$scheme://$target";
377                     $this->log(LOG_INFO, "Checking profile address '$url'");
378                     try {
379                         $oprofile = Ostatus_profile::ensureProfileURL($url);
380                         if ($oprofile && !$oprofile->isGroup()) {
381                             $profile = $oprofile->localProfile();
382                             $matches[$pos] = array('mentioned' => array($profile),
383                                                    'text' => $target,
384                                                    'position' => $pos,
385                                                    'url' => $profile->profileurl);
386                             break;
387                         }
388                     } catch (Exception $e) {
389                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
390                     }
391                 }
392             }
393         }
394
395         foreach ($mentions as $i => $other) {
396             // If we share a common prefix with a local user, override it!
397             $pos = $other['position'];
398             if (isset($matches[$pos])) {
399                 $mentions[$i] = $matches[$pos];
400                 unset($matches[$pos]);
401             }
402         }
403         foreach ($matches as $mention) {
404             $mentions[] = $mention;
405         }
406
407         return true;
408     }
409
410     /**
411      * Allow remote profile references to be used in commands:
412      *   sub update@status.net
413      *   whois evan@identi.ca
414      *   reply http://identi.ca/evan hey what's up
415      *
416      * @param Command $command
417      * @param string $arg
418      * @param Profile &$profile
419      * @return hook return code
420      */
421     function onStartCommandGetProfile($command, $arg, &$profile)
422     {
423         $oprofile = $this->pullRemoteProfile($arg);
424         if ($oprofile && !$oprofile->isGroup()) {
425             $profile = $oprofile->localProfile();
426             return false;
427         } else {
428             return true;
429         }
430     }
431
432     /**
433      * Allow remote group references to be used in commands:
434      *   join group+statusnet@identi.ca
435      *   join http://identi.ca/group/statusnet
436      *   drop identi.ca/group/statusnet
437      *
438      * @param Command $command
439      * @param string $arg
440      * @param User_group &$group
441      * @return hook return code
442      */
443     function onStartCommandGetGroup($command, $arg, &$group)
444     {
445         $oprofile = $this->pullRemoteProfile($arg);
446         if ($oprofile && $oprofile->isGroup()) {
447             $group = $oprofile->localGroup();
448             return false;
449         } else {
450             return true;
451         }
452     }
453
454     protected function pullRemoteProfile($arg)
455     {
456         $oprofile = null;
457         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
458             // webfinger lookup
459             try {
460                 return Ostatus_profile::ensureWebfinger($arg);
461             } catch (Exception $e) {
462                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
463                                     $arg . ': ' . $e->getMessage());
464             }
465         }
466
467         // Look for profile URLs, with or without scheme:
468         $urls = array();
469         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
470             $urls[] = $arg;
471         }
472         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
473             $schemes = array('http', 'https');
474             foreach ($schemes as $scheme) {
475                 $urls[] = "$scheme://$arg";
476             }
477         }
478
479         foreach ($urls as $url) {
480             try {
481                 return Ostatus_profile::ensureProfileURL($url);
482             } catch (Exception $e) {
483                 common_log(LOG_ERR, 'Profile lookup failed for ' .
484                                     $arg . ': ' . $e->getMessage());
485             }
486         }
487         return null;
488     }
489
490     /**
491      * Make sure necessary tables are filled out.
492      */
493     function onCheckSchema() {
494         $schema = Schema::get();
495         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
496         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
497         $schema->ensureTable('feedsub', FeedSub::schemaDef());
498         $schema->ensureTable('hubsub', HubSub::schemaDef());
499         $schema->ensureTable('magicsig', Magicsig::schemaDef());
500         return true;
501     }
502
503     public function onEndShowStylesheets(Action $action) {
504         $action->cssLink($this->path('theme/base/css/ostatus.css'));
505         return true;
506     }
507
508     function onEndShowStatusNetScripts($action) {
509         $action->script($this->path('js/ostatus.js'));
510         return true;
511     }
512
513     /**
514      * Override the "from ostatus" bit in notice lists to link to the
515      * original post and show the domain it came from.
516      *
517      * @param Notice in $notice
518      * @param string out &$name
519      * @param string out &$url
520      * @param string out &$title
521      * @return mixed hook return code
522      */
523     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
524     {
525         if ($notice->source == 'ostatus') {
526             if ($notice->url) {
527                 $bits = parse_url($notice->url);
528                 $domain = $bits['host'];
529                 if (substr($domain, 0, 4) == 'www.') {
530                     $name = substr($domain, 4);
531                 } else {
532                     $name = $domain;
533                 }
534
535                 $url = $notice->url;
536                 // TRANS: Title. %s is a domain name.
537                 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
538                 return false;
539             }
540         }
541     return true;
542     }
543
544     /**
545      * Send incoming PuSH feeds for OStatus endpoints in for processing.
546      *
547      * @param FeedSub $feedsub
548      * @param DOMDocument $feed
549      * @return mixed hook return code
550      */
551     function onStartFeedSubReceive($feedsub, $feed)
552     {
553         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
554         if ($oprofile) {
555             $oprofile->processFeed($feed, 'push');
556         } else {
557             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
558         }
559     }
560
561     /**
562      * Tell the FeedSub infrastructure whether we have any active OStatus
563      * usage for the feed; if not it'll be able to garbage-collect the
564      * feed subscription.
565      *
566      * @param FeedSub $feedsub
567      * @param integer $count in/out
568      * @return mixed hook return code
569      */
570     function onFeedSubSubscriberCount($feedsub, &$count)
571     {
572         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
573         if ($oprofile) {
574             $count += $oprofile->subscriberCount();
575         }
576         return true;
577     }
578
579     /**
580      * When about to subscribe to a remote user, start a server-to-server
581      * PuSH subscription if needed. If we can't establish that, abort.
582      *
583      * @fixme If something else aborts later, we could end up with a stray
584      *        PuSH subscription. This is relatively harmless, though.
585      *
586      * @param Profile $profile  subscriber
587      * @param Profile $other    subscribee
588      *
589      * @return hook return code
590      *
591      * @throws Exception
592      */
593     function onStartSubscribe(Profile $profile, Profile $other)
594     {
595         if (!$profile->isLocal()) {
596             return true;
597         }
598
599         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
600
601         if (empty($oprofile)) {
602             return true;
603         }
604
605         if (!$oprofile->subscribe()) {
606             // TRANS: Exception thrown when setup of remote subscription fails.
607             throw new Exception(_m('Could not set up remote subscription.'));
608         }
609     }
610
611     /**
612      * Having established a remote subscription, send a notification to the
613      * remote OStatus profile's endpoint.
614      *
615      * @param Profile $profile  subscriber
616      * @param Profile $other    subscribee
617      *
618      * @return hook return code
619      *
620      * @throws Exception
621      */
622     function onEndSubscribe(Profile $profile, Profile $other)
623     {
624         if (!$profile->isLocal()) {
625             return true;
626         }
627
628         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
629
630         if (empty($oprofile)) {
631             return true;
632         }
633
634         $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
635                                            'subscribed' => $other->id));
636
637         $act = $sub->asActivity();
638
639         $oprofile->notifyActivity($act, $profile);
640
641         return true;
642     }
643
644     /**
645      * Notify remote server and garbage collect unused feeds on unsubscribe.
646      * @todo FIXME: Send these operations to background queues
647      *
648      * @param User $user
649      * @param Profile $other
650      * @return hook return value
651      */
652     function onEndUnsubscribe(Profile $profile, Profile $other)
653     {
654         if (!$profile->isLocal()) {
655             return true;
656         }
657
658         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
659
660         if (empty($oprofile)) {
661             return true;
662         }
663
664         // Drop the PuSH subscription if there are no other subscribers.
665         $oprofile->garbageCollect();
666
667         $act = new Activity();
668
669         $act->verb = ActivityVerb::UNFOLLOW;
670
671         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
672                                   $profile->id,
673                                   $other->id,
674                                   common_date_iso8601(time()));
675
676         $act->time    = time();
677         // TRANS: Title for unfollowing a remote profile.
678         $act->title   = _m('TITLE','Unfollow');
679         // TRANS: Success message for unsubscribe from user attempt through OStatus.
680         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
681         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
682                                $profile->getBestName(),
683                                $other->getBestName());
684
685         $act->actor   = ActivityObject::fromProfile($profile);
686         $act->object  = ActivityObject::fromProfile($other);
687
688         $oprofile->notifyActivity($act, $profile);
689
690         return true;
691     }
692
693     /**
694      * When one of our local users tries to join a remote group,
695      * notify the remote server. If the notification is rejected,
696      * deny the join.
697      *
698      * @param User_group $group
699      * @param Profile    $profile
700      *
701      * @return mixed hook return value
702      */
703     function onStartJoinGroup($group, $profile)
704     {
705         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
706         if ($oprofile) {
707             if (!$oprofile->subscribe()) {
708                 // TRANS: Exception thrown when setup of remote group membership fails.
709                 throw new Exception(_m('Could not set up remote group membership.'));
710             }
711
712             // NOTE: we don't use Group_member::asActivity() since that record
713             // has not yet been created.
714
715             $act = new Activity();
716             $act->id = TagURI::mint('join:%d:%d:%s',
717                                     $profile->id,
718                                     $group->id,
719                                     common_date_iso8601(time()));
720
721             $act->actor = ActivityObject::fromProfile($profile);
722             $act->verb = ActivityVerb::JOIN;
723             $act->object = $oprofile->asActivityObject();
724
725             $act->time = time();
726             // TRANS: Title for joining a remote groep.
727             $act->title = _m('TITLE','Join');
728             // TRANS: Success message for subscribe to group attempt through OStatus.
729             // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
730             $act->content = sprintf(_m('%1$s has joined group %2$s.'),
731                                     $profile->getBestName(),
732                                     $oprofile->getBestName());
733
734             if ($oprofile->notifyActivity($act, $profile)) {
735                 return true;
736             } else {
737                 $oprofile->garbageCollect();
738                 // TRANS: Exception thrown when joining a remote group fails.
739                 throw new Exception(_m('Failed joining remote group.'));
740             }
741         }
742     }
743
744     /**
745      * When one of our local users leaves a remote group, notify the remote
746      * server.
747      *
748      * @fixme Might be good to schedule a resend of the leave notification
749      * if it failed due to a transitory error. We've canceled the local
750      * membership already anyway, but if the remote server comes back up
751      * it'll be left with a stray membership record.
752      *
753      * @param User_group $group
754      * @param Profile $profile
755      *
756      * @return mixed hook return value
757      */
758     function onEndLeaveGroup($group, $profile)
759     {
760         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
761         if ($oprofile) {
762             // Drop the PuSH subscription if there are no other subscribers.
763             $oprofile->garbageCollect();
764
765             $member = $profile;
766
767             $act = new Activity();
768             $act->id = TagURI::mint('leave:%d:%d:%s',
769                                     $member->id,
770                                     $group->id,
771                                     common_date_iso8601(time()));
772
773             $act->actor = ActivityObject::fromProfile($member);
774             $act->verb = ActivityVerb::LEAVE;
775             $act->object = $oprofile->asActivityObject();
776
777             $act->time = time();
778             // TRANS: Title for leaving a remote group.
779             $act->title = _m('TITLE','Leave');
780             // TRANS: Success message for unsubscribe from group attempt through OStatus.
781             // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
782             $act->content = sprintf(_m('%1$s has left group %2$s.'),
783                                     $member->getBestName(),
784                                     $oprofile->getBestName());
785
786             $oprofile->notifyActivity($act, $member);
787         }
788     }
789
790     /**
791      * When one of our local users tries to subscribe to a remote peopletag,
792      * notify the remote server. If the notification is rejected,
793      * deny the subscription.
794      *
795      * @param Profile_list $peopletag
796      * @param User         $user
797      *
798      * @return mixed hook return value
799      */
800
801     function onStartSubscribePeopletag($peopletag, $user)
802     {
803         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
804         if ($oprofile) {
805             if (!$oprofile->subscribe()) {
806                 // TRANS: Exception thrown when setup of remote list subscription fails.
807                 throw new Exception(_m('Could not set up remote list subscription.'));
808             }
809
810             $sub = $user->getProfile();
811             $tagger = Profile::getKV($peopletag->tagger);
812
813             $act = new Activity();
814             $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
815                                     $sub->id,
816                                     $peopletag->id,
817                                     common_date_iso8601(time()));
818
819             $act->actor = ActivityObject::fromProfile($sub);
820             $act->verb = ActivityVerb::FOLLOW;
821             $act->object = $oprofile->asActivityObject();
822
823             $act->time = time();
824             // TRANS: Title for following a remote list.
825             $act->title = _m('TITLE','Follow list');
826             // TRANS: Success message for remote list follow through OStatus.
827             // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
828             $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
829                                     $sub->getBestName(),
830                                     $oprofile->getBestName(),
831                                     $tagger->getBestName());
832
833             if ($oprofile->notifyActivity($act, $sub)) {
834                 return true;
835             } else {
836                 $oprofile->garbageCollect();
837                 // TRANS: Exception thrown when subscription to remote list fails.
838                 throw new Exception(_m('Failed subscribing to remote list.'));
839             }
840         }
841     }
842
843     /**
844      * When one of our local users unsubscribes to a remote peopletag, notify the remote
845      * server.
846      *
847      * @param Profile_list $peopletag
848      * @param User         $user
849      *
850      * @return mixed hook return value
851      */
852
853     function onEndUnsubscribePeopletag($peopletag, $user)
854     {
855         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
856         if ($oprofile) {
857             // Drop the PuSH subscription if there are no other subscribers.
858             $oprofile->garbageCollect();
859
860             $sub = Profile::getKV($user->id);
861             $tagger = Profile::getKV($peopletag->tagger);
862
863             $act = new Activity();
864             $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
865                                     $sub->id,
866                                     $peopletag->id,
867                                     common_date_iso8601(time()));
868
869             $act->actor = ActivityObject::fromProfile($member);
870             $act->verb = ActivityVerb::UNFOLLOW;
871             $act->object = $oprofile->asActivityObject();
872
873             $act->time = time();
874             // TRANS: Title for unfollowing a remote list.
875             $act->title = _m('Unfollow list');
876             // TRANS: Success message for remote list unfollow through OStatus.
877             // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
878             $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
879                                     $sub->getBestName(),
880                                     $oprofile->getBestName(),
881                                     $tagger->getBestName());
882
883             $oprofile->notifyActivity($act, $user);
884         }
885     }
886
887     /**
888      * Notify remote users when their notices get favorited.
889      *
890      * @param Profile or User $profile of local user doing the faving
891      * @param Notice $notice being favored
892      * @return hook return value
893      */
894     function onEndFavorNotice(Profile $profile, Notice $notice)
895     {
896         $user = User::getKV('id', $profile->id);
897
898         if (empty($user)) {
899             return true;
900         }
901
902         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
903
904         if (empty($oprofile)) {
905             return true;
906         }
907
908         $fav = Fave::pkeyGet(array('user_id' => $user->id,
909                                    'notice_id' => $notice->id));
910
911         if (empty($fav)) {
912             // That's weird.
913             return true;
914         }
915
916         $act = $fav->asActivity();
917
918         $oprofile->notifyActivity($act, $profile);
919
920         return true;
921     }
922
923     /**
924      * Notify remote user it has got a new people tag
925      *   - tag verb is queued
926      *   - the subscription is done immediately if not present
927      *
928      * @param Profile_tag $ptag the people tag that was created
929      * @return hook return value
930      */
931     function onEndTagProfile($ptag)
932     {
933         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
934
935         if (empty($oprofile)) {
936             return true;
937         }
938
939         $plist = $ptag->getMeta();
940         if ($plist->private) {
941             return true;
942         }
943
944         $act = new Activity();
945
946         $tagger = $plist->getTagger();
947         $tagged = Profile::getKV('id', $ptag->tagged);
948
949         $act->verb = ActivityVerb::TAG;
950         $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
951                                   $plist->tagger, $plist->id,
952                                   common_date_iso8601(time()));
953         $act->time = time();
954         // TRANS: Title for listing a remote profile.
955         $act->title = _m('TITLE','List');
956         // TRANS: Success message for remote list addition through OStatus.
957         // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
958         $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
959                                 $tagger->getBestName(),
960                                 $tagged->getBestName(),
961                                 $plist->getBestName());
962
963         $act->actor  = ActivityObject::fromProfile($tagger);
964         $act->objects = array(ActivityObject::fromProfile($tagged));
965         $act->target = ActivityObject::fromPeopletag($plist);
966
967         $oprofile->notifyDeferred($act, $tagger);
968
969         // initiate a PuSH subscription for the person being tagged
970         if (!$oprofile->subscribe()) {
971             // TRANS: Exception thrown when subscribing to a remote list fails.
972             throw new Exception(sprintf(_m('Could not complete subscription to remote '.
973                                           'profile\'s feed. List %s could not be saved.'), $ptag->tag));
974             return false;
975         }
976         return true;
977     }
978
979     /**
980      * Notify remote user that a people tag has been removed
981      *   - untag verb is queued
982      *   - the subscription is undone immediately if not required
983      *     i.e garbageCollect()'d
984      *
985      * @param Profile_tag $ptag the people tag that was deleted
986      * @return hook return value
987      */
988     function onEndUntagProfile($ptag)
989     {
990         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
991
992         if (empty($oprofile)) {
993             return true;
994         }
995
996         $plist = $ptag->getMeta();
997         if ($plist->private) {
998             return true;
999         }
1000
1001         $act = new Activity();
1002
1003         $tagger = $plist->getTagger();
1004         $tagged = Profile::getKV('id', $ptag->tagged);
1005
1006         $act->verb = ActivityVerb::UNTAG;
1007         $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
1008                                   $plist->tagger, $plist->id,
1009                                   common_date_iso8601(time()));
1010         $act->time = time();
1011         // TRANS: Title for unlisting a remote profile.
1012         $act->title = _m('TITLE','Unlist');
1013         // TRANS: Success message for remote list removal through OStatus.
1014         // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1015         $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1016                                 $tagger->getBestName(),
1017                                 $tagged->getBestName(),
1018                                 $plist->getBestName());
1019
1020         $act->actor  = ActivityObject::fromProfile($tagger);
1021         $act->objects = array(ActivityObject::fromProfile($tagged));
1022         $act->target = ActivityObject::fromPeopletag($plist);
1023
1024         $oprofile->notifyDeferred($act, $tagger);
1025
1026         // unsubscribe to PuSH feed if no more required
1027         $oprofile->garbageCollect();
1028
1029         return true;
1030     }
1031
1032     /**
1033      * Notify remote users when their notices get de-favorited.
1034      *
1035      * @param Profile $profile Profile person doing the de-faving
1036      * @param Notice  $notice  Notice being favored
1037      *
1038      * @return hook return value
1039      */
1040     function onEndDisfavorNotice(Profile $profile, Notice $notice)
1041     {
1042         $user = User::getKV('id', $profile->id);
1043
1044         if (empty($user)) {
1045             return true;
1046         }
1047
1048         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1049
1050         if (empty($oprofile)) {
1051             return true;
1052         }
1053
1054         $act = new Activity();
1055
1056         $act->verb = ActivityVerb::UNFAVORITE;
1057         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
1058                                   $profile->id,
1059                                   $notice->id,
1060                                   common_date_iso8601(time()));
1061         $act->time    = time();
1062         // TRANS: Title for unliking a remote notice.
1063         $act->title   = _m('Unlike');
1064         // TRANS: Success message for remove a favorite notice through OStatus.
1065         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1066         $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1067                                $profile->getBestName(),
1068                                $notice->uri);
1069
1070         $act->actor   = ActivityObject::fromProfile($profile);
1071         $act->object  = ActivityObject::fromNotice($notice);
1072
1073         $oprofile->notifyActivity($act, $profile);
1074
1075         return true;
1076     }
1077
1078     function onStartGetProfileUri($profile, &$uri)
1079     {
1080         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1081         if (!empty($oprofile)) {
1082             $uri = $oprofile->uri;
1083             return false;
1084         }
1085         return true;
1086     }
1087
1088     function onStartUserGroupHomeUrl($group, &$url)
1089     {
1090         return $this->onStartUserGroupPermalink($group, $url);
1091     }
1092
1093     function onStartUserGroupPermalink($group, &$url)
1094     {
1095         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1096         if ($oprofile) {
1097             // @fixme this should probably be in the user_group table
1098             // @fixme this uri not guaranteed to be a profile page
1099             $url = $oprofile->uri;
1100             return false;
1101         }
1102     }
1103
1104     function onStartShowSubscriptionsContent($action)
1105     {
1106         $this->showEntityRemoteSubscribe($action);
1107
1108         return true;
1109     }
1110
1111     function onStartShowUserGroupsContent($action)
1112     {
1113         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1114
1115         return true;
1116     }
1117
1118     function onEndShowSubscriptionsMiniList($action)
1119     {
1120         $this->showEntityRemoteSubscribe($action);
1121
1122         return true;
1123     }
1124
1125     function onEndShowGroupsMiniList($action)
1126     {
1127         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1128
1129         return true;
1130     }
1131
1132     function showEntityRemoteSubscribe($action, $target='ostatussub')
1133     {
1134         $user = common_current_user();
1135         if ($user && ($user->id == $action->profile->id)) {
1136             $action->elementStart('div', 'entity_actions');
1137             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1138                                              'class' => 'entity_subscribe'));
1139             $action->element('a', array('href' => common_local_url($target),
1140                                         'class' => 'entity_remote_subscribe'),
1141                                 // TRANS: Link text for link to remote subscribe.
1142                                 _m('Remote'));
1143             $action->elementEnd('p');
1144             $action->elementEnd('div');
1145         }
1146     }
1147
1148     /**
1149      * Ping remote profiles with updates to this profile.
1150      * Salmon pings are queued for background processing.
1151      */
1152     function onEndBroadcastProfile(Profile $profile)
1153     {
1154         $user = User::getKV('id', $profile->id);
1155
1156         // Find foreign accounts I'm subscribed to that support Salmon pings.
1157         //
1158         // @fixme we could run updates through the PuSH feed too,
1159         // in which case we can skip Salmon pings to folks who
1160         // are also subscribed to me.
1161         $sql = "SELECT * FROM ostatus_profile " .
1162                "WHERE profile_id IN " .
1163                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1164                "OR group_id IN " .
1165                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1166         $oprofile = new Ostatus_profile();
1167         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1168
1169         if ($oprofile->N == 0) {
1170             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1171             return true;
1172         }
1173
1174         $act = new Activity();
1175
1176         $act->verb = ActivityVerb::UPDATE_PROFILE;
1177         $act->id   = TagURI::mint('update-profile:%d:%s',
1178                                   $profile->id,
1179                                   common_date_iso8601(time()));
1180         $act->time    = time();
1181         // TRANS: Title for activity.
1182         $act->title   = _m('Profile update');
1183         // TRANS: Ping text for remote profile update through OStatus.
1184         // TRANS: %s is user that updated their profile.
1185         $act->content = sprintf(_m('%s has updated their profile page.'),
1186                                $profile->getBestName());
1187
1188         $act->actor   = ActivityObject::fromProfile($profile);
1189         $act->object  = $act->actor;
1190
1191         while ($oprofile->fetch()) {
1192             $oprofile->notifyDeferred($act, $profile);
1193         }
1194
1195         return true;
1196     }
1197
1198     function onStartProfileListItemActionElements($item, $profile=null)
1199     {
1200         if (!common_logged_in()) {
1201
1202             $profileUser = User::getKV('id', $item->profile->id);
1203
1204             if (!empty($profileUser)) {
1205
1206                 if ($item instanceof Action) {
1207                     $output = $item;
1208                     $profile = $item->profile;
1209                 } else {
1210                     $output = $item->out;
1211                 }
1212
1213                 // Add an OStatus subscribe
1214                 $output->elementStart('li', 'entity_subscribe');
1215                 $url = common_local_url('ostatusinit',
1216                                         array('nickname' => $profileUser->nickname));
1217                 $output->element('a', array('href' => $url,
1218                                             'class' => 'entity_remote_subscribe'),
1219                                   // TRANS: Link text for a user to subscribe to an OStatus user.
1220                                  _m('Subscribe'));
1221                 $output->elementEnd('li');
1222
1223                 $output->elementStart('li', 'entity_tag');
1224                 $url = common_local_url('ostatustag',
1225                                         array('nickname' => $profileUser->nickname));
1226                 $output->element('a', array('href' => $url,
1227                                             'class' => 'entity_remote_tag'),
1228                                   // TRANS: Link text for a user to list an OStatus user.
1229                                  _m('List'));
1230                 $output->elementEnd('li');
1231             }
1232         }
1233
1234         return true;
1235     }
1236
1237     function onPluginVersion(&$versions)
1238     {
1239         $versions[] = array('name' => 'OStatus',
1240                             'version' => STATUSNET_VERSION,
1241                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1242                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1243                             // TRANS: Plugin description.
1244                             'rawdescription' => _m('Follow people across social networks that implement '.
1245                                '<a href="http://ostatus.org/">OStatus</a>.'));
1246
1247         return true;
1248     }
1249
1250     /**
1251      * Utility function to check if the given URI is a canonical group profile
1252      * page, and if so return the ID number.
1253      *
1254      * @param string $url
1255      * @return mixed int or false
1256      */
1257     public static function localGroupFromUrl($url)
1258     {
1259         $group = User_group::getKV('uri', $url);
1260         if ($group) {
1261             $local = Local_group::getKV('group_id', $group->id);
1262             if ($local) {
1263                 return $group->id;
1264             }
1265         } else {
1266             // To find local groups which haven't had their uri fields filled out...
1267             // If the domain has changed since a subscriber got the URI, it'll
1268             // be broken.
1269             $template = common_local_url('groupbyid', array('id' => '31337'));
1270             $template = preg_quote($template, '/');
1271             $template = str_replace('31337', '(\d+)', $template);
1272             if (preg_match("/$template/", $url, $matches)) {
1273                 return intval($matches[1]);
1274             }
1275         }
1276         return false;
1277     }
1278
1279     public function onStartProfileGetAtomFeed($profile, &$feed)
1280     {
1281         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1282
1283         if (empty($oprofile)) {
1284             return true;
1285         }
1286
1287         $feed = $oprofile->feeduri;
1288         return false;
1289     }
1290
1291     function onStartGetProfileFromURI($uri, &$profile)
1292     {
1293         // Don't want to do Web-based discovery on our own server,
1294         // so we check locally first.
1295
1296         $user = User::getKV('uri', $uri);
1297
1298         if (!empty($user)) {
1299             $profile = $user->getProfile();
1300             return false;
1301         }
1302
1303         // Now, check remotely
1304
1305         $oprofile = Ostatus_profile::ensureProfileURI($uri);
1306
1307         if (!empty($oprofile)) {
1308             $profile = $oprofile->localProfile();
1309             return false;
1310         }
1311
1312         // Still not a hit, so give up.
1313
1314         return true;
1315     }
1316
1317     function onEndXrdActionLinks(XML_XRD $xrd, Profile $target)
1318     {
1319         $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1320                             common_local_url('ApiTimelineUser',
1321                                 array('id' => $target->id, 'format' => 'atom')),
1322                             'application/atom+xml');
1323
1324                 // Salmon
1325         $salmon_url = common_local_url('usersalmon',
1326                                        array('id' => $target->id));
1327
1328         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1329         // XXX : Deprecated - to be removed.
1330         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1331         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1332
1333         // Get this user's keypair
1334         $magickey = Magicsig::getKV('user_id', $target->id);
1335         if (!($magickey instanceof Magicsig)) {
1336             // No keypair yet, let's generate one.
1337             $magickey = new Magicsig();
1338             $magickey->generate($target->id);
1339         }
1340
1341         $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1342                             'data:application/magic-public-key,'. $magickey->toString(false));
1343
1344         // TODO - finalize where the redirect should go on the publisher
1345         $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1346                               common_local_url('ostatussub') . '?profile={uri}',
1347                               null, // type not set
1348                               true); // isTemplate
1349
1350         return true;
1351     }
1352 }