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