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 FeedSubException extends Exception
35 function __construct($msg=null)
37 $type = get_class($this);
39 parent::__construct("$type: $msg");
41 parent::__construct($type);
46 class OStatusPlugin extends Plugin
49 * Hook for RouterInitialized event.
51 * @param Net_URL_Mapper $m path-to-action mapper
52 * @return boolean hook return
54 function onRouterInitialized($m)
57 $m->connect('main/ostatustag',
58 array('action' => 'ostatustag'));
59 $m->connect('main/ostatustag?nickname=:nickname',
60 array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
61 $m->connect('main/ostatus/nickname/:nickname',
62 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
63 $m->connect('main/ostatus/group/:group',
64 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
65 $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
66 array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
67 'peopletag' => '[A-Za-z0-9_-]+'));
68 $m->connect('main/ostatus',
69 array('action' => 'ostatusinit'));
71 // Remote subscription actions
72 $m->connect('main/ostatussub',
73 array('action' => 'ostatussub'));
74 $m->connect('main/ostatusgroup',
75 array('action' => 'ostatusgroup'));
76 $m->connect('main/ostatuspeopletag',
77 array('action' => 'ostatuspeopletag'));
80 $m->connect('main/push/hub', array('action' => 'pushhub'));
82 $m->connect('main/push/callback/:feed',
83 array('action' => 'pushcallback'),
84 array('feed' => '[0-9]+'));
87 $m->connect('main/salmon/user/:id',
88 array('action' => 'usersalmon'),
89 array('id' => '[0-9]+'));
90 $m->connect('main/salmon/group/:id',
91 array('action' => 'groupsalmon'),
92 array('id' => '[0-9]+'));
93 $m->connect('main/salmon/peopletag/:id',
94 array('action' => 'peopletagsalmon'),
95 array('id' => '[0-9]+'));
100 * Set up queue handlers for outgoing hub pushes
101 * @param QueueManager $qm
102 * @return boolean hook return
104 function onEndInitializeQueueManager(QueueManager $qm)
106 // Prepare outgoing distributions after notice save.
107 $qm->connect('ostatus', 'OStatusQueueHandler');
109 // Outgoing from our internal PuSH hub
110 $qm->connect('hubconf', 'HubConfQueueHandler');
111 $qm->connect('hubprep', 'HubPrepQueueHandler');
113 $qm->connect('hubout', 'HubOutQueueHandler');
115 // Outgoing Salmon replies (when we don't need a return value)
116 $qm->connect('salmon', 'SalmonQueueHandler');
118 // Incoming from a foreign PuSH hub
119 $qm->connect('pushin', 'PushInQueueHandler');
124 * Put saved notices into the queue for pubsub distribution.
126 function onStartEnqueueNotice($notice, &$transports)
128 if ($notice->inScope(null)) {
129 // put our transport first, in case there's any conflict (like OMB)
130 array_unshift($transports, 'ostatus');
131 $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
133 // FIXME: we don't do privacy-controlled OStatus updates yet.
134 // once that happens, finer grain of control here.
135 $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
141 * Set up a PuSH hub link to our internal link for canonical timeline
142 * Atom feeds for users and groups.
144 function onStartApiAtom($feed)
148 if ($feed instanceof AtomUserNoticeFeed) {
149 $salmonAction = 'usersalmon';
150 $user = $feed->getUser();
152 $profile = $user->getProfile();
153 } else if ($feed instanceof AtomGroupNoticeFeed) {
154 $salmonAction = 'groupsalmon';
155 $group = $feed->getGroup();
157 } else if ($feed instanceof AtomListNoticeFeed) {
158 $salmonAction = 'peopletagsalmon';
159 $peopletag = $feed->getList();
160 $id = $peopletag->id;
166 $hub = common_config('ostatus', 'hub');
168 // Updates will be handled through our internal PuSH hub.
169 $hub = common_local_url('pushhub');
171 $feed->addLink($hub, array('rel' => 'hub'));
173 // Also, we'll add in the salmon link
174 $salmon = common_local_url($salmonAction, array('id' => $id));
175 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
177 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
178 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
179 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
186 * Add in an OStatus subscribe button
188 function onStartProfileRemoteSubscribe($output, $profile)
190 $this->onStartProfileListItemActionElements($output, $profile);
194 function onStartGroupSubscribe($widget, $group)
196 $cur = common_current_user();
199 $widget->out->elementStart('li', 'entity_subscribe');
201 $url = common_local_url('ostatusinit',
202 array('group' => $group->nickname));
203 $widget->out->element('a', array('href' => $url,
204 'class' => 'entity_remote_subscribe'),
205 // TRANS: Link to subscribe to a remote entity.
208 $widget->out->elementEnd('li');
215 function onStartSubscribePeopletagForm($output, $peopletag)
217 $cur = common_current_user();
220 $output->elementStart('li', 'entity_subscribe');
221 $profile = $peopletag->getTagger();
222 $url = common_local_url('ostatusinit',
223 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
224 $output->element('a', array('href' => $url,
225 'class' => 'entity_remote_subscribe'),
226 // TRANS: Link to subscribe to a remote entity.
229 $output->elementEnd('li');
236 function onStartTagProfileAction($action, $profile)
239 $uri = $action->trimmed('uri');
241 if (!$profile && $uri) {
243 if (Validate::email($uri)) {
244 $oprofile = Ostatus_profile::ensureWebfinger($uri);
245 } else if (Validate::uri($uri)) {
246 $oprofile = Ostatus_profile::ensureProfileURL($uri);
248 // TRANS: Exception in OStatus when invalid URI was entered.
249 throw new Exception(_m('Invalid URI.'));
252 // redirect to the new profile.
253 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
255 } catch (Exception $e) {
256 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
257 // TRANS: and example.net, as these are official standard domain names for use in examples.
258 $err = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
261 $action->showForm($err);
268 * If the field being looked for is URI look for the profile
270 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
271 if ($action->field == 'uri') {
272 $profile->joinAdd(array('id', 'user:id'));
273 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
276 if ($profile->N == 0) {
278 if (Validate::email($q)) {
279 $oprofile = Ostatus_profile::ensureWebfinger($q);
280 } else if (Validate::uri($q)) {
281 $oprofile = Ostatus_profile::ensureProfileURL($q);
283 // TRANS: Exception in OStatus when invalid URI was entered.
284 throw new Exception(_m('Invalid URI.'));
286 return $this->filter(array($oprofile->localProfile()));
288 } catch (Exception $e) {
289 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
290 // TRANS: and example.net, as these are official standard domain names for use in examples.
291 $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.");
301 * Find any explicit remote mentions. Accepted forms:
302 * Webfinger: @user@example.com
303 * Profile link: @example.com/mublog/user
304 * @param Profile $sender
305 * @param string $text input markup text
306 * @param array &$mention in/out param: set of found mentions
307 * @return boolean hook return value
309 function onEndFindMentions(Profile $sender, $text, &$mentions)
313 // Webfinger matches: @user@example.com
314 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
317 PREG_OFFSET_CAPTURE)) {
318 foreach ($wmatches[1] as $wmatch) {
319 list($target, $pos) = $wmatch;
320 $this->log(LOG_INFO, "Checking webfinger '$target'");
322 $oprofile = Ostatus_profile::ensureWebfinger($target);
323 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
324 $profile = $oprofile->localProfile();
325 $matches[$pos] = array('mentioned' => array($profile),
329 'url' => $profile->profileurl);
331 } catch (Exception $e) {
332 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
337 // Profile matches: @example.com/mublog/user
338 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
341 PREG_OFFSET_CAPTURE)) {
342 foreach ($wmatches[1] as $wmatch) {
343 list($target, $pos) = $wmatch;
344 $schemes = array('http', 'https');
345 foreach ($schemes as $scheme) {
346 $url = "$scheme://$target";
347 $this->log(LOG_INFO, "Checking profile address '$url'");
349 $oprofile = Ostatus_profile::ensureProfileURL($url);
350 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
351 $profile = $oprofile->localProfile();
352 $matches[$pos] = array('mentioned' => array($profile),
356 'url' => $profile->profileurl);
359 } catch (Exception $e) {
360 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
366 foreach ($mentions as $i => $other) {
367 // If we share a common prefix with a local user, override it!
368 $pos = $other['position'];
369 if (isset($matches[$pos])) {
370 $mentions[$i] = $matches[$pos];
371 unset($matches[$pos]);
374 foreach ($matches as $mention) {
375 $mentions[] = $mention;
382 * Allow remote profile references to be used in commands:
383 * sub update@status.net
384 * whois evan@identi.ca
385 * reply http://identi.ca/evan hey what's up
387 * @param Command $command
389 * @param Profile &$profile
390 * @return hook return code
392 function onStartCommandGetProfile($command, $arg, &$profile)
394 $oprofile = $this->pullRemoteProfile($arg);
395 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
397 $profile = $oprofile->localProfile();
398 } catch (NoProfileException $e) {
399 // No locally stored profile found for remote profile
409 * Allow remote group references to be used in commands:
410 * join group+statusnet@identi.ca
411 * join http://identi.ca/group/statusnet
412 * drop identi.ca/group/statusnet
414 * @param Command $command
416 * @param User_group &$group
417 * @return hook return code
419 function onStartCommandGetGroup($command, $arg, &$group)
421 $oprofile = $this->pullRemoteProfile($arg);
422 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
423 $group = $oprofile->localGroup();
430 protected function pullRemoteProfile($arg)
433 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
436 return Ostatus_profile::ensureWebfinger($arg);
437 } catch (Exception $e) {
438 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
439 $arg . ': ' . $e->getMessage());
443 // Look for profile URLs, with or without scheme:
445 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
448 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
449 $schemes = array('http', 'https');
450 foreach ($schemes as $scheme) {
451 $urls[] = "$scheme://$arg";
455 foreach ($urls as $url) {
457 return Ostatus_profile::ensureProfileURL($url);
458 } catch (Exception $e) {
459 common_log(LOG_ERR, 'Profile lookup failed for ' .
460 $arg . ': ' . $e->getMessage());
467 * Make sure necessary tables are filled out.
469 function onCheckSchema() {
470 $schema = Schema::get();
471 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
472 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
473 $schema->ensureTable('feedsub', FeedSub::schemaDef());
474 $schema->ensureTable('hubsub', HubSub::schemaDef());
475 $schema->ensureTable('magicsig', Magicsig::schemaDef());
479 public function onEndShowStylesheets(Action $action) {
480 $action->cssLink($this->path('theme/base/css/ostatus.css'));
484 function onEndShowStatusNetScripts($action) {
485 $action->script($this->path('js/ostatus.js'));
490 * Override the "from ostatus" bit in notice lists to link to the
491 * original post and show the domain it came from.
493 * @param Notice in $notice
494 * @param string out &$name
495 * @param string out &$url
496 * @param string out &$title
497 * @return mixed hook return code
499 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
501 // If we don't handle this, keep the event handler going
502 if ($notice->source != 'ostatus') {
507 $url = $notice->getUrl();
508 // If getUrl() throws exception, $url is never set
510 $bits = parse_url($url);
511 $domain = $bits['host'];
512 if (substr($domain, 0, 4) == 'www.') {
513 $name = substr($domain, 4);
518 // TRANS: Title. %s is a domain name.
519 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
521 // Abort event handler, we have a name and URL!
523 } catch (InvalidUrlException $e) {
524 // This just means we don't have the notice source data
530 * Send incoming PuSH feeds for OStatus endpoints in for processing.
532 * @param FeedSub $feedsub
533 * @param DOMDocument $feed
534 * @return mixed hook return code
536 function onStartFeedSubReceive($feedsub, $feed)
538 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
539 if ($oprofile instanceof Ostatus_profile) {
540 $oprofile->processFeed($feed, 'push');
542 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
547 * Tell the FeedSub infrastructure whether we have any active OStatus
548 * usage for the feed; if not it'll be able to garbage-collect the
551 * @param FeedSub $feedsub
552 * @param integer $count in/out
553 * @return mixed hook return code
555 function onFeedSubSubscriberCount($feedsub, &$count)
557 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
558 if ($oprofile instanceof Ostatus_profile) {
559 $count += $oprofile->subscriberCount();
565 * When about to subscribe to a remote user, start a server-to-server
566 * PuSH subscription if needed. If we can't establish that, abort.
568 * @fixme If something else aborts later, we could end up with a stray
569 * PuSH subscription. This is relatively harmless, though.
571 * @param Profile $profile subscriber
572 * @param Profile $other subscribee
574 * @return hook return code
578 function onStartSubscribe(Profile $profile, Profile $other)
580 if (!$profile->isLocal()) {
584 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
585 if (!$oprofile instanceof Ostatus_profile) {
589 $oprofile->subscribe();
593 * Having established a remote subscription, send a notification to the
594 * remote OStatus profile's endpoint.
596 * @param Profile $profile subscriber
597 * @param Profile $other subscribee
599 * @return hook return code
603 function onEndSubscribe(Profile $profile, Profile $other)
605 if (!$profile->isLocal()) {
609 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
610 if (!$oprofile instanceof Ostatus_profile) {
614 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
615 'subscribed' => $other->id));
617 $act = $sub->asActivity();
619 $oprofile->notifyActivity($act, $profile);
625 * Notify remote server and garbage collect unused feeds on unsubscribe.
626 * @todo FIXME: Send these operations to background queues
629 * @param Profile $other
630 * @return hook return value
632 function onEndUnsubscribe(Profile $profile, Profile $other)
634 if (!$profile->isLocal()) {
638 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
639 if (!$oprofile instanceof Ostatus_profile) {
643 // Drop the PuSH subscription if there are no other subscribers.
644 $oprofile->garbageCollect();
646 $act = new Activity();
648 $act->verb = ActivityVerb::UNFOLLOW;
650 $act->id = TagURI::mint('unfollow:%d:%d:%s',
653 common_date_iso8601(time()));
656 // TRANS: Title for unfollowing a remote profile.
657 $act->title = _m('TITLE','Unfollow');
658 // TRANS: Success message for unsubscribe from user attempt through OStatus.
659 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
660 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
661 $profile->getBestName(),
662 $other->getBestName());
664 $act->actor = $profile->asActivityObject();
665 $act->object = $other->asActivityObject();
667 $oprofile->notifyActivity($act, $profile);
673 * When one of our local users tries to join a remote group,
674 * notify the remote server. If the notification is rejected,
677 * @param User_group $group
678 * @param Profile $profile
680 * @return mixed hook return value
681 * @throws Exception of various kinds, some from $oprofile->subscribe();
683 function onStartJoinGroup($group, $profile)
685 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
686 if (!$oprofile instanceof Ostatus_profile) {
690 $oprofile->subscribe();
692 // NOTE: we don't use Group_member::asActivity() since that record
693 // has not yet been created.
695 $act = new Activity();
696 $act->id = TagURI::mint('join:%d:%d:%s',
699 common_date_iso8601(time()));
701 $act->actor = $profile->asActivityObject();
702 $act->verb = ActivityVerb::JOIN;
703 $act->object = $oprofile->asActivityObject();
706 // TRANS: Title for joining a remote groep.
707 $act->title = _m('TITLE','Join');
708 // TRANS: Success message for subscribe to group attempt through OStatus.
709 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
710 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
711 $profile->getBestName(),
712 $oprofile->getBestName());
714 if ($oprofile->notifyActivity($act, $profile)) {
717 $oprofile->garbageCollect();
718 // TRANS: Exception thrown when joining a remote group fails.
719 throw new Exception(_m('Failed joining remote group.'));
724 * When one of our local users leaves a remote group, notify the remote
727 * @fixme Might be good to schedule a resend of the leave notification
728 * if it failed due to a transitory error. We've canceled the local
729 * membership already anyway, but if the remote server comes back up
730 * it'll be left with a stray membership record.
732 * @param User_group $group
733 * @param Profile $profile
735 * @return mixed hook return value
737 function onEndLeaveGroup($group, $profile)
739 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
740 if (!$oprofile instanceof Ostatus_profile) {
744 // Drop the PuSH subscription if there are no other subscribers.
745 $oprofile->garbageCollect();
749 $act = new Activity();
750 $act->id = TagURI::mint('leave:%d:%d:%s',
753 common_date_iso8601(time()));
755 $act->actor = $member->asActivityObject();
756 $act->verb = ActivityVerb::LEAVE;
757 $act->object = $oprofile->asActivityObject();
760 // TRANS: Title for leaving a remote group.
761 $act->title = _m('TITLE','Leave');
762 // TRANS: Success message for unsubscribe from group attempt through OStatus.
763 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
764 $act->content = sprintf(_m('%1$s has left group %2$s.'),
765 $member->getBestName(),
766 $oprofile->getBestName());
768 $oprofile->notifyActivity($act, $member);
772 * When one of our local users tries to subscribe to a remote peopletag,
773 * notify the remote server. If the notification is rejected,
774 * deny the subscription.
776 * @param Profile_list $peopletag
779 * @return mixed hook return value
780 * @throws Exception of various kinds, some from $oprofile->subscribe();
783 function onStartSubscribePeopletag($peopletag, $user)
785 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
786 if (!$oprofile instanceof Ostatus_profile) {
790 $oprofile->subscribe();
792 $sub = $user->getProfile();
793 $tagger = Profile::getKV($peopletag->tagger);
795 $act = new Activity();
796 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
799 common_date_iso8601(time()));
801 $act->actor = $sub->asActivityObject();
802 $act->verb = ActivityVerb::FOLLOW;
803 $act->object = $oprofile->asActivityObject();
806 // TRANS: Title for following a remote list.
807 $act->title = _m('TITLE','Follow list');
808 // TRANS: Success message for remote list follow through OStatus.
809 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
810 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
812 $oprofile->getBestName(),
813 $tagger->getBestName());
815 if ($oprofile->notifyActivity($act, $sub)) {
818 $oprofile->garbageCollect();
819 // TRANS: Exception thrown when subscription to remote list fails.
820 throw new Exception(_m('Failed subscribing to remote list.'));
825 * When one of our local users unsubscribes to a remote peopletag, notify the remote
828 * @param Profile_list $peopletag
831 * @return mixed hook return value
834 function onEndUnsubscribePeopletag($peopletag, $user)
836 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
837 if (!$oprofile instanceof Ostatus_profile) {
841 // Drop the PuSH subscription if there are no other subscribers.
842 $oprofile->garbageCollect();
844 $sub = Profile::getKV($user->id);
845 $tagger = Profile::getKV($peopletag->tagger);
847 $act = new Activity();
848 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
851 common_date_iso8601(time()));
853 $act->actor = $member->asActivityObject();
854 $act->verb = ActivityVerb::UNFOLLOW;
855 $act->object = $oprofile->asActivityObject();
858 // TRANS: Title for unfollowing a remote list.
859 $act->title = _m('Unfollow list');
860 // TRANS: Success message for remote list unfollow through OStatus.
861 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
862 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
864 $oprofile->getBestName(),
865 $tagger->getBestName());
867 $oprofile->notifyActivity($act, $user);
871 * Notify remote users when their notices get favorited.
873 * @param Profile or User $profile of local user doing the faving
874 * @param Notice $notice being favored
875 * @return hook return value
877 function onEndFavorNotice(Profile $profile, Notice $notice)
879 // Only distribute local users' favor actions, remote users
880 // will have already distributed theirs.
881 if (!$profile->isLocal()) {
885 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
886 if (!$oprofile instanceof Ostatus_profile) {
890 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
891 'notice_id' => $notice->id));
893 if (!$fav instanceof Fave) {
895 // TODO: Make pkeyGet throw exception, since this is a critical failure.
899 $act = $fav->asActivity();
901 $oprofile->notifyActivity($act, $profile);
907 * Notify remote user it has got a new people tag
908 * - tag verb is queued
909 * - the subscription is done immediately if not present
911 * @param Profile_tag $ptag the people tag that was created
912 * @return hook return value
913 * @throws Exception of various kinds, some from $oprofile->subscribe();
915 function onEndTagProfile($ptag)
917 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
918 if (!$oprofile instanceof Ostatus_profile) {
922 $plist = $ptag->getMeta();
923 if ($plist->private) {
927 $act = new Activity();
929 $tagger = $plist->getTagger();
930 $tagged = Profile::getKV('id', $ptag->tagged);
932 $act->verb = ActivityVerb::TAG;
933 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
934 $plist->tagger, $plist->id,
935 common_date_iso8601(time()));
937 // TRANS: Title for listing a remote profile.
938 $act->title = _m('TITLE','List');
939 // TRANS: Success message for remote list addition through OStatus.
940 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
941 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
942 $tagger->getBestName(),
943 $tagged->getBestName(),
944 $plist->getBestName());
946 $act->actor = $tagger->asActivityObject();
947 $act->objects = array($tagged->asActivityObject());
948 $act->target = ActivityObject::fromPeopletag($plist);
950 $oprofile->notifyDeferred($act, $tagger);
952 // initiate a PuSH subscription for the person being tagged
953 $oprofile->subscribe();
958 * Notify remote user that a people tag has been removed
959 * - untag verb is queued
960 * - the subscription is undone immediately if not required
961 * i.e garbageCollect()'d
963 * @param Profile_tag $ptag the people tag that was deleted
964 * @return hook return value
966 function onEndUntagProfile($ptag)
968 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
969 if (!$oprofile instanceof Ostatus_profile) {
973 $plist = $ptag->getMeta();
974 if ($plist->private) {
978 $act = new Activity();
980 $tagger = $plist->getTagger();
981 $tagged = Profile::getKV('id', $ptag->tagged);
983 $act->verb = ActivityVerb::UNTAG;
984 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
985 $plist->tagger, $plist->id,
986 common_date_iso8601(time()));
988 // TRANS: Title for unlisting a remote profile.
989 $act->title = _m('TITLE','Unlist');
990 // TRANS: Success message for remote list removal through OStatus.
991 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
992 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
993 $tagger->getBestName(),
994 $tagged->getBestName(),
995 $plist->getBestName());
997 $act->actor = $tagger->asActivityObject();
998 $act->objects = array($tagged->asActivityObject());
999 $act->target = ActivityObject::fromPeopletag($plist);
1001 $oprofile->notifyDeferred($act, $tagger);
1003 // unsubscribe to PuSH feed if no more required
1004 $oprofile->garbageCollect();
1010 * Notify remote users when their notices get de-favorited.
1012 * @param Profile $profile Profile person doing the de-faving
1013 * @param Notice $notice Notice being favored
1015 * @return hook return value
1017 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1019 // Only distribute local users' disfavor actions, remote users
1020 // will have already distributed theirs.
1021 if (!$profile->isLocal()) {
1025 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1026 if (!$oprofile instanceof Ostatus_profile) {
1030 $act = new Activity();
1032 $act->verb = ActivityVerb::UNFAVORITE;
1033 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1036 common_date_iso8601(time()));
1037 $act->time = time();
1038 // TRANS: Title for unliking a remote notice.
1039 $act->title = _m('Unlike');
1040 // TRANS: Success message for remove a favorite notice through OStatus.
1041 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1042 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1043 $profile->getBestName(),
1046 $act->actor = $profile->asActivityObject();
1047 $act->object = $notice->asActivityObject();
1049 $oprofile->notifyActivity($act, $profile);
1054 function onStartGetProfileUri($profile, &$uri)
1056 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1057 if ($oprofile instanceof Ostatus_profile) {
1058 $uri = $oprofile->uri;
1064 function onStartUserGroupHomeUrl($group, &$url)
1066 return $this->onStartUserGroupPermalink($group, $url);
1069 function onStartUserGroupPermalink($group, &$url)
1071 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1072 if ($oprofile instanceof Ostatus_profile) {
1073 // @fixme this should probably be in the user_group table
1074 // @fixme this uri not guaranteed to be a profile page
1075 $url = $oprofile->uri;
1080 function onStartShowSubscriptionsContent($action)
1082 $this->showEntityRemoteSubscribe($action);
1087 function onStartShowUserGroupsContent($action)
1089 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1094 function onEndShowSubscriptionsMiniList($action)
1096 $this->showEntityRemoteSubscribe($action);
1101 function onEndShowGroupsMiniList($action)
1103 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1108 function showEntityRemoteSubscribe($action, $target='ostatussub')
1110 $user = common_current_user();
1111 if ($user && ($user->id == $action->profile->id)) {
1112 $action->elementStart('div', 'entity_actions');
1113 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1114 'class' => 'entity_subscribe'));
1115 $action->element('a', array('href' => common_local_url($target),
1116 'class' => 'entity_remote_subscribe'),
1117 // TRANS: Link text for link to remote subscribe.
1119 $action->elementEnd('p');
1120 $action->elementEnd('div');
1125 * Ping remote profiles with updates to this profile.
1126 * Salmon pings are queued for background processing.
1128 function onEndBroadcastProfile(Profile $profile)
1130 $user = User::getKV('id', $profile->id);
1132 // Find foreign accounts I'm subscribed to that support Salmon pings.
1134 // @fixme we could run updates through the PuSH feed too,
1135 // in which case we can skip Salmon pings to folks who
1136 // are also subscribed to me.
1137 $sql = "SELECT * FROM ostatus_profile " .
1138 "WHERE profile_id IN " .
1139 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1141 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1142 $oprofile = new Ostatus_profile();
1143 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1145 if ($oprofile->N == 0) {
1146 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1150 $act = new Activity();
1152 $act->verb = ActivityVerb::UPDATE_PROFILE;
1153 $act->id = TagURI::mint('update-profile:%d:%s',
1155 common_date_iso8601(time()));
1156 $act->time = time();
1157 // TRANS: Title for activity.
1158 $act->title = _m('Profile update');
1159 // TRANS: Ping text for remote profile update through OStatus.
1160 // TRANS: %s is user that updated their profile.
1161 $act->content = sprintf(_m('%s has updated their profile page.'),
1162 $profile->getBestName());
1164 $act->actor = $profile->asActivityObject();
1165 $act->object = $act->actor;
1167 while ($oprofile->fetch()) {
1168 $oprofile->notifyDeferred($act, $profile);
1174 function onStartProfileListItemActionElements($item, $profile=null)
1176 if (!common_logged_in()) {
1178 $profileUser = User::getKV('id', $item->profile->id);
1180 if (!empty($profileUser)) {
1182 if ($item instanceof Action) {
1184 $profile = $item->profile;
1186 $output = $item->out;
1189 // Add an OStatus subscribe
1190 $output->elementStart('li', 'entity_subscribe');
1191 $url = common_local_url('ostatusinit',
1192 array('nickname' => $profileUser->nickname));
1193 $output->element('a', array('href' => $url,
1194 'class' => 'entity_remote_subscribe'),
1195 // TRANS: Link text for a user to subscribe to an OStatus user.
1197 $output->elementEnd('li');
1199 $output->elementStart('li', 'entity_tag');
1200 $url = common_local_url('ostatustag',
1201 array('nickname' => $profileUser->nickname));
1202 $output->element('a', array('href' => $url,
1203 'class' => 'entity_remote_tag'),
1204 // TRANS: Link text for a user to list an OStatus user.
1206 $output->elementEnd('li');
1213 function onPluginVersion(&$versions)
1215 $versions[] = array('name' => 'OStatus',
1216 'version' => GNUSOCIAL_VERSION,
1217 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1218 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1219 // TRANS: Plugin description.
1220 'rawdescription' => _m('Follow people across social networks that implement '.
1221 '<a href="http://ostatus.org/">OStatus</a>.'));
1227 * Utility function to check if the given URI is a canonical group profile
1228 * page, and if so return the ID number.
1230 * @param string $url
1231 * @return mixed int or false
1233 public static function localGroupFromUrl($url)
1235 $group = User_group::getKV('uri', $url);
1236 if ($group instanceof User_group) {
1237 if ($group->isLocal()) {
1241 // To find local groups which haven't had their uri fields filled out...
1242 // If the domain has changed since a subscriber got the URI, it'll
1244 $template = common_local_url('groupbyid', array('id' => '31337'));
1245 $template = preg_quote($template, '/');
1246 $template = str_replace('31337', '(\d+)', $template);
1247 if (preg_match("/$template/", $url, $matches)) {
1248 return intval($matches[1]);
1254 public function onStartProfileGetAtomFeed($profile, &$feed)
1256 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1258 if (!$oprofile instanceof Ostatus_profile) {
1262 $feed = $oprofile->feeduri;
1266 function onStartGetProfileFromURI($uri, &$profile)
1268 // Don't want to do Web-based discovery on our own server,
1269 // so we check locally first.
1271 $user = User::getKV('uri', $uri);
1273 if (!empty($user)) {
1274 $profile = $user->getProfile();
1278 // Now, check remotely
1281 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1282 $profile = $oprofile->localProfile();
1283 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1284 } catch (Exception $e) {
1285 return true; // It's not an OStatus profile as far as we know, continue event handling
1289 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1291 $author = $target->getProfile();
1292 $salmon_url = common_local_url('usersalmon', array('id' => $author->id));
1293 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1297 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1299 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1300 common_local_url('ApiTimelineUser',
1301 array('id' => $target->id, 'format' => 'atom')),
1302 'application/atom+xml');
1305 $salmon_url = common_local_url('usersalmon',
1306 array('id' => $target->id));
1308 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1310 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1311 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1312 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1314 // Get this profile's keypair
1315 $magicsig = Magicsig::getKV('user_id', $target->id);
1316 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1317 $magicsig = Magicsig::generate($target->getUser());
1320 if ($magicsig instanceof Magicsig) {
1321 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1322 'data:application/magic-public-key,'. $magicsig->toString());
1325 // TODO - finalize where the redirect should go on the publisher
1326 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1327 common_local_url('ostatussub') . '?profile={uri}',
1328 null, // type not set
1329 true); // isTemplate
1334 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1336 list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
1339 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1340 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1343 $oprofile = Ostatus_profile::getFromProfile($profile);
1344 $oprofile = $oprofile->checkAuthorship($activity);
1345 $profile = $oprofile->localProfile();
1346 } catch (Exception $e) {
1347 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'")');
1354 public function onProfileDeleteRelated($profile, &$related)
1356 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1357 $related[] = 'Ostatus_profile';