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