3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
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.
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.
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/>.
21 * OStatusPlugin implementation for GNU Social
23 * Depends on: WebFinger plugin
25 * @package OStatusPlugin
26 * @maintainer Brion Vibber <brion@status.net>
29 if (!defined('GNUSOCIAL')) { exit(1); }
31 class OStatusPlugin extends Plugin
34 * Hook for RouterInitialized event.
36 * @param URLMapper $m path-to-action mapper
37 * @return boolean hook return
39 public function onRouterInitialized(URLMapper $m)
42 $m->connect('main/ostatustag',
43 array('action' => 'ostatustag'));
44 $m->connect('main/ostatustag?nickname=:nickname',
45 array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
46 $m->connect('main/ostatus/nickname/:nickname',
47 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
48 $m->connect('main/ostatus/group/:group',
49 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
50 $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
51 array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
52 'peopletag' => '[A-Za-z0-9_-]+'));
53 $m->connect('main/ostatus',
54 array('action' => 'ostatusinit'));
56 // Remote subscription actions
57 $m->connect('main/ostatussub',
58 array('action' => 'ostatussub'));
59 $m->connect('main/ostatusgroup',
60 array('action' => 'ostatusgroup'));
61 $m->connect('main/ostatuspeopletag',
62 array('action' => 'ostatuspeopletag'));
65 $m->connect('main/push/hub', array('action' => 'pushhub'));
67 $m->connect('main/push/callback/:feed',
68 array('action' => 'pushcallback'),
69 array('feed' => '[0-9]+'));
72 $m->connect('main/salmon/user/:id',
73 array('action' => 'usersalmon'),
74 array('id' => '[0-9]+'));
75 $m->connect('main/salmon/group/:id',
76 array('action' => 'groupsalmon'),
77 array('id' => '[0-9]+'));
78 $m->connect('main/salmon/peopletag/:id',
79 array('action' => 'peopletagsalmon'),
80 array('id' => '[0-9]+'));
85 * Set up queue handlers for outgoing hub pushes
86 * @param QueueManager $qm
87 * @return boolean hook return
89 function onEndInitializeQueueManager(QueueManager $qm)
91 // Prepare outgoing distributions after notice save.
92 $qm->connect('ostatus', 'OStatusQueueHandler');
94 // Outgoing from our internal PuSH hub
95 $qm->connect('hubconf', 'HubConfQueueHandler');
96 $qm->connect('hubprep', 'HubPrepQueueHandler');
98 $qm->connect('hubout', 'HubOutQueueHandler');
100 // Outgoing Salmon replies (when we don't need a return value)
101 $qm->connect('salmon', 'SalmonQueueHandler');
103 // Incoming from a foreign PuSH hub
104 $qm->connect('pushin', 'PushInQueueHandler');
106 // Re-subscribe feeds that need renewal
107 $qm->connect('pushrenew', 'PushRenewQueueHandler');
112 * Put saved notices into the queue for pubsub distribution.
114 function onStartEnqueueNotice($notice, &$transports)
116 if ($notice->inScope(null) && $notice->getProfile()->hasRight(Right::PUBLICNOTICE)) {
117 // put our transport first, in case there's any conflict (like OMB)
118 array_unshift($transports, 'ostatus');
119 $this->log(LOG_INFO, "OSTATUS [{$notice->getID()}]: queued for OStatus processing");
121 // FIXME: we don't do privacy-controlled OStatus updates yet.
122 // once that happens, finer grain of control here.
123 $this->log(LOG_NOTICE, "OSTATUS [{$notice->getID()}]: Not queueing because of privacy; scope = {$notice->scope}");
129 * Set up a PuSH hub link to our internal link for canonical timeline
130 * Atom feeds for users and groups.
132 function onStartApiAtom($feed)
136 if ($feed instanceof AtomUserNoticeFeed) {
137 $salmonAction = 'usersalmon';
138 $user = $feed->getUser();
140 $profile = $user->getProfile();
141 } else if ($feed instanceof AtomGroupNoticeFeed) {
142 $salmonAction = 'groupsalmon';
143 $group = $feed->getGroup();
145 } else if ($feed instanceof AtomListNoticeFeed) {
146 $salmonAction = 'peopletagsalmon';
147 $peopletag = $feed->getList();
148 $id = $peopletag->id;
154 $hub = common_config('ostatus', 'hub');
156 // Updates will be handled through our internal PuSH hub.
157 $hub = common_local_url('pushhub');
159 $feed->addLink($hub, array('rel' => 'hub'));
161 // Also, we'll add in the salmon link
162 $salmon = common_local_url($salmonAction, array('id' => $id));
163 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
165 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
166 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
167 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
174 * Add in an OStatus subscribe button
176 function onStartProfileRemoteSubscribe($output, $profile)
178 $this->onStartProfileListItemActionElements($output, $profile);
182 function onStartGroupSubscribe($widget, $group)
184 $cur = common_current_user();
187 $widget->out->elementStart('li', 'entity_subscribe');
189 $url = common_local_url('ostatusinit',
190 array('group' => $group->nickname));
191 $widget->out->element('a', array('href' => $url,
192 'class' => 'entity_remote_subscribe'),
193 // TRANS: Link to subscribe to a remote entity.
196 $widget->out->elementEnd('li');
203 function onStartSubscribePeopletagForm($output, $peopletag)
205 $cur = common_current_user();
208 $output->elementStart('li', 'entity_subscribe');
209 $profile = $peopletag->getTagger();
210 $url = common_local_url('ostatusinit',
211 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
212 $output->element('a', array('href' => $url,
213 'class' => 'entity_remote_subscribe'),
214 // TRANS: Link to subscribe to a remote entity.
217 $output->elementEnd('li');
225 * If the field being looked for is URI look for the profile
227 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
228 if ($action->field == 'uri') {
229 $profile->joinAdd(array('id', 'user:id'));
230 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
233 $validate = new Validate();
235 if ($profile->N == 0) {
237 if ($validate->email($q)) {
238 $oprofile = Ostatus_profile::ensureWebfinger($q);
239 } else if ($validate->uri($q)) {
240 $oprofile = Ostatus_profile::ensureProfileURL($q);
242 // TRANS: Exception in OStatus when invalid URI was entered.
243 throw new Exception(_m('Invalid URI.'));
245 return $this->filter(array($oprofile->localProfile()));
247 } catch (Exception $e) {
248 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
249 // TRANS: and example.net, as these are official standard domain names for use in examples.
250 $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.");
260 * Find any explicit remote mentions. Accepted forms:
261 * Webfinger: @user@example.com
262 * Profile link: @example.com/mublog/user
263 * @param Profile $sender
264 * @param string $text input markup text
265 * @param array &$mention in/out param: set of found mentions
266 * @return boolean hook return value
268 function onEndFindMentions(Profile $sender, $text, &$mentions)
273 // Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
274 if (preg_match_all('!(?:^|\s+)@((?:\w+[\w\-\_\.]?)*(?:[\w\-\_\.]*\w+)@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
277 PREG_OFFSET_CAPTURE)) {
278 foreach ($wmatches[1] as $wmatch) {
279 list($target, $pos) = $wmatch;
280 $this->log(LOG_INFO, "Checking webfinger '$target'");
283 $oprofile = Ostatus_profile::ensureWebfinger($target);
284 if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
287 $profile = $oprofile->localProfile();
288 } catch (OStatusShadowException $e) {
289 // This means we got a local user in the webfinger lookup
290 $profile = $e->profile;
291 } catch (Exception $e) {
292 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
296 assert($profile instanceof Profile);
298 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
299 ? $profile->getNickname() // TODO: we could do getBestName() or getFullname() here
301 $url = $profile->getUri();
302 if (!common_valid_http_url($url)) {
303 $url = $profile->getUrl();
305 $matches[$pos] = array('mentioned' => array($profile),
309 'length' => mb_strlen($target),
314 // Profile matches: @example.com/mublog/user
315 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)*)!',
318 PREG_OFFSET_CAPTURE)) {
319 foreach ($wmatches[1] as $wmatch) {
320 list($target, $pos) = $wmatch;
321 $schemes = array('http', 'https');
322 foreach ($schemes as $scheme) {
323 $url = "$scheme://$target";
324 $this->log(LOG_INFO, "Checking profile address '$url'");
326 $oprofile = Ostatus_profile::ensureProfileURL($url);
327 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
328 $profile = $oprofile->localProfile();
329 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
330 $profile->nickname : $target;
331 $matches[$pos] = array('mentioned' => array($profile),
335 'length' => mb_strlen($target),
336 'url' => $profile->getUrl());
339 } catch (Exception $e) {
340 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
346 foreach ($mentions as $i => $other) {
347 // If we share a common prefix with a local user, override it!
348 $pos = $other['position'];
349 if (isset($matches[$pos])) {
350 $mentions[$i] = $matches[$pos];
351 unset($matches[$pos]);
354 foreach ($matches as $mention) {
355 $mentions[] = $mention;
362 * Allow remote profile references to be used in commands:
363 * sub update@status.net
364 * whois evan@identi.ca
365 * reply http://identi.ca/evan hey what's up
367 * @param Command $command
369 * @param Profile &$profile
370 * @return hook return code
372 function onStartCommandGetProfile($command, $arg, &$profile)
374 $oprofile = $this->pullRemoteProfile($arg);
375 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
377 $profile = $oprofile->localProfile();
378 } catch (NoProfileException $e) {
379 // No locally stored profile found for remote profile
389 * Allow remote group references to be used in commands:
390 * join group+statusnet@identi.ca
391 * join http://identi.ca/group/statusnet
392 * drop identi.ca/group/statusnet
394 * @param Command $command
396 * @param User_group &$group
397 * @return hook return code
399 function onStartCommandGetGroup($command, $arg, &$group)
401 $oprofile = $this->pullRemoteProfile($arg);
402 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
403 $group = $oprofile->localGroup();
410 protected function pullRemoteProfile($arg)
413 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
416 return Ostatus_profile::ensureWebfinger($arg);
417 } catch (Exception $e) {
418 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
419 $arg . ': ' . $e->getMessage());
423 // Look for profile URLs, with or without scheme:
425 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
428 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
429 $schemes = array('http', 'https');
430 foreach ($schemes as $scheme) {
431 $urls[] = "$scheme://$arg";
435 foreach ($urls as $url) {
437 return Ostatus_profile::ensureProfileURL($url);
438 } catch (Exception $e) {
439 common_log(LOG_ERR, 'Profile lookup failed for ' .
440 $arg . ': ' . $e->getMessage());
446 function onEndProfileSettingsActions($out) {
447 $siteName = common_config('site', 'name');
448 $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('ostatussub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
449 $out->elementStart('li');
451 array('href' => 'javascript:'.$js),
452 // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
453 _('Add to Firefox as feedreader'));
454 $out->elementEnd('li');
458 * Make sure necessary tables are filled out.
460 function onCheckSchema() {
461 $schema = Schema::get();
462 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
463 $schema->ensureTable('feedsub', FeedSub::schemaDef());
464 $schema->ensureTable('hubsub', HubSub::schemaDef());
465 $schema->ensureTable('magicsig', Magicsig::schemaDef());
469 public function onEndShowStylesheets(Action $action) {
470 $action->cssLink($this->path('theme/base/css/ostatus.css'));
474 function onEndShowStatusNetScripts($action) {
475 $action->script($this->path('js/ostatus.js'));
480 * Override the "from ostatus" bit in notice lists to link to the
481 * original post and show the domain it came from.
483 * @param Notice in $notice
484 * @param string out &$name
485 * @param string out &$url
486 * @param string out &$title
487 * @return mixed hook return code
489 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
491 // If we don't handle this, keep the event handler going
492 if (!in_array($notice->source, array('ostatus', 'share'))) {
497 $url = $notice->getUrl();
498 // If getUrl() throws exception, $url is never set
500 $bits = parse_url($url);
501 $domain = $bits['host'];
502 if (substr($domain, 0, 4) == 'www.') {
503 $name = substr($domain, 4);
508 // TRANS: Title. %s is a domain name.
509 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
511 // Abort event handler, we have a name and URL!
513 } catch (InvalidUrlException $e) {
514 // This just means we don't have the notice source data
520 * Send incoming PuSH feeds for OStatus endpoints in for processing.
522 * @param FeedSub $feedsub
523 * @param DOMDocument $feed
524 * @return mixed hook return code
526 function onStartFeedSubReceive($feedsub, $feed)
528 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
529 if ($oprofile instanceof Ostatus_profile) {
530 $oprofile->processFeed($feed, 'push');
532 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
537 * Tell the FeedSub infrastructure whether we have any active OStatus
538 * usage for the feed; if not it'll be able to garbage-collect the
541 * @param FeedSub $feedsub
542 * @param integer $count in/out
543 * @return mixed hook return code
545 function onFeedSubSubscriberCount($feedsub, &$count)
547 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
548 if ($oprofile instanceof Ostatus_profile) {
549 $count += $oprofile->subscriberCount();
555 * When about to subscribe to a remote user, start a server-to-server
556 * PuSH subscription if needed. If we can't establish that, abort.
558 * @fixme If something else aborts later, we could end up with a stray
559 * PuSH subscription. This is relatively harmless, though.
561 * @param Profile $profile subscriber
562 * @param Profile $other subscribee
564 * @return hook return code
568 function onStartSubscribe(Profile $profile, Profile $other)
570 if (!$profile->isLocal()) {
574 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
575 if (!$oprofile instanceof Ostatus_profile) {
579 $oprofile->subscribe();
583 * Having established a remote subscription, send a notification to the
584 * remote OStatus profile's endpoint.
586 * @param Profile $profile subscriber
587 * @param Profile $other subscribee
589 * @return hook return code
593 function onEndSubscribe(Profile $profile, Profile $other)
595 if (!$profile->isLocal()) {
599 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
600 if (!$oprofile instanceof Ostatus_profile) {
604 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
605 'subscribed' => $other->id));
607 $act = $sub->asActivity();
609 $oprofile->notifyActivity($act, $profile);
615 * Notify remote server and garbage collect unused feeds on unsubscribe.
616 * @todo FIXME: Send these operations to background queues
619 * @param Profile $other
620 * @return hook return value
622 function onEndUnsubscribe(Profile $profile, Profile $other)
624 if (!$profile->isLocal()) {
628 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
629 if (!$oprofile instanceof Ostatus_profile) {
633 // Drop the PuSH subscription if there are no other subscribers.
634 $oprofile->garbageCollect();
636 $act = new Activity();
638 $act->verb = ActivityVerb::UNFOLLOW;
640 $act->id = TagURI::mint('unfollow:%d:%d:%s',
643 common_date_iso8601(time()));
646 // TRANS: Title for unfollowing a remote profile.
647 $act->title = _m('TITLE','Unfollow');
648 // TRANS: Success message for unsubscribe from user attempt through OStatus.
649 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
650 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
651 $profile->getBestName(),
652 $other->getBestName());
654 $act->actor = $profile->asActivityObject();
655 $act->objects[] = $other->asActivityObject();
657 $oprofile->notifyActivity($act, $profile);
663 * When one of our local users tries to join a remote group,
664 * notify the remote server. If the notification is rejected,
667 * @param User_group $group
668 * @param Profile $profile
670 * @return mixed hook return value
671 * @throws Exception of various kinds, some from $oprofile->subscribe();
673 function onStartJoinGroup($group, $profile)
675 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
676 if (!$oprofile instanceof Ostatus_profile) {
680 $oprofile->subscribe();
682 // NOTE: we don't use Group_member::asActivity() since that record
683 // has not yet been created.
685 $act = new Activity();
686 $act->id = TagURI::mint('join:%d:%d:%s',
689 common_date_iso8601(time()));
691 $act->actor = $profile->asActivityObject();
692 $act->verb = ActivityVerb::JOIN;
693 $act->objects[] = $oprofile->asActivityObject();
696 // TRANS: Title for joining a remote groep.
697 $act->title = _m('TITLE','Join');
698 // TRANS: Success message for subscribe to group attempt through OStatus.
699 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
700 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
701 $profile->getBestName(),
702 $oprofile->getBestName());
704 if ($oprofile->notifyActivity($act, $profile)) {
707 $oprofile->garbageCollect();
708 // TRANS: Exception thrown when joining a remote group fails.
709 throw new Exception(_m('Failed joining remote group.'));
714 * When one of our local users leaves a remote group, notify the remote
717 * @fixme Might be good to schedule a resend of the leave notification
718 * if it failed due to a transitory error. We've canceled the local
719 * membership already anyway, but if the remote server comes back up
720 * it'll be left with a stray membership record.
722 * @param User_group $group
723 * @param Profile $profile
725 * @return mixed hook return value
727 function onEndLeaveGroup($group, $profile)
729 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
730 if (!$oprofile instanceof Ostatus_profile) {
734 // Drop the PuSH subscription if there are no other subscribers.
735 $oprofile->garbageCollect();
739 $act = new Activity();
740 $act->id = TagURI::mint('leave:%d:%d:%s',
743 common_date_iso8601(time()));
745 $act->actor = $member->asActivityObject();
746 $act->verb = ActivityVerb::LEAVE;
747 $act->objects[] = $oprofile->asActivityObject();
750 // TRANS: Title for leaving a remote group.
751 $act->title = _m('TITLE','Leave');
752 // TRANS: Success message for unsubscribe from group attempt through OStatus.
753 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
754 $act->content = sprintf(_m('%1$s has left group %2$s.'),
755 $member->getBestName(),
756 $oprofile->getBestName());
758 $oprofile->notifyActivity($act, $member);
762 * When one of our local users tries to subscribe to a remote peopletag,
763 * notify the remote server. If the notification is rejected,
764 * deny the subscription.
766 * @param Profile_list $peopletag
769 * @return mixed hook return value
770 * @throws Exception of various kinds, some from $oprofile->subscribe();
773 function onStartSubscribePeopletag($peopletag, $user)
775 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
776 if (!$oprofile instanceof Ostatus_profile) {
780 $oprofile->subscribe();
782 $sub = $user->getProfile();
783 $tagger = Profile::getKV($peopletag->tagger);
785 $act = new Activity();
786 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
789 common_date_iso8601(time()));
791 $act->actor = $sub->asActivityObject();
792 $act->verb = ActivityVerb::FOLLOW;
793 $act->objects[] = $oprofile->asActivityObject();
796 // TRANS: Title for following a remote list.
797 $act->title = _m('TITLE','Follow list');
798 // TRANS: Success message for remote list follow through OStatus.
799 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
800 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
802 $oprofile->getBestName(),
803 $tagger->getBestName());
805 if ($oprofile->notifyActivity($act, $sub)) {
808 $oprofile->garbageCollect();
809 // TRANS: Exception thrown when subscription to remote list fails.
810 throw new Exception(_m('Failed subscribing to remote list.'));
815 * When one of our local users unsubscribes to a remote peopletag, notify the remote
818 * @param Profile_list $peopletag
821 * @return mixed hook return value
824 function onEndUnsubscribePeopletag($peopletag, $user)
826 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
827 if (!$oprofile instanceof Ostatus_profile) {
831 // Drop the PuSH subscription if there are no other subscribers.
832 $oprofile->garbageCollect();
834 $sub = Profile::getKV($user->id);
835 $tagger = Profile::getKV($peopletag->tagger);
837 $act = new Activity();
838 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
841 common_date_iso8601(time()));
843 $act->actor = $member->asActivityObject();
844 $act->verb = ActivityVerb::UNFOLLOW;
845 $act->objects[] = $oprofile->asActivityObject();
848 // TRANS: Title for unfollowing a remote list.
849 $act->title = _m('Unfollow list');
850 // TRANS: Success message for remote list unfollow through OStatus.
851 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
852 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
854 $oprofile->getBestName(),
855 $tagger->getBestName());
857 $oprofile->notifyActivity($act, $user);
861 * Notify remote users when their notices get favorited.
863 * @param Profile or User $profile of local user doing the faving
864 * @param Notice $notice being favored
865 * @return hook return value
867 function onEndFavorNotice(Profile $profile, Notice $notice)
869 // Only distribute local users' favor actions, remote users
870 // will have already distributed theirs.
871 if (!$profile->isLocal()) {
875 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
876 if (!$oprofile instanceof Ostatus_profile) {
880 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
881 'notice_id' => $notice->id));
883 if (!$fav instanceof Fave) {
885 // TODO: Make pkeyGet throw exception, since this is a critical failure.
889 $act = $fav->asActivity();
891 $oprofile->notifyActivity($act, $profile);
897 * Notify remote user it has got a new people tag
898 * - tag verb is queued
899 * - the subscription is done immediately if not present
901 * @param Profile_tag $ptag the people tag that was created
902 * @return hook return value
903 * @throws Exception of various kinds, some from $oprofile->subscribe();
905 function onEndTagProfile($ptag)
907 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
908 if (!$oprofile instanceof Ostatus_profile) {
912 $plist = $ptag->getMeta();
913 if ($plist->private) {
917 $act = new Activity();
919 $tagger = $plist->getTagger();
920 $tagged = Profile::getKV('id', $ptag->tagged);
922 $act->verb = ActivityVerb::TAG;
923 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
924 $plist->tagger, $plist->id,
925 common_date_iso8601(time()));
927 // TRANS: Title for listing a remote profile.
928 $act->title = _m('TITLE','List');
929 // TRANS: Success message for remote list addition through OStatus.
930 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
931 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
932 $tagger->getBestName(),
933 $tagged->getBestName(),
934 $plist->getBestName());
936 $act->actor = $tagger->asActivityObject();
937 $act->objects = array($tagged->asActivityObject());
938 $act->target = ActivityObject::fromPeopletag($plist);
940 $oprofile->notifyDeferred($act, $tagger);
942 // initiate a PuSH subscription for the person being tagged
943 $oprofile->subscribe();
948 * Notify remote user that a people tag has been removed
949 * - untag verb is queued
950 * - the subscription is undone immediately if not required
951 * i.e garbageCollect()'d
953 * @param Profile_tag $ptag the people tag that was deleted
954 * @return hook return value
956 function onEndUntagProfile($ptag)
958 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
959 if (!$oprofile instanceof Ostatus_profile) {
963 $plist = $ptag->getMeta();
964 if ($plist->private) {
968 $act = new Activity();
970 $tagger = $plist->getTagger();
971 $tagged = Profile::getKV('id', $ptag->tagged);
973 $act->verb = ActivityVerb::UNTAG;
974 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
975 $plist->tagger, $plist->id,
976 common_date_iso8601(time()));
978 // TRANS: Title for unlisting a remote profile.
979 $act->title = _m('TITLE','Unlist');
980 // TRANS: Success message for remote list removal through OStatus.
981 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
982 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
983 $tagger->getBestName(),
984 $tagged->getBestName(),
985 $plist->getBestName());
987 $act->actor = $tagger->asActivityObject();
988 $act->objects = array($tagged->asActivityObject());
989 $act->target = ActivityObject::fromPeopletag($plist);
991 $oprofile->notifyDeferred($act, $tagger);
993 // unsubscribe to PuSH feed if no more required
994 $oprofile->garbageCollect();
1000 * Notify remote users when their notices get de-favorited.
1002 * @param Profile $profile Profile person doing the de-faving
1003 * @param Notice $notice Notice being favored
1005 * @return hook return value
1007 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1009 // Only distribute local users' disfavor actions, remote users
1010 // will have already distributed theirs.
1011 if (!$profile->isLocal()) {
1015 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1016 if (!$oprofile instanceof Ostatus_profile) {
1020 $act = new Activity();
1022 $act->verb = ActivityVerb::UNFAVORITE;
1023 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1026 common_date_iso8601(time()));
1027 $act->time = time();
1028 // TRANS: Title for unliking a remote notice.
1029 $act->title = _m('Unlike');
1030 // TRANS: Success message for remove a favorite notice through OStatus.
1031 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1032 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1033 $profile->getBestName(),
1036 $act->actor = $profile->asActivityObject();
1037 $act->objects[] = $notice->asActivityObject();
1039 $oprofile->notifyActivity($act, $profile);
1044 function onStartGetProfileUri($profile, &$uri)
1046 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1047 if ($oprofile instanceof Ostatus_profile) {
1048 $uri = $oprofile->uri;
1054 function onStartUserGroupHomeUrl($group, &$url)
1056 return $this->onStartUserGroupPermalink($group, $url);
1059 function onStartUserGroupPermalink($group, &$url)
1061 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1062 if ($oprofile instanceof Ostatus_profile) {
1063 // @fixme this should probably be in the user_group table
1064 // @fixme this uri not guaranteed to be a profile page
1065 $url = $oprofile->uri;
1070 function onStartShowSubscriptionsContent($action)
1072 $this->showEntityRemoteSubscribe($action);
1077 function onStartShowUserGroupsContent($action)
1079 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1084 function onEndShowSubscriptionsMiniList($action)
1086 $this->showEntityRemoteSubscribe($action);
1091 function onEndShowGroupsMiniList($action)
1093 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1098 function showEntityRemoteSubscribe($action, $target='ostatussub')
1100 if (!$action->getScoped() instanceof Profile) {
1101 // early return if we're not logged in
1105 if ($action->getScoped()->sameAs($action->getTarget())) {
1106 $action->elementStart('div', 'entity_actions');
1107 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1108 'class' => 'entity_subscribe'));
1109 $action->element('a', array('href' => common_local_url($target),
1110 'class' => 'entity_remote_subscribe'),
1111 // TRANS: Link text for link to remote subscribe.
1113 $action->elementEnd('p');
1114 $action->elementEnd('div');
1119 * Ping remote profiles with updates to this profile.
1120 * Salmon pings are queued for background processing.
1122 function onEndBroadcastProfile(Profile $profile)
1124 $user = User::getKV('id', $profile->id);
1126 // Find foreign accounts I'm subscribed to that support Salmon pings.
1128 // @fixme we could run updates through the PuSH feed too,
1129 // in which case we can skip Salmon pings to folks who
1130 // are also subscribed to me.
1131 $sql = "SELECT * FROM ostatus_profile " .
1132 "WHERE profile_id IN " .
1133 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1135 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1136 $oprofile = new Ostatus_profile();
1137 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1139 if ($oprofile->N == 0) {
1140 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1144 $act = new Activity();
1146 $act->verb = ActivityVerb::UPDATE_PROFILE;
1147 $act->id = TagURI::mint('update-profile:%d:%s',
1149 common_date_iso8601(time()));
1150 $act->time = time();
1151 // TRANS: Title for activity.
1152 $act->title = _m('Profile update');
1153 // TRANS: Ping text for remote profile update through OStatus.
1154 // TRANS: %s is user that updated their profile.
1155 $act->content = sprintf(_m('%s has updated their profile page.'),
1156 $profile->getBestName());
1158 $act->actor = $profile->asActivityObject();
1159 $act->objects[] = $act->actor;
1161 while ($oprofile->fetch()) {
1162 $oprofile->notifyDeferred($act, $profile);
1168 // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1169 function onStartProfileListItemActionElements($item)
1171 if (common_logged_in()) {
1172 // only non-logged in users get to see the "remote subscribe" form
1174 } elseif (!$item->getTarget()->isLocal()) {
1175 // we can (for now) only provide remote subscribe forms for local users
1179 if ($item instanceof ProfileAction) {
1181 } elseif ($item instanceof Widget) {
1182 $output = $item->out;
1184 // Bad $item class, don't know how to use this for outputting!
1185 throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1188 // Add an OStatus subscribe
1189 $output->elementStart('li', 'entity_subscribe');
1190 $url = common_local_url('ostatusinit',
1191 array('nickname' => $item->getTarget()->getNickname()));
1192 $output->element('a', array('href' => $url,
1193 'class' => 'entity_remote_subscribe'),
1194 // TRANS: Link text for a user to subscribe to an OStatus user.
1196 $output->elementEnd('li');
1198 $output->elementStart('li', 'entity_tag');
1199 $url = common_local_url('ostatustag',
1200 array('nickname' => $item->getTarget()->getNickname()));
1201 $output->element('a', array('href' => $url,
1202 'class' => 'entity_remote_tag'),
1203 // TRANS: Link text for a user to list an OStatus user.
1205 $output->elementEnd('li');
1210 function onPluginVersion(array &$versions)
1212 $versions[] = array('name' => 'OStatus',
1213 'version' => GNUSOCIAL_VERSION,
1214 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1215 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/OStatus',
1216 // TRANS: Plugin description.
1217 'rawdescription' => _m('Follow people across social networks that implement '.
1218 '<a href="http://ostatus.org/">OStatus</a>.'));
1224 * Utility function to check if the given URI is a canonical group profile
1225 * page, and if so return the ID number.
1227 * @param string $url
1228 * @return mixed int or false
1230 public static function localGroupFromUrl($url)
1232 $group = User_group::getKV('uri', $url);
1233 if ($group instanceof User_group) {
1234 if ($group->isLocal()) {
1238 // To find local groups which haven't had their uri fields filled out...
1239 // If the domain has changed since a subscriber got the URI, it'll
1241 $template = common_local_url('groupbyid', array('id' => '31337'));
1242 $template = preg_quote($template, '/');
1243 $template = str_replace('31337', '(\d+)', $template);
1244 if (preg_match("/$template/", $url, $matches)) {
1245 return intval($matches[1]);
1251 public function onStartProfileGetAtomFeed($profile, &$feed)
1253 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1255 if (!$oprofile instanceof Ostatus_profile) {
1259 $feed = $oprofile->feeduri;
1263 function onStartGetProfileFromURI($uri, &$profile)
1265 // Don't want to do Web-based discovery on our own server,
1266 // so we check locally first. This duplicates the functionality
1267 // in the Profile class, since the plugin always runs before
1268 // that local lookup, but since we return false it won't run double.
1270 $user = User::getKV('uri', $uri);
1271 if ($user instanceof User) {
1272 $profile = $user->getProfile();
1275 $group = User_group::getKV('uri', $uri);
1276 if ($group instanceof User_group) {
1277 $profile = $group->getProfile();
1282 // Now, check remotely
1284 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1285 $profile = $oprofile->localProfile();
1286 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1287 } catch (Exception $e) {
1288 return true; // It's not an OStatus profile as far as we know, continue event handling
1292 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1295 $actor = $target->getProfile();
1296 if ($actor->isLocal()) {
1297 $profiletype = $this->profileTypeString($actor);
1298 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $actor->getID()));
1301 $oprofile = Ostatus_profile::fromProfile($actor);
1302 $salmon_url = $oprofile->salmonuri;
1303 } catch (Exception $e) {
1304 // Even though it's not a local user, we couldn't get an Ostatus_profile?!
1307 // Ostatus_profile salmon URL may be empty
1308 if (!empty($salmon_url)) {
1309 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1314 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1316 if ($target->getObjectType() === ActivityObject::PERSON) {
1317 $this->addWebFingerPersonLinks($xrd, $target);
1318 } elseif ($target->getObjectType() === ActivityObject::GROUP) {
1319 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1320 common_local_url('ApiTimelineGroup',
1321 array('id' => $target->getGroup()->getID(), 'format' => 'atom')),
1322 'application/atom+xml');
1327 $profiletype = $this->profileTypeString($target);
1328 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1330 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1332 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1333 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1334 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1336 // TODO - finalize where the redirect should go on the publisher
1337 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1338 common_local_url('ostatussub') . '?profile={uri}',
1339 null, // type not set
1340 true); // isTemplate
1345 protected function profileTypeString(Profile $target)
1347 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1348 switch ($target->getObjectType()) {
1349 case ActivityObject::PERSON:
1351 case ActivityObject::GROUP:
1354 throw new ServerException('Unknown profile type for WebFinger profile links');
1358 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1360 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1361 common_local_url('ApiTimelineUser',
1362 array('id' => $target->id, 'format' => 'atom')),
1363 'application/atom+xml');
1365 // Get this profile's keypair
1366 $magicsig = Magicsig::getKV('user_id', $target->id);
1367 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1368 $magicsig = Magicsig::generate($target->getUser());
1371 if (!$magicsig instanceof Magicsig) {
1372 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1374 if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1375 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1376 'data:application/magic-public-key,'. $magicsig->toString());
1377 // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1378 Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1382 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1384 list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
1387 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1388 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1391 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1392 $profile = $oprofile->checkAuthorship($activity);
1393 } catch (Exception $e) {
1394 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1401 public function onProfileDeleteRelated($profile, &$related)
1403 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1404 $related[] = 'Ostatus_profile';
1406 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1407 $magicsig = Magicsig::getKV('user_id', $profile->id);
1408 if ($magicsig instanceof Magicsig) {
1409 $magicsig->delete();
1414 public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
1417 $envxml = $magic_env->toXML($target);
1418 } catch (Exception $e) {
1419 common_log(LOG_ERR, sprintf('Could not generate Magic Envelope XML for profile id=='.$target->getID().': '.$e->getMessage()));
1423 $headers = array('Content-Type: application/magic-envelope+xml');
1426 $client = new HTTPClient();
1427 $client->setBody($envxml);
1428 $response = $client->post($endpoint_uri, $headers);
1429 } catch (Exception $e) {
1430 common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
1433 if ($response->getStatus() === 422) {
1434 common_debug(sprintf('Salmon (from profile %d) endpoint %s returned status %s. We assume it is a Diaspora seed; will adapt and try again if that plugin is enabled!', $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus()));
1438 // 200 OK is the best response
1439 // 202 Accepted is what we get from Diaspora for example
1440 if (!in_array($response->getStatus(), array(200, 202))) {
1441 common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
1442 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
1446 // Since we completed the salmon slap, we discontinue the event
1450 public function onCronDaily()
1453 $sub = FeedSub::renewalCheck();
1454 } catch (NoResultException $e) {
1455 common_log(LOG_INFO, "There were no expiring feeds.");
1459 $qm = QueueManager::get();
1460 while ($sub->fetch()) {
1461 $item = array('feedsub_id' => $sub->id);
1462 $qm->enqueue($item, 'pushrenew');