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 $matches[$pos] = array('mentioned' => array($profile),
285 'length' => mb_strlen($target),
286 'url' => $profile->getUrl());
288 } catch (Exception $e) {
289 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
294 // Profile matches: @example.com/mublog/user
295 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)*)!',
298 PREG_OFFSET_CAPTURE)) {
299 foreach ($wmatches[1] as $wmatch) {
300 list($target, $pos) = $wmatch;
301 $schemes = array('http', 'https');
302 foreach ($schemes as $scheme) {
303 $url = "$scheme://$target";
304 $this->log(LOG_INFO, "Checking profile address '$url'");
306 $oprofile = Ostatus_profile::ensureProfileURL($url);
307 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
308 $profile = $oprofile->localProfile();
309 $matches[$pos] = array('mentioned' => array($profile),
313 'length' => mb_strlen($target),
314 'url' => $profile->getUrl());
317 } catch (Exception $e) {
318 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
324 foreach ($mentions as $i => $other) {
325 // If we share a common prefix with a local user, override it!
326 $pos = $other['position'];
327 if (isset($matches[$pos])) {
328 $mentions[$i] = $matches[$pos];
329 unset($matches[$pos]);
332 foreach ($matches as $mention) {
333 $mentions[] = $mention;
340 * Allow remote profile references to be used in commands:
341 * sub update@status.net
342 * whois evan@identi.ca
343 * reply http://identi.ca/evan hey what's up
345 * @param Command $command
347 * @param Profile &$profile
348 * @return hook return code
350 function onStartCommandGetProfile($command, $arg, &$profile)
352 $oprofile = $this->pullRemoteProfile($arg);
353 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
355 $profile = $oprofile->localProfile();
356 } catch (NoProfileException $e) {
357 // No locally stored profile found for remote profile
367 * Allow remote group references to be used in commands:
368 * join group+statusnet@identi.ca
369 * join http://identi.ca/group/statusnet
370 * drop identi.ca/group/statusnet
372 * @param Command $command
374 * @param User_group &$group
375 * @return hook return code
377 function onStartCommandGetGroup($command, $arg, &$group)
379 $oprofile = $this->pullRemoteProfile($arg);
380 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
381 $group = $oprofile->localGroup();
388 protected function pullRemoteProfile($arg)
391 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
394 return Ostatus_profile::ensureWebfinger($arg);
395 } catch (Exception $e) {
396 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
397 $arg . ': ' . $e->getMessage());
401 // Look for profile URLs, with or without scheme:
403 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
406 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
407 $schemes = array('http', 'https');
408 foreach ($schemes as $scheme) {
409 $urls[] = "$scheme://$arg";
413 foreach ($urls as $url) {
415 return Ostatus_profile::ensureProfileURL($url);
416 } catch (Exception $e) {
417 common_log(LOG_ERR, 'Profile lookup failed for ' .
418 $arg . ': ' . $e->getMessage());
425 * Make sure necessary tables are filled out.
427 function onCheckSchema() {
428 $schema = Schema::get();
429 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
430 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
431 $schema->ensureTable('feedsub', FeedSub::schemaDef());
432 $schema->ensureTable('hubsub', HubSub::schemaDef());
433 $schema->ensureTable('magicsig', Magicsig::schemaDef());
437 public function onEndShowStylesheets(Action $action) {
438 $action->cssLink($this->path('theme/base/css/ostatus.css'));
442 function onEndShowStatusNetScripts($action) {
443 $action->script($this->path('js/ostatus.js'));
448 * Override the "from ostatus" bit in notice lists to link to the
449 * original post and show the domain it came from.
451 * @param Notice in $notice
452 * @param string out &$name
453 * @param string out &$url
454 * @param string out &$title
455 * @return mixed hook return code
457 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
459 // If we don't handle this, keep the event handler going
460 if ($notice->source != 'ostatus') {
465 $url = $notice->getUrl();
466 // If getUrl() throws exception, $url is never set
468 $bits = parse_url($url);
469 $domain = $bits['host'];
470 if (substr($domain, 0, 4) == 'www.') {
471 $name = substr($domain, 4);
476 // TRANS: Title. %s is a domain name.
477 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
479 // Abort event handler, we have a name and URL!
481 } catch (InvalidUrlException $e) {
482 // This just means we don't have the notice source data
488 * Send incoming PuSH feeds for OStatus endpoints in for processing.
490 * @param FeedSub $feedsub
491 * @param DOMDocument $feed
492 * @return mixed hook return code
494 function onStartFeedSubReceive($feedsub, $feed)
496 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
497 if ($oprofile instanceof Ostatus_profile) {
498 $oprofile->processFeed($feed, 'push');
500 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
505 * Tell the FeedSub infrastructure whether we have any active OStatus
506 * usage for the feed; if not it'll be able to garbage-collect the
509 * @param FeedSub $feedsub
510 * @param integer $count in/out
511 * @return mixed hook return code
513 function onFeedSubSubscriberCount($feedsub, &$count)
515 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
516 if ($oprofile instanceof Ostatus_profile) {
517 $count += $oprofile->subscriberCount();
523 * When about to subscribe to a remote user, start a server-to-server
524 * PuSH subscription if needed. If we can't establish that, abort.
526 * @fixme If something else aborts later, we could end up with a stray
527 * PuSH subscription. This is relatively harmless, though.
529 * @param Profile $profile subscriber
530 * @param Profile $other subscribee
532 * @return hook return code
536 function onStartSubscribe(Profile $profile, Profile $other)
538 if (!$profile->isLocal()) {
542 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
543 if (!$oprofile instanceof Ostatus_profile) {
547 $oprofile->subscribe();
551 * Having established a remote subscription, send a notification to the
552 * remote OStatus profile's endpoint.
554 * @param Profile $profile subscriber
555 * @param Profile $other subscribee
557 * @return hook return code
561 function onEndSubscribe(Profile $profile, Profile $other)
563 if (!$profile->isLocal()) {
567 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
568 if (!$oprofile instanceof Ostatus_profile) {
572 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
573 'subscribed' => $other->id));
575 $act = $sub->asActivity();
577 $oprofile->notifyActivity($act, $profile);
583 * Notify remote server and garbage collect unused feeds on unsubscribe.
584 * @todo FIXME: Send these operations to background queues
587 * @param Profile $other
588 * @return hook return value
590 function onEndUnsubscribe(Profile $profile, Profile $other)
592 if (!$profile->isLocal()) {
596 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
597 if (!$oprofile instanceof Ostatus_profile) {
601 // Drop the PuSH subscription if there are no other subscribers.
602 $oprofile->garbageCollect();
604 $act = new Activity();
606 $act->verb = ActivityVerb::UNFOLLOW;
608 $act->id = TagURI::mint('unfollow:%d:%d:%s',
611 common_date_iso8601(time()));
614 // TRANS: Title for unfollowing a remote profile.
615 $act->title = _m('TITLE','Unfollow');
616 // TRANS: Success message for unsubscribe from user attempt through OStatus.
617 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
618 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
619 $profile->getBestName(),
620 $other->getBestName());
622 $act->actor = $profile->asActivityObject();
623 $act->object = $other->asActivityObject();
625 $oprofile->notifyActivity($act, $profile);
631 * When one of our local users tries to join a remote group,
632 * notify the remote server. If the notification is rejected,
635 * @param User_group $group
636 * @param Profile $profile
638 * @return mixed hook return value
639 * @throws Exception of various kinds, some from $oprofile->subscribe();
641 function onStartJoinGroup($group, $profile)
643 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
644 if (!$oprofile instanceof Ostatus_profile) {
648 $oprofile->subscribe();
650 // NOTE: we don't use Group_member::asActivity() since that record
651 // has not yet been created.
653 $act = new Activity();
654 $act->id = TagURI::mint('join:%d:%d:%s',
657 common_date_iso8601(time()));
659 $act->actor = $profile->asActivityObject();
660 $act->verb = ActivityVerb::JOIN;
661 $act->object = $oprofile->asActivityObject();
664 // TRANS: Title for joining a remote groep.
665 $act->title = _m('TITLE','Join');
666 // TRANS: Success message for subscribe to group attempt through OStatus.
667 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
668 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
669 $profile->getBestName(),
670 $oprofile->getBestName());
672 if ($oprofile->notifyActivity($act, $profile)) {
675 $oprofile->garbageCollect();
676 // TRANS: Exception thrown when joining a remote group fails.
677 throw new Exception(_m('Failed joining remote group.'));
682 * When one of our local users leaves a remote group, notify the remote
685 * @fixme Might be good to schedule a resend of the leave notification
686 * if it failed due to a transitory error. We've canceled the local
687 * membership already anyway, but if the remote server comes back up
688 * it'll be left with a stray membership record.
690 * @param User_group $group
691 * @param Profile $profile
693 * @return mixed hook return value
695 function onEndLeaveGroup($group, $profile)
697 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
698 if (!$oprofile instanceof Ostatus_profile) {
702 // Drop the PuSH subscription if there are no other subscribers.
703 $oprofile->garbageCollect();
707 $act = new Activity();
708 $act->id = TagURI::mint('leave:%d:%d:%s',
711 common_date_iso8601(time()));
713 $act->actor = $member->asActivityObject();
714 $act->verb = ActivityVerb::LEAVE;
715 $act->object = $oprofile->asActivityObject();
718 // TRANS: Title for leaving a remote group.
719 $act->title = _m('TITLE','Leave');
720 // TRANS: Success message for unsubscribe from group attempt through OStatus.
721 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
722 $act->content = sprintf(_m('%1$s has left group %2$s.'),
723 $member->getBestName(),
724 $oprofile->getBestName());
726 $oprofile->notifyActivity($act, $member);
730 * When one of our local users tries to subscribe to a remote peopletag,
731 * notify the remote server. If the notification is rejected,
732 * deny the subscription.
734 * @param Profile_list $peopletag
737 * @return mixed hook return value
738 * @throws Exception of various kinds, some from $oprofile->subscribe();
741 function onStartSubscribePeopletag($peopletag, $user)
743 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
744 if (!$oprofile instanceof Ostatus_profile) {
748 $oprofile->subscribe();
750 $sub = $user->getProfile();
751 $tagger = Profile::getKV($peopletag->tagger);
753 $act = new Activity();
754 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
757 common_date_iso8601(time()));
759 $act->actor = $sub->asActivityObject();
760 $act->verb = ActivityVerb::FOLLOW;
761 $act->object = $oprofile->asActivityObject();
764 // TRANS: Title for following a remote list.
765 $act->title = _m('TITLE','Follow list');
766 // TRANS: Success message for remote list follow through OStatus.
767 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
768 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
770 $oprofile->getBestName(),
771 $tagger->getBestName());
773 if ($oprofile->notifyActivity($act, $sub)) {
776 $oprofile->garbageCollect();
777 // TRANS: Exception thrown when subscription to remote list fails.
778 throw new Exception(_m('Failed subscribing to remote list.'));
783 * When one of our local users unsubscribes to a remote peopletag, notify the remote
786 * @param Profile_list $peopletag
789 * @return mixed hook return value
792 function onEndUnsubscribePeopletag($peopletag, $user)
794 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
795 if (!$oprofile instanceof Ostatus_profile) {
799 // Drop the PuSH subscription if there are no other subscribers.
800 $oprofile->garbageCollect();
802 $sub = Profile::getKV($user->id);
803 $tagger = Profile::getKV($peopletag->tagger);
805 $act = new Activity();
806 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
809 common_date_iso8601(time()));
811 $act->actor = $member->asActivityObject();
812 $act->verb = ActivityVerb::UNFOLLOW;
813 $act->object = $oprofile->asActivityObject();
816 // TRANS: Title for unfollowing a remote list.
817 $act->title = _m('Unfollow list');
818 // TRANS: Success message for remote list unfollow through OStatus.
819 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
820 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
822 $oprofile->getBestName(),
823 $tagger->getBestName());
825 $oprofile->notifyActivity($act, $user);
829 * Notify remote users when their notices get favorited.
831 * @param Profile or User $profile of local user doing the faving
832 * @param Notice $notice being favored
833 * @return hook return value
835 function onEndFavorNotice(Profile $profile, Notice $notice)
837 // Only distribute local users' favor actions, remote users
838 // will have already distributed theirs.
839 if (!$profile->isLocal()) {
843 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
844 if (!$oprofile instanceof Ostatus_profile) {
848 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
849 'notice_id' => $notice->id));
851 if (!$fav instanceof Fave) {
853 // TODO: Make pkeyGet throw exception, since this is a critical failure.
857 $act = $fav->asActivity();
859 $oprofile->notifyActivity($act, $profile);
865 * Notify remote user it has got a new people tag
866 * - tag verb is queued
867 * - the subscription is done immediately if not present
869 * @param Profile_tag $ptag the people tag that was created
870 * @return hook return value
871 * @throws Exception of various kinds, some from $oprofile->subscribe();
873 function onEndTagProfile($ptag)
875 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
876 if (!$oprofile instanceof Ostatus_profile) {
880 $plist = $ptag->getMeta();
881 if ($plist->private) {
885 $act = new Activity();
887 $tagger = $plist->getTagger();
888 $tagged = Profile::getKV('id', $ptag->tagged);
890 $act->verb = ActivityVerb::TAG;
891 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
892 $plist->tagger, $plist->id,
893 common_date_iso8601(time()));
895 // TRANS: Title for listing a remote profile.
896 $act->title = _m('TITLE','List');
897 // TRANS: Success message for remote list addition through OStatus.
898 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
899 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
900 $tagger->getBestName(),
901 $tagged->getBestName(),
902 $plist->getBestName());
904 $act->actor = $tagger->asActivityObject();
905 $act->objects = array($tagged->asActivityObject());
906 $act->target = ActivityObject::fromPeopletag($plist);
908 $oprofile->notifyDeferred($act, $tagger);
910 // initiate a PuSH subscription for the person being tagged
911 $oprofile->subscribe();
916 * Notify remote user that a people tag has been removed
917 * - untag verb is queued
918 * - the subscription is undone immediately if not required
919 * i.e garbageCollect()'d
921 * @param Profile_tag $ptag the people tag that was deleted
922 * @return hook return value
924 function onEndUntagProfile($ptag)
926 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
927 if (!$oprofile instanceof Ostatus_profile) {
931 $plist = $ptag->getMeta();
932 if ($plist->private) {
936 $act = new Activity();
938 $tagger = $plist->getTagger();
939 $tagged = Profile::getKV('id', $ptag->tagged);
941 $act->verb = ActivityVerb::UNTAG;
942 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
943 $plist->tagger, $plist->id,
944 common_date_iso8601(time()));
946 // TRANS: Title for unlisting a remote profile.
947 $act->title = _m('TITLE','Unlist');
948 // TRANS: Success message for remote list removal through OStatus.
949 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
950 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
951 $tagger->getBestName(),
952 $tagged->getBestName(),
953 $plist->getBestName());
955 $act->actor = $tagger->asActivityObject();
956 $act->objects = array($tagged->asActivityObject());
957 $act->target = ActivityObject::fromPeopletag($plist);
959 $oprofile->notifyDeferred($act, $tagger);
961 // unsubscribe to PuSH feed if no more required
962 $oprofile->garbageCollect();
968 * Notify remote users when their notices get de-favorited.
970 * @param Profile $profile Profile person doing the de-faving
971 * @param Notice $notice Notice being favored
973 * @return hook return value
975 function onEndDisfavorNotice(Profile $profile, Notice $notice)
977 // Only distribute local users' disfavor actions, remote users
978 // will have already distributed theirs.
979 if (!$profile->isLocal()) {
983 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
984 if (!$oprofile instanceof Ostatus_profile) {
988 $act = new Activity();
990 $act->verb = ActivityVerb::UNFAVORITE;
991 $act->id = TagURI::mint('disfavor:%d:%d:%s',
994 common_date_iso8601(time()));
996 // TRANS: Title for unliking a remote notice.
997 $act->title = _m('Unlike');
998 // TRANS: Success message for remove a favorite notice through OStatus.
999 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1000 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1001 $profile->getBestName(),
1004 $act->actor = $profile->asActivityObject();
1005 $act->object = $notice->asActivityObject();
1007 $oprofile->notifyActivity($act, $profile);
1012 function onStartGetProfileUri($profile, &$uri)
1014 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1015 if ($oprofile instanceof Ostatus_profile) {
1016 $uri = $oprofile->uri;
1022 function onStartUserGroupHomeUrl($group, &$url)
1024 return $this->onStartUserGroupPermalink($group, $url);
1027 function onStartUserGroupPermalink($group, &$url)
1029 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1030 if ($oprofile instanceof Ostatus_profile) {
1031 // @fixme this should probably be in the user_group table
1032 // @fixme this uri not guaranteed to be a profile page
1033 $url = $oprofile->uri;
1038 function onStartShowSubscriptionsContent($action)
1040 $this->showEntityRemoteSubscribe($action);
1045 function onStartShowUserGroupsContent($action)
1047 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1052 function onEndShowSubscriptionsMiniList($action)
1054 $this->showEntityRemoteSubscribe($action);
1059 function onEndShowGroupsMiniList($action)
1061 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1066 function showEntityRemoteSubscribe($action, $target='ostatussub')
1068 if (!$action->getScoped() instanceof Profile) {
1069 // early return if we're not logged in
1073 if ($action->getScoped()->sameAs($action->getTarget())) {
1074 $action->elementStart('div', 'entity_actions');
1075 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1076 'class' => 'entity_subscribe'));
1077 $action->element('a', array('href' => common_local_url($target),
1078 'class' => 'entity_remote_subscribe'),
1079 // TRANS: Link text for link to remote subscribe.
1081 $action->elementEnd('p');
1082 $action->elementEnd('div');
1087 * Ping remote profiles with updates to this profile.
1088 * Salmon pings are queued for background processing.
1090 function onEndBroadcastProfile(Profile $profile)
1092 $user = User::getKV('id', $profile->id);
1094 // Find foreign accounts I'm subscribed to that support Salmon pings.
1096 // @fixme we could run updates through the PuSH feed too,
1097 // in which case we can skip Salmon pings to folks who
1098 // are also subscribed to me.
1099 $sql = "SELECT * FROM ostatus_profile " .
1100 "WHERE profile_id IN " .
1101 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1103 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1104 $oprofile = new Ostatus_profile();
1105 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1107 if ($oprofile->N == 0) {
1108 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1112 $act = new Activity();
1114 $act->verb = ActivityVerb::UPDATE_PROFILE;
1115 $act->id = TagURI::mint('update-profile:%d:%s',
1117 common_date_iso8601(time()));
1118 $act->time = time();
1119 // TRANS: Title for activity.
1120 $act->title = _m('Profile update');
1121 // TRANS: Ping text for remote profile update through OStatus.
1122 // TRANS: %s is user that updated their profile.
1123 $act->content = sprintf(_m('%s has updated their profile page.'),
1124 $profile->getBestName());
1126 $act->actor = $profile->asActivityObject();
1127 $act->object = $act->actor;
1129 while ($oprofile->fetch()) {
1130 $oprofile->notifyDeferred($act, $profile);
1136 // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1137 function onStartProfileListItemActionElements($item)
1139 if (common_logged_in()) {
1140 // only non-logged in users get to see the "remote subscribe" form
1142 } elseif (!$item->getTarget()->isLocal()) {
1143 // we can (for now) only provide remote subscribe forms for local users
1147 if ($item instanceof ProfileAction) {
1149 } elseif ($item instanceof Widget) {
1150 $output = $item->out;
1152 // Bad $item class, don't know how to use this for outputting!
1153 throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1156 // Add an OStatus subscribe
1157 $output->elementStart('li', 'entity_subscribe');
1158 $url = common_local_url('ostatusinit',
1159 array('nickname' => $item->getTarget()->getNickname()));
1160 $output->element('a', array('href' => $url,
1161 'class' => 'entity_remote_subscribe'),
1162 // TRANS: Link text for a user to subscribe to an OStatus user.
1164 $output->elementEnd('li');
1166 $output->elementStart('li', 'entity_tag');
1167 $url = common_local_url('ostatustag',
1168 array('nickname' => $item->getTarget()->getNickname()));
1169 $output->element('a', array('href' => $url,
1170 'class' => 'entity_remote_tag'),
1171 // TRANS: Link text for a user to list an OStatus user.
1173 $output->elementEnd('li');
1178 function onPluginVersion(array &$versions)
1180 $versions[] = array('name' => 'OStatus',
1181 'version' => GNUSOCIAL_VERSION,
1182 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1183 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1184 // TRANS: Plugin description.
1185 'rawdescription' => _m('Follow people across social networks that implement '.
1186 '<a href="http://ostatus.org/">OStatus</a>.'));
1192 * Utility function to check if the given URI is a canonical group profile
1193 * page, and if so return the ID number.
1195 * @param string $url
1196 * @return mixed int or false
1198 public static function localGroupFromUrl($url)
1200 $group = User_group::getKV('uri', $url);
1201 if ($group instanceof User_group) {
1202 if ($group->isLocal()) {
1206 // To find local groups which haven't had their uri fields filled out...
1207 // If the domain has changed since a subscriber got the URI, it'll
1209 $template = common_local_url('groupbyid', array('id' => '31337'));
1210 $template = preg_quote($template, '/');
1211 $template = str_replace('31337', '(\d+)', $template);
1212 if (preg_match("/$template/", $url, $matches)) {
1213 return intval($matches[1]);
1219 public function onStartProfileGetAtomFeed($profile, &$feed)
1221 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1223 if (!$oprofile instanceof Ostatus_profile) {
1227 $feed = $oprofile->feeduri;
1231 function onStartGetProfileFromURI($uri, &$profile)
1233 // Don't want to do Web-based discovery on our own server,
1234 // so we check locally first.
1236 $user = User::getKV('uri', $uri);
1238 if (!empty($user)) {
1239 $profile = $user->getProfile();
1243 // Now, check remotely
1246 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1247 $profile = $oprofile->localProfile();
1248 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1249 } catch (Exception $e) {
1250 return true; // It's not an OStatus profile as far as we know, continue event handling
1254 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1256 $author = $target->getProfile();
1257 $profiletype = $this->profileTypeString($author);
1258 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1259 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1263 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1265 if ($target->getObjectType() === ActivityObject::PERSON) {
1266 $this->addWebFingerPersonLinks($xrd, $target);
1270 $profiletype = $this->profileTypeString($target);
1271 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1273 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1275 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1276 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1277 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1279 // TODO - finalize where the redirect should go on the publisher
1280 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1281 common_local_url('ostatussub') . '?profile={uri}',
1282 null, // type not set
1283 true); // isTemplate
1288 protected function profileTypeString(Profile $target)
1290 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1291 switch ($target->getObjectType()) {
1292 case ActivityObject::PERSON:
1294 case ActivityObject::GROUP:
1297 throw new ServerException('Unknown profile type for WebFinger profile links');
1301 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1303 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1304 common_local_url('ApiTimelineUser',
1305 array('id' => $target->id, 'format' => 'atom')),
1306 'application/atom+xml');
1308 // Get this profile's keypair
1309 $magicsig = Magicsig::getKV('user_id', $target->id);
1310 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1311 $magicsig = Magicsig::generate($target->getUser());
1314 if (!$magicsig instanceof Magicsig) {
1315 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1317 if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1318 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1319 'data:application/magic-public-key,'. $magicsig->toString());
1320 // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1321 Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1325 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1327 list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
1330 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1331 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1334 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1335 $profile = $oprofile->checkAuthorship($activity);
1336 } catch (Exception $e) {
1337 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1344 public function onProfileDeleteRelated($profile, &$related)
1346 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1347 $related[] = 'Ostatus_profile';
1349 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1350 $magicsig = Magicsig::getKV('user_id', $profile->id);
1351 if ($magicsig instanceof Magicsig) {
1352 $magicsig->delete();