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 URLMapper $m path-to-action mapper
52 * @return boolean hook return
54 public function onRouterInitialized(URLMapper $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');
237 * If the field being looked for is URI look for the profile
239 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
240 if ($action->field == 'uri') {
241 $profile->joinAdd(array('id', 'user:id'));
242 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
245 if ($profile->N == 0) {
247 if (Validate::email($q)) {
248 $oprofile = Ostatus_profile::ensureWebfinger($q);
249 } else if (Validate::uri($q)) {
250 $oprofile = Ostatus_profile::ensureProfileURL($q);
252 // TRANS: Exception in OStatus when invalid URI was entered.
253 throw new Exception(_m('Invalid URI.'));
255 return $this->filter(array($oprofile->localProfile()));
257 } catch (Exception $e) {
258 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
259 // TRANS: and example.net, as these are official standard domain names for use in examples.
260 $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.");
270 * Find any explicit remote mentions. Accepted forms:
271 * Webfinger: @user@example.com
272 * Profile link: @example.com/mublog/user
273 * @param Profile $sender
274 * @param string $text input markup text
275 * @param array &$mention in/out param: set of found mentions
276 * @return boolean hook return value
278 function onEndFindMentions(Profile $sender, $text, &$mentions)
282 // Webfinger matches: @user@example.com
283 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
286 PREG_OFFSET_CAPTURE)) {
287 foreach ($wmatches[1] as $wmatch) {
288 list($target, $pos) = $wmatch;
289 $this->log(LOG_INFO, "Checking webfinger '$target'");
291 $oprofile = Ostatus_profile::ensureWebfinger($target);
292 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
293 $profile = $oprofile->localProfile();
294 $matches[$pos] = array('mentioned' => array($profile),
298 'url' => $profile->getUrl());
300 } catch (Exception $e) {
301 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
306 // Profile matches: @example.com/mublog/user
307 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
310 PREG_OFFSET_CAPTURE)) {
311 foreach ($wmatches[1] as $wmatch) {
312 list($target, $pos) = $wmatch;
313 $schemes = array('http', 'https');
314 foreach ($schemes as $scheme) {
315 $url = "$scheme://$target";
316 $this->log(LOG_INFO, "Checking profile address '$url'");
318 $oprofile = Ostatus_profile::ensureProfileURL($url);
319 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
320 $profile = $oprofile->localProfile();
321 $matches[$pos] = array('mentioned' => array($profile),
325 'url' => $profile->getUrl());
328 } catch (Exception $e) {
329 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
335 foreach ($mentions as $i => $other) {
336 // If we share a common prefix with a local user, override it!
337 $pos = $other['position'];
338 if (isset($matches[$pos])) {
339 $mentions[$i] = $matches[$pos];
340 unset($matches[$pos]);
343 foreach ($matches as $mention) {
344 $mentions[] = $mention;
351 * Allow remote profile references to be used in commands:
352 * sub update@status.net
353 * whois evan@identi.ca
354 * reply http://identi.ca/evan hey what's up
356 * @param Command $command
358 * @param Profile &$profile
359 * @return hook return code
361 function onStartCommandGetProfile($command, $arg, &$profile)
363 $oprofile = $this->pullRemoteProfile($arg);
364 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
366 $profile = $oprofile->localProfile();
367 } catch (NoProfileException $e) {
368 // No locally stored profile found for remote profile
378 * Allow remote group references to be used in commands:
379 * join group+statusnet@identi.ca
380 * join http://identi.ca/group/statusnet
381 * drop identi.ca/group/statusnet
383 * @param Command $command
385 * @param User_group &$group
386 * @return hook return code
388 function onStartCommandGetGroup($command, $arg, &$group)
390 $oprofile = $this->pullRemoteProfile($arg);
391 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
392 $group = $oprofile->localGroup();
399 protected function pullRemoteProfile($arg)
402 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
405 return Ostatus_profile::ensureWebfinger($arg);
406 } catch (Exception $e) {
407 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
408 $arg . ': ' . $e->getMessage());
412 // Look for profile URLs, with or without scheme:
414 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
417 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
418 $schemes = array('http', 'https');
419 foreach ($schemes as $scheme) {
420 $urls[] = "$scheme://$arg";
424 foreach ($urls as $url) {
426 return Ostatus_profile::ensureProfileURL($url);
427 } catch (Exception $e) {
428 common_log(LOG_ERR, 'Profile lookup failed for ' .
429 $arg . ': ' . $e->getMessage());
436 * Make sure necessary tables are filled out.
438 function onCheckSchema() {
439 $schema = Schema::get();
440 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
441 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
442 $schema->ensureTable('feedsub', FeedSub::schemaDef());
443 $schema->ensureTable('hubsub', HubSub::schemaDef());
444 $schema->ensureTable('magicsig', Magicsig::schemaDef());
448 public function onEndShowStylesheets(Action $action) {
449 $action->cssLink($this->path('theme/base/css/ostatus.css'));
453 function onEndShowStatusNetScripts($action) {
454 $action->script($this->path('js/ostatus.js'));
459 * Override the "from ostatus" bit in notice lists to link to the
460 * original post and show the domain it came from.
462 * @param Notice in $notice
463 * @param string out &$name
464 * @param string out &$url
465 * @param string out &$title
466 * @return mixed hook return code
468 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
470 // If we don't handle this, keep the event handler going
471 if ($notice->source != 'ostatus') {
476 $url = $notice->getUrl();
477 // If getUrl() throws exception, $url is never set
479 $bits = parse_url($url);
480 $domain = $bits['host'];
481 if (substr($domain, 0, 4) == 'www.') {
482 $name = substr($domain, 4);
487 // TRANS: Title. %s is a domain name.
488 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
490 // Abort event handler, we have a name and URL!
492 } catch (InvalidUrlException $e) {
493 // This just means we don't have the notice source data
499 * Send incoming PuSH feeds for OStatus endpoints in for processing.
501 * @param FeedSub $feedsub
502 * @param DOMDocument $feed
503 * @return mixed hook return code
505 function onStartFeedSubReceive($feedsub, $feed)
507 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
508 if ($oprofile instanceof Ostatus_profile) {
509 $oprofile->processFeed($feed, 'push');
511 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
516 * Tell the FeedSub infrastructure whether we have any active OStatus
517 * usage for the feed; if not it'll be able to garbage-collect the
520 * @param FeedSub $feedsub
521 * @param integer $count in/out
522 * @return mixed hook return code
524 function onFeedSubSubscriberCount($feedsub, &$count)
526 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
527 if ($oprofile instanceof Ostatus_profile) {
528 $count += $oprofile->subscriberCount();
534 * When about to subscribe to a remote user, start a server-to-server
535 * PuSH subscription if needed. If we can't establish that, abort.
537 * @fixme If something else aborts later, we could end up with a stray
538 * PuSH subscription. This is relatively harmless, though.
540 * @param Profile $profile subscriber
541 * @param Profile $other subscribee
543 * @return hook return code
547 function onStartSubscribe(Profile $profile, Profile $other)
549 if (!$profile->isLocal()) {
553 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
554 if (!$oprofile instanceof Ostatus_profile) {
558 $oprofile->subscribe();
562 * Having established a remote subscription, send a notification to the
563 * remote OStatus profile's endpoint.
565 * @param Profile $profile subscriber
566 * @param Profile $other subscribee
568 * @return hook return code
572 function onEndSubscribe(Profile $profile, Profile $other)
574 if (!$profile->isLocal()) {
578 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
579 if (!$oprofile instanceof Ostatus_profile) {
583 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
584 'subscribed' => $other->id));
586 $act = $sub->asActivity();
588 $oprofile->notifyActivity($act, $profile);
594 * Notify remote server and garbage collect unused feeds on unsubscribe.
595 * @todo FIXME: Send these operations to background queues
598 * @param Profile $other
599 * @return hook return value
601 function onEndUnsubscribe(Profile $profile, Profile $other)
603 if (!$profile->isLocal()) {
607 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
608 if (!$oprofile instanceof Ostatus_profile) {
612 // Drop the PuSH subscription if there are no other subscribers.
613 $oprofile->garbageCollect();
615 $act = new Activity();
617 $act->verb = ActivityVerb::UNFOLLOW;
619 $act->id = TagURI::mint('unfollow:%d:%d:%s',
622 common_date_iso8601(time()));
625 // TRANS: Title for unfollowing a remote profile.
626 $act->title = _m('TITLE','Unfollow');
627 // TRANS: Success message for unsubscribe from user attempt through OStatus.
628 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
629 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
630 $profile->getBestName(),
631 $other->getBestName());
633 $act->actor = $profile->asActivityObject();
634 $act->object = $other->asActivityObject();
636 $oprofile->notifyActivity($act, $profile);
642 * When one of our local users tries to join a remote group,
643 * notify the remote server. If the notification is rejected,
646 * @param User_group $group
647 * @param Profile $profile
649 * @return mixed hook return value
650 * @throws Exception of various kinds, some from $oprofile->subscribe();
652 function onStartJoinGroup($group, $profile)
654 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
655 if (!$oprofile instanceof Ostatus_profile) {
659 $oprofile->subscribe();
661 // NOTE: we don't use Group_member::asActivity() since that record
662 // has not yet been created.
664 $act = new Activity();
665 $act->id = TagURI::mint('join:%d:%d:%s',
668 common_date_iso8601(time()));
670 $act->actor = $profile->asActivityObject();
671 $act->verb = ActivityVerb::JOIN;
672 $act->object = $oprofile->asActivityObject();
675 // TRANS: Title for joining a remote groep.
676 $act->title = _m('TITLE','Join');
677 // TRANS: Success message for subscribe to group attempt through OStatus.
678 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
679 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
680 $profile->getBestName(),
681 $oprofile->getBestName());
683 if ($oprofile->notifyActivity($act, $profile)) {
686 $oprofile->garbageCollect();
687 // TRANS: Exception thrown when joining a remote group fails.
688 throw new Exception(_m('Failed joining remote group.'));
693 * When one of our local users leaves a remote group, notify the remote
696 * @fixme Might be good to schedule a resend of the leave notification
697 * if it failed due to a transitory error. We've canceled the local
698 * membership already anyway, but if the remote server comes back up
699 * it'll be left with a stray membership record.
701 * @param User_group $group
702 * @param Profile $profile
704 * @return mixed hook return value
706 function onEndLeaveGroup($group, $profile)
708 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
709 if (!$oprofile instanceof Ostatus_profile) {
713 // Drop the PuSH subscription if there are no other subscribers.
714 $oprofile->garbageCollect();
718 $act = new Activity();
719 $act->id = TagURI::mint('leave:%d:%d:%s',
722 common_date_iso8601(time()));
724 $act->actor = $member->asActivityObject();
725 $act->verb = ActivityVerb::LEAVE;
726 $act->object = $oprofile->asActivityObject();
729 // TRANS: Title for leaving a remote group.
730 $act->title = _m('TITLE','Leave');
731 // TRANS: Success message for unsubscribe from group attempt through OStatus.
732 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
733 $act->content = sprintf(_m('%1$s has left group %2$s.'),
734 $member->getBestName(),
735 $oprofile->getBestName());
737 $oprofile->notifyActivity($act, $member);
741 * When one of our local users tries to subscribe to a remote peopletag,
742 * notify the remote server. If the notification is rejected,
743 * deny the subscription.
745 * @param Profile_list $peopletag
748 * @return mixed hook return value
749 * @throws Exception of various kinds, some from $oprofile->subscribe();
752 function onStartSubscribePeopletag($peopletag, $user)
754 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
755 if (!$oprofile instanceof Ostatus_profile) {
759 $oprofile->subscribe();
761 $sub = $user->getProfile();
762 $tagger = Profile::getKV($peopletag->tagger);
764 $act = new Activity();
765 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
768 common_date_iso8601(time()));
770 $act->actor = $sub->asActivityObject();
771 $act->verb = ActivityVerb::FOLLOW;
772 $act->object = $oprofile->asActivityObject();
775 // TRANS: Title for following a remote list.
776 $act->title = _m('TITLE','Follow list');
777 // TRANS: Success message for remote list follow through OStatus.
778 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
779 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
781 $oprofile->getBestName(),
782 $tagger->getBestName());
784 if ($oprofile->notifyActivity($act, $sub)) {
787 $oprofile->garbageCollect();
788 // TRANS: Exception thrown when subscription to remote list fails.
789 throw new Exception(_m('Failed subscribing to remote list.'));
794 * When one of our local users unsubscribes to a remote peopletag, notify the remote
797 * @param Profile_list $peopletag
800 * @return mixed hook return value
803 function onEndUnsubscribePeopletag($peopletag, $user)
805 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
806 if (!$oprofile instanceof Ostatus_profile) {
810 // Drop the PuSH subscription if there are no other subscribers.
811 $oprofile->garbageCollect();
813 $sub = Profile::getKV($user->id);
814 $tagger = Profile::getKV($peopletag->tagger);
816 $act = new Activity();
817 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
820 common_date_iso8601(time()));
822 $act->actor = $member->asActivityObject();
823 $act->verb = ActivityVerb::UNFOLLOW;
824 $act->object = $oprofile->asActivityObject();
827 // TRANS: Title for unfollowing a remote list.
828 $act->title = _m('Unfollow list');
829 // TRANS: Success message for remote list unfollow through OStatus.
830 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
831 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
833 $oprofile->getBestName(),
834 $tagger->getBestName());
836 $oprofile->notifyActivity($act, $user);
840 * Notify remote users when their notices get favorited.
842 * @param Profile or User $profile of local user doing the faving
843 * @param Notice $notice being favored
844 * @return hook return value
846 function onEndFavorNotice(Profile $profile, Notice $notice)
848 // Only distribute local users' favor actions, remote users
849 // will have already distributed theirs.
850 if (!$profile->isLocal()) {
854 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
855 if (!$oprofile instanceof Ostatus_profile) {
859 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
860 'notice_id' => $notice->id));
862 if (!$fav instanceof Fave) {
864 // TODO: Make pkeyGet throw exception, since this is a critical failure.
868 $act = $fav->asActivity();
870 $oprofile->notifyActivity($act, $profile);
876 * Notify remote user it has got a new people tag
877 * - tag verb is queued
878 * - the subscription is done immediately if not present
880 * @param Profile_tag $ptag the people tag that was created
881 * @return hook return value
882 * @throws Exception of various kinds, some from $oprofile->subscribe();
884 function onEndTagProfile($ptag)
886 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
887 if (!$oprofile instanceof Ostatus_profile) {
891 $plist = $ptag->getMeta();
892 if ($plist->private) {
896 $act = new Activity();
898 $tagger = $plist->getTagger();
899 $tagged = Profile::getKV('id', $ptag->tagged);
901 $act->verb = ActivityVerb::TAG;
902 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
903 $plist->tagger, $plist->id,
904 common_date_iso8601(time()));
906 // TRANS: Title for listing a remote profile.
907 $act->title = _m('TITLE','List');
908 // TRANS: Success message for remote list addition through OStatus.
909 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
910 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
911 $tagger->getBestName(),
912 $tagged->getBestName(),
913 $plist->getBestName());
915 $act->actor = $tagger->asActivityObject();
916 $act->objects = array($tagged->asActivityObject());
917 $act->target = ActivityObject::fromPeopletag($plist);
919 $oprofile->notifyDeferred($act, $tagger);
921 // initiate a PuSH subscription for the person being tagged
922 $oprofile->subscribe();
927 * Notify remote user that a people tag has been removed
928 * - untag verb is queued
929 * - the subscription is undone immediately if not required
930 * i.e garbageCollect()'d
932 * @param Profile_tag $ptag the people tag that was deleted
933 * @return hook return value
935 function onEndUntagProfile($ptag)
937 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
938 if (!$oprofile instanceof Ostatus_profile) {
942 $plist = $ptag->getMeta();
943 if ($plist->private) {
947 $act = new Activity();
949 $tagger = $plist->getTagger();
950 $tagged = Profile::getKV('id', $ptag->tagged);
952 $act->verb = ActivityVerb::UNTAG;
953 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
954 $plist->tagger, $plist->id,
955 common_date_iso8601(time()));
957 // TRANS: Title for unlisting a remote profile.
958 $act->title = _m('TITLE','Unlist');
959 // TRANS: Success message for remote list removal through OStatus.
960 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
961 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
962 $tagger->getBestName(),
963 $tagged->getBestName(),
964 $plist->getBestName());
966 $act->actor = $tagger->asActivityObject();
967 $act->objects = array($tagged->asActivityObject());
968 $act->target = ActivityObject::fromPeopletag($plist);
970 $oprofile->notifyDeferred($act, $tagger);
972 // unsubscribe to PuSH feed if no more required
973 $oprofile->garbageCollect();
979 * Notify remote users when their notices get de-favorited.
981 * @param Profile $profile Profile person doing the de-faving
982 * @param Notice $notice Notice being favored
984 * @return hook return value
986 function onEndDisfavorNotice(Profile $profile, Notice $notice)
988 // Only distribute local users' disfavor actions, remote users
989 // will have already distributed theirs.
990 if (!$profile->isLocal()) {
994 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
995 if (!$oprofile instanceof Ostatus_profile) {
999 $act = new Activity();
1001 $act->verb = ActivityVerb::UNFAVORITE;
1002 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1005 common_date_iso8601(time()));
1006 $act->time = time();
1007 // TRANS: Title for unliking a remote notice.
1008 $act->title = _m('Unlike');
1009 // TRANS: Success message for remove a favorite notice through OStatus.
1010 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1011 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1012 $profile->getBestName(),
1015 $act->actor = $profile->asActivityObject();
1016 $act->object = $notice->asActivityObject();
1018 $oprofile->notifyActivity($act, $profile);
1023 function onStartGetProfileUri($profile, &$uri)
1025 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1026 if ($oprofile instanceof Ostatus_profile) {
1027 $uri = $oprofile->uri;
1033 function onStartUserGroupHomeUrl($group, &$url)
1035 return $this->onStartUserGroupPermalink($group, $url);
1038 function onStartUserGroupPermalink($group, &$url)
1040 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1041 if ($oprofile instanceof Ostatus_profile) {
1042 // @fixme this should probably be in the user_group table
1043 // @fixme this uri not guaranteed to be a profile page
1044 $url = $oprofile->uri;
1049 function onStartShowSubscriptionsContent($action)
1051 $this->showEntityRemoteSubscribe($action);
1056 function onStartShowUserGroupsContent($action)
1058 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1063 function onEndShowSubscriptionsMiniList($action)
1065 $this->showEntityRemoteSubscribe($action);
1070 function onEndShowGroupsMiniList($action)
1072 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1077 function showEntityRemoteSubscribe($action, $target='ostatussub')
1079 $user = common_current_user();
1080 if ($user && ($user->id == $action->profile->id)) {
1081 $action->elementStart('div', 'entity_actions');
1082 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1083 'class' => 'entity_subscribe'));
1084 $action->element('a', array('href' => common_local_url($target),
1085 'class' => 'entity_remote_subscribe'),
1086 // TRANS: Link text for link to remote subscribe.
1088 $action->elementEnd('p');
1089 $action->elementEnd('div');
1094 * Ping remote profiles with updates to this profile.
1095 * Salmon pings are queued for background processing.
1097 function onEndBroadcastProfile(Profile $profile)
1099 $user = User::getKV('id', $profile->id);
1101 // Find foreign accounts I'm subscribed to that support Salmon pings.
1103 // @fixme we could run updates through the PuSH feed too,
1104 // in which case we can skip Salmon pings to folks who
1105 // are also subscribed to me.
1106 $sql = "SELECT * FROM ostatus_profile " .
1107 "WHERE profile_id IN " .
1108 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1110 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1111 $oprofile = new Ostatus_profile();
1112 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1114 if ($oprofile->N == 0) {
1115 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1119 $act = new Activity();
1121 $act->verb = ActivityVerb::UPDATE_PROFILE;
1122 $act->id = TagURI::mint('update-profile:%d:%s',
1124 common_date_iso8601(time()));
1125 $act->time = time();
1126 // TRANS: Title for activity.
1127 $act->title = _m('Profile update');
1128 // TRANS: Ping text for remote profile update through OStatus.
1129 // TRANS: %s is user that updated their profile.
1130 $act->content = sprintf(_m('%s has updated their profile page.'),
1131 $profile->getBestName());
1133 $act->actor = $profile->asActivityObject();
1134 $act->object = $act->actor;
1136 while ($oprofile->fetch()) {
1137 $oprofile->notifyDeferred($act, $profile);
1143 function onStartProfileListItemActionElements($item, $profile=null)
1145 if (!common_logged_in()) {
1147 $profileUser = User::getKV('id', $item->profile->id);
1149 if (!empty($profileUser)) {
1151 if ($item instanceof Action) {
1153 $profile = $item->profile;
1155 $output = $item->out;
1158 // Add an OStatus subscribe
1159 $output->elementStart('li', 'entity_subscribe');
1160 $url = common_local_url('ostatusinit',
1161 array('nickname' => $profileUser->nickname));
1162 $output->element('a', array('href' => $url,
1163 'class' => 'entity_remote_subscribe'),
1164 // TRANS: Link text for a user to subscribe to an OStatus user.
1166 $output->elementEnd('li');
1168 $output->elementStart('li', 'entity_tag');
1169 $url = common_local_url('ostatustag',
1170 array('nickname' => $profileUser->nickname));
1171 $output->element('a', array('href' => $url,
1172 'class' => 'entity_remote_tag'),
1173 // TRANS: Link text for a user to list an OStatus user.
1175 $output->elementEnd('li');
1182 function onPluginVersion(&$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 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1320 'data:application/magic-public-key,'. $magicsig->toString());
1321 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::DIASPORA_PUBLICKEYREL,
1322 base64_encode($magicsig->exportPublicKey()));
1326 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1328 list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
1331 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1332 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1335 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1336 $profile = $oprofile->checkAuthorship($activity);
1337 } catch (Exception $e) {
1338 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1345 public function onProfileDeleteRelated($profile, &$related)
1347 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1348 $related[] = 'Ostatus_profile';
1350 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1351 $magicsig = Magicsig::getKV('user_id', $profile->id);
1352 if ($magicsig instanceof Magicsig) {
1353 $magicsig->delete();