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 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phpseclib');
33 class OStatusPlugin extends Plugin
36 * Hook for RouterInitialized event.
38 * @param URLMapper $m path-to-action mapper
39 * @return boolean hook return
41 public function onRouterInitialized(URLMapper $m)
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'));
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'));
67 $m->connect('main/push/hub', array('action' => 'pushhub'));
69 $m->connect('main/push/callback/:feed',
70 array('action' => 'pushcallback'),
71 array('feed' => '[0-9]+'));
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]+'));
87 * Set up queue handlers for outgoing hub pushes
88 * @param QueueManager $qm
89 * @return boolean hook return
91 function onEndInitializeQueueManager(QueueManager $qm)
93 // Prepare outgoing distributions after notice save.
94 $qm->connect('ostatus', 'OStatusQueueHandler');
96 // Outgoing from our internal PuSH hub
97 $qm->connect('hubconf', 'HubConfQueueHandler');
98 $qm->connect('hubprep', 'HubPrepQueueHandler');
100 $qm->connect('hubout', 'HubOutQueueHandler');
102 // Outgoing Salmon replies (when we don't need a return value)
103 $qm->connect('salmon', 'SalmonQueueHandler');
105 // Incoming from a foreign PuSH hub
106 $qm->connect('pushin', 'PushInQueueHandler');
111 * Put saved notices into the queue for pubsub distribution.
113 function onStartEnqueueNotice($notice, &$transports)
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");
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}");
128 * Set up a PuSH hub link to our internal link for canonical timeline
129 * Atom feeds for users and groups.
131 function onStartApiAtom($feed)
135 if ($feed instanceof AtomUserNoticeFeed) {
136 $salmonAction = 'usersalmon';
137 $user = $feed->getUser();
139 $profile = $user->getProfile();
140 } else if ($feed instanceof AtomGroupNoticeFeed) {
141 $salmonAction = 'groupsalmon';
142 $group = $feed->getGroup();
144 } else if ($feed instanceof AtomListNoticeFeed) {
145 $salmonAction = 'peopletagsalmon';
146 $peopletag = $feed->getList();
147 $id = $peopletag->id;
153 $hub = common_config('ostatus', 'hub');
155 // Updates will be handled through our internal PuSH hub.
156 $hub = common_local_url('pushhub');
158 $feed->addLink($hub, array('rel' => 'hub'));
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));
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));
173 * Add in an OStatus subscribe button
175 function onStartProfileRemoteSubscribe($output, $profile)
177 $this->onStartProfileListItemActionElements($output, $profile);
181 function onStartGroupSubscribe($widget, $group)
183 $cur = common_current_user();
186 $widget->out->elementStart('li', 'entity_subscribe');
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.
195 $widget->out->elementEnd('li');
202 function onStartSubscribePeopletagForm($output, $peopletag)
204 $cur = common_current_user();
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.
216 $output->elementEnd('li');
224 * If the field being looked for is URI look for the profile
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) . '%"');
232 if ($profile->N == 0) {
234 if (Validate::email($q)) {
235 $oprofile = Ostatus_profile::ensureWebfinger($q);
236 } else if (Validate::uri($q)) {
237 $oprofile = Ostatus_profile::ensureProfileURL($q);
239 // TRANS: Exception in OStatus when invalid URI was entered.
240 throw new Exception(_m('Invalid URI.'));
242 return $this->filter(array($oprofile->localProfile()));
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.");
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
265 function onEndFindMentions(Profile $sender, $text, &$mentions)
269 // Webfinger matches: @user@example.com
270 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
273 PREG_OFFSET_CAPTURE)) {
274 foreach ($wmatches[1] as $wmatch) {
275 list($target, $pos) = $wmatch;
276 $this->log(LOG_INFO, "Checking webfinger '$target'");
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),
287 'length' => mb_strlen($target),
288 'url' => $profile->getUrl());
290 } catch (Exception $e) {
291 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
296 // Profile matches: @example.com/mublog/user
297 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)*)!',
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'");
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),
317 'length' => mb_strlen($target),
318 'url' => $profile->getUrl());
321 } catch (Exception $e) {
322 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
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]);
336 foreach ($matches as $mention) {
337 $mentions[] = $mention;
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
349 * @param Command $command
351 * @param Profile &$profile
352 * @return hook return code
354 function onStartCommandGetProfile($command, $arg, &$profile)
356 $oprofile = $this->pullRemoteProfile($arg);
357 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
359 $profile = $oprofile->localProfile();
360 } catch (NoProfileException $e) {
361 // No locally stored profile found for remote profile
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
376 * @param Command $command
378 * @param User_group &$group
379 * @return hook return code
381 function onStartCommandGetGroup($command, $arg, &$group)
383 $oprofile = $this->pullRemoteProfile($arg);
384 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
385 $group = $oprofile->localGroup();
392 protected function pullRemoteProfile($arg)
395 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
398 return Ostatus_profile::ensureWebfinger($arg);
399 } catch (Exception $e) {
400 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
401 $arg . ': ' . $e->getMessage());
405 // Look for profile URLs, with or without scheme:
407 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
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";
417 foreach ($urls as $url) {
419 return Ostatus_profile::ensureProfileURL($url);
420 } catch (Exception $e) {
421 common_log(LOG_ERR, 'Profile lookup failed for ' .
422 $arg . ': ' . $e->getMessage());
429 * Make sure necessary tables are filled out.
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());
441 public function onEndShowStylesheets(Action $action) {
442 $action->cssLink($this->path('theme/base/css/ostatus.css'));
446 function onEndShowStatusNetScripts($action) {
447 $action->script($this->path('js/ostatus.js'));
452 * Override the "from ostatus" bit in notice lists to link to the
453 * original post and show the domain it came from.
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
461 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
463 // If we don't handle this, keep the event handler going
464 if ($notice->source != 'ostatus') {
469 $url = $notice->getUrl();
470 // If getUrl() throws exception, $url is never set
472 $bits = parse_url($url);
473 $domain = $bits['host'];
474 if (substr($domain, 0, 4) == 'www.') {
475 $name = substr($domain, 4);
480 // TRANS: Title. %s is a domain name.
481 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
483 // Abort event handler, we have a name and URL!
485 } catch (InvalidUrlException $e) {
486 // This just means we don't have the notice source data
492 * Send incoming PuSH feeds for OStatus endpoints in for processing.
494 * @param FeedSub $feedsub
495 * @param DOMDocument $feed
496 * @return mixed hook return code
498 function onStartFeedSubReceive($feedsub, $feed)
500 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
501 if ($oprofile instanceof Ostatus_profile) {
502 $oprofile->processFeed($feed, 'push');
504 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
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
513 * @param FeedSub $feedsub
514 * @param integer $count in/out
515 * @return mixed hook return code
517 function onFeedSubSubscriberCount($feedsub, &$count)
519 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
520 if ($oprofile instanceof Ostatus_profile) {
521 $count += $oprofile->subscriberCount();
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.
530 * @fixme If something else aborts later, we could end up with a stray
531 * PuSH subscription. This is relatively harmless, though.
533 * @param Profile $profile subscriber
534 * @param Profile $other subscribee
536 * @return hook return code
540 function onStartSubscribe(Profile $profile, Profile $other)
542 if (!$profile->isLocal()) {
546 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
547 if (!$oprofile instanceof Ostatus_profile) {
551 $oprofile->subscribe();
555 * Having established a remote subscription, send a notification to the
556 * remote OStatus profile's endpoint.
558 * @param Profile $profile subscriber
559 * @param Profile $other subscribee
561 * @return hook return code
565 function onEndSubscribe(Profile $profile, Profile $other)
567 if (!$profile->isLocal()) {
571 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
572 if (!$oprofile instanceof Ostatus_profile) {
576 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
577 'subscribed' => $other->id));
579 $act = $sub->asActivity();
581 $oprofile->notifyActivity($act, $profile);
587 * Notify remote server and garbage collect unused feeds on unsubscribe.
588 * @todo FIXME: Send these operations to background queues
591 * @param Profile $other
592 * @return hook return value
594 function onEndUnsubscribe(Profile $profile, Profile $other)
596 if (!$profile->isLocal()) {
600 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
601 if (!$oprofile instanceof Ostatus_profile) {
605 // Drop the PuSH subscription if there are no other subscribers.
606 $oprofile->garbageCollect();
608 $act = new Activity();
610 $act->verb = ActivityVerb::UNFOLLOW;
612 $act->id = TagURI::mint('unfollow:%d:%d:%s',
615 common_date_iso8601(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());
626 $act->actor = $profile->asActivityObject();
627 $act->object = $other->asActivityObject();
629 $oprofile->notifyActivity($act, $profile);
635 * When one of our local users tries to join a remote group,
636 * notify the remote server. If the notification is rejected,
639 * @param User_group $group
640 * @param Profile $profile
642 * @return mixed hook return value
643 * @throws Exception of various kinds, some from $oprofile->subscribe();
645 function onStartJoinGroup($group, $profile)
647 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
648 if (!$oprofile instanceof Ostatus_profile) {
652 $oprofile->subscribe();
654 // NOTE: we don't use Group_member::asActivity() since that record
655 // has not yet been created.
657 $act = new Activity();
658 $act->id = TagURI::mint('join:%d:%d:%s',
661 common_date_iso8601(time()));
663 $act->actor = $profile->asActivityObject();
664 $act->verb = ActivityVerb::JOIN;
665 $act->object = $oprofile->asActivityObject();
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());
676 if ($oprofile->notifyActivity($act, $profile)) {
679 $oprofile->garbageCollect();
680 // TRANS: Exception thrown when joining a remote group fails.
681 throw new Exception(_m('Failed joining remote group.'));
686 * When one of our local users leaves a remote group, notify the remote
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.
694 * @param User_group $group
695 * @param Profile $profile
697 * @return mixed hook return value
699 function onEndLeaveGroup($group, $profile)
701 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
702 if (!$oprofile instanceof Ostatus_profile) {
706 // Drop the PuSH subscription if there are no other subscribers.
707 $oprofile->garbageCollect();
711 $act = new Activity();
712 $act->id = TagURI::mint('leave:%d:%d:%s',
715 common_date_iso8601(time()));
717 $act->actor = $member->asActivityObject();
718 $act->verb = ActivityVerb::LEAVE;
719 $act->object = $oprofile->asActivityObject();
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());
730 $oprofile->notifyActivity($act, $member);
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.
738 * @param Profile_list $peopletag
741 * @return mixed hook return value
742 * @throws Exception of various kinds, some from $oprofile->subscribe();
745 function onStartSubscribePeopletag($peopletag, $user)
747 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
748 if (!$oprofile instanceof Ostatus_profile) {
752 $oprofile->subscribe();
754 $sub = $user->getProfile();
755 $tagger = Profile::getKV($peopletag->tagger);
757 $act = new Activity();
758 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
761 common_date_iso8601(time()));
763 $act->actor = $sub->asActivityObject();
764 $act->verb = ActivityVerb::FOLLOW;
765 $act->object = $oprofile->asActivityObject();
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.'),
774 $oprofile->getBestName(),
775 $tagger->getBestName());
777 if ($oprofile->notifyActivity($act, $sub)) {
780 $oprofile->garbageCollect();
781 // TRANS: Exception thrown when subscription to remote list fails.
782 throw new Exception(_m('Failed subscribing to remote list.'));
787 * When one of our local users unsubscribes to a remote peopletag, notify the remote
790 * @param Profile_list $peopletag
793 * @return mixed hook return value
796 function onEndUnsubscribePeopletag($peopletag, $user)
798 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
799 if (!$oprofile instanceof Ostatus_profile) {
803 // Drop the PuSH subscription if there are no other subscribers.
804 $oprofile->garbageCollect();
806 $sub = Profile::getKV($user->id);
807 $tagger = Profile::getKV($peopletag->tagger);
809 $act = new Activity();
810 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
813 common_date_iso8601(time()));
815 $act->actor = $member->asActivityObject();
816 $act->verb = ActivityVerb::UNFOLLOW;
817 $act->object = $oprofile->asActivityObject();
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.'),
826 $oprofile->getBestName(),
827 $tagger->getBestName());
829 $oprofile->notifyActivity($act, $user);
833 * Notify remote users when their notices get favorited.
835 * @param Profile or User $profile of local user doing the faving
836 * @param Notice $notice being favored
837 * @return hook return value
839 function onEndFavorNotice(Profile $profile, Notice $notice)
841 // Only distribute local users' favor actions, remote users
842 // will have already distributed theirs.
843 if (!$profile->isLocal()) {
847 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
848 if (!$oprofile instanceof Ostatus_profile) {
852 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
853 'notice_id' => $notice->id));
855 if (!$fav instanceof Fave) {
857 // TODO: Make pkeyGet throw exception, since this is a critical failure.
861 $act = $fav->asActivity();
863 $oprofile->notifyActivity($act, $profile);
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
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();
877 function onEndTagProfile($ptag)
879 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
880 if (!$oprofile instanceof Ostatus_profile) {
884 $plist = $ptag->getMeta();
885 if ($plist->private) {
889 $act = new Activity();
891 $tagger = $plist->getTagger();
892 $tagged = Profile::getKV('id', $ptag->tagged);
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()));
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());
908 $act->actor = $tagger->asActivityObject();
909 $act->objects = array($tagged->asActivityObject());
910 $act->target = ActivityObject::fromPeopletag($plist);
912 $oprofile->notifyDeferred($act, $tagger);
914 // initiate a PuSH subscription for the person being tagged
915 $oprofile->subscribe();
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
925 * @param Profile_tag $ptag the people tag that was deleted
926 * @return hook return value
928 function onEndUntagProfile($ptag)
930 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
931 if (!$oprofile instanceof Ostatus_profile) {
935 $plist = $ptag->getMeta();
936 if ($plist->private) {
940 $act = new Activity();
942 $tagger = $plist->getTagger();
943 $tagged = Profile::getKV('id', $ptag->tagged);
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()));
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());
959 $act->actor = $tagger->asActivityObject();
960 $act->objects = array($tagged->asActivityObject());
961 $act->target = ActivityObject::fromPeopletag($plist);
963 $oprofile->notifyDeferred($act, $tagger);
965 // unsubscribe to PuSH feed if no more required
966 $oprofile->garbageCollect();
972 * Notify remote users when their notices get de-favorited.
974 * @param Profile $profile Profile person doing the de-faving
975 * @param Notice $notice Notice being favored
977 * @return hook return value
979 function onEndDisfavorNotice(Profile $profile, Notice $notice)
981 // Only distribute local users' disfavor actions, remote users
982 // will have already distributed theirs.
983 if (!$profile->isLocal()) {
987 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
988 if (!$oprofile instanceof Ostatus_profile) {
992 $act = new Activity();
994 $act->verb = ActivityVerb::UNFAVORITE;
995 $act->id = TagURI::mint('disfavor:%d:%d:%s',
998 common_date_iso8601(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(),
1008 $act->actor = $profile->asActivityObject();
1009 $act->object = $notice->asActivityObject();
1011 $oprofile->notifyActivity($act, $profile);
1016 function onStartGetProfileUri($profile, &$uri)
1018 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1019 if ($oprofile instanceof Ostatus_profile) {
1020 $uri = $oprofile->uri;
1026 function onStartUserGroupHomeUrl($group, &$url)
1028 return $this->onStartUserGroupPermalink($group, $url);
1031 function onStartUserGroupPermalink($group, &$url)
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;
1042 function onStartShowSubscriptionsContent($action)
1044 $this->showEntityRemoteSubscribe($action);
1049 function onStartShowUserGroupsContent($action)
1051 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1056 function onEndShowSubscriptionsMiniList($action)
1058 $this->showEntityRemoteSubscribe($action);
1063 function onEndShowGroupsMiniList($action)
1065 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1070 function showEntityRemoteSubscribe($action, $target='ostatussub')
1072 if (!$action->getScoped() instanceof Profile) {
1073 // early return if we're not logged in
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.
1085 $action->elementEnd('p');
1086 $action->elementEnd('div');
1091 * Ping remote profiles with updates to this profile.
1092 * Salmon pings are queued for background processing.
1094 function onEndBroadcastProfile(Profile $profile)
1096 $user = User::getKV('id', $profile->id);
1098 // Find foreign accounts I'm subscribed to that support Salmon pings.
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) " .
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));
1111 if ($oprofile->N == 0) {
1112 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1116 $act = new Activity();
1118 $act->verb = ActivityVerb::UPDATE_PROFILE;
1119 $act->id = TagURI::mint('update-profile:%d:%s',
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());
1130 $act->actor = $profile->asActivityObject();
1131 $act->object = $act->actor;
1133 while ($oprofile->fetch()) {
1134 $oprofile->notifyDeferred($act, $profile);
1140 // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1141 function onStartProfileListItemActionElements($item)
1143 if (common_logged_in()) {
1144 // only non-logged in users get to see the "remote subscribe" form
1146 } elseif (!$item->getTarget()->isLocal()) {
1147 // we can (for now) only provide remote subscribe forms for local users
1151 if ($item instanceof ProfileAction) {
1153 } elseif ($item instanceof Widget) {
1154 $output = $item->out;
1156 // Bad $item class, don't know how to use this for outputting!
1157 throw new ServerException('Bad item type for onStartProfileListItemActionElements');
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.
1168 $output->elementEnd('li');
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.
1177 $output->elementEnd('li');
1182 function onPluginVersion(array &$versions)
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>.'));
1196 * Utility function to check if the given URI is a canonical group profile
1197 * page, and if so return the ID number.
1199 * @param string $url
1200 * @return mixed int or false
1202 public static function localGroupFromUrl($url)
1204 $group = User_group::getKV('uri', $url);
1205 if ($group instanceof User_group) {
1206 if ($group->isLocal()) {
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
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]);
1223 public function onStartProfileGetAtomFeed($profile, &$feed)
1225 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1227 if (!$oprofile instanceof Ostatus_profile) {
1231 $feed = $oprofile->feeduri;
1235 function onStartGetProfileFromURI($uri, &$profile)
1237 // Don't want to do Web-based discovery on our own server,
1238 // so we check locally first.
1240 $user = User::getKV('uri', $uri);
1242 if (!empty($user)) {
1243 $profile = $user->getProfile();
1247 // Now, check remotely
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
1258 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
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);
1267 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1269 if ($target->getObjectType() === ActivityObject::PERSON) {
1270 $this->addWebFingerPersonLinks($xrd, $target);
1274 $profiletype = $this->profileTypeString($target);
1275 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1277 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
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);
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
1292 protected function profileTypeString(Profile $target)
1294 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1295 switch ($target->getObjectType()) {
1296 case ActivityObject::PERSON:
1298 case ActivityObject::GROUP:
1301 throw new ServerException('Unknown profile type for WebFinger profile links');
1305 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
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');
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());
1318 if (!$magicsig instanceof Magicsig) {
1319 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
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));
1329 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1331 list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
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)
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);
1348 public function onProfileDeleteRelated($profile, &$related)
1350 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1351 $related[] = 'Ostatus_profile';
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();