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 $notice, array &$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 public function onStartProfileCompletionSearch(Action $action, Profile $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, array &$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 'url' => $profile->getUrl());
287 } catch (Exception $e) {
288 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
293 // Profile matches: @example.com/mublog/user
294 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
297 PREG_OFFSET_CAPTURE)) {
298 foreach ($wmatches[1] as $wmatch) {
299 list($target, $pos) = $wmatch;
300 $schemes = array('http', 'https');
301 foreach ($schemes as $scheme) {
302 $url = "$scheme://$target";
303 $this->log(LOG_INFO, "Checking profile address '$url'");
305 $oprofile = Ostatus_profile::ensureProfileURL($url);
306 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
307 $profile = $oprofile->localProfile();
308 $matches[$pos] = array('mentioned' => array($profile),
312 'url' => $profile->getUrl());
315 } catch (Exception $e) {
316 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
322 foreach ($mentions as $i => $other) {
323 // If we share a common prefix with a local user, override it!
324 $pos = $other['position'];
325 if (isset($matches[$pos])) {
326 $mentions[$i] = $matches[$pos];
327 unset($matches[$pos]);
330 foreach ($matches as $mention) {
331 $mentions[] = $mention;
338 * Allow remote profile references to be used in commands:
339 * sub update@status.net
340 * whois evan@identi.ca
341 * reply http://identi.ca/evan hey what's up
343 * @param Command $command
345 * @param Profile &$profile
346 * @return hook return code
348 public function onStartCommandGetProfile(Command $command, $arg, Profile &$profile = null)
350 $oprofile = $this->pullRemoteProfile($arg);
351 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
353 $profile = $oprofile->localProfile();
354 } catch (NoProfileException $e) {
355 // No locally stored profile found for remote profile
365 * Allow remote group references to be used in commands:
366 * join group+statusnet@identi.ca
367 * join http://identi.ca/group/statusnet
368 * drop identi.ca/group/statusnet
370 * @param Command $command
372 * @param User_group &$group
373 * @return hook return code
375 function onStartCommandGetGroup(Command $command, $arg, User_group &$group = null)
377 $oprofile = $this->pullRemoteProfile($arg);
378 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
379 $group = $oprofile->localGroup();
386 protected function pullRemoteProfile($arg)
389 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
392 return Ostatus_profile::ensureWebfinger($arg);
393 } catch (Exception $e) {
394 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
395 $arg . ': ' . $e->getMessage());
399 // Look for profile URLs, with or without scheme:
401 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
404 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
405 $schemes = array('http', 'https');
406 foreach ($schemes as $scheme) {
407 $urls[] = "$scheme://$arg";
411 foreach ($urls as $url) {
413 return Ostatus_profile::ensureProfileURL($url);
414 } catch (Exception $e) {
415 common_log(LOG_ERR, 'Profile lookup failed for ' .
416 $arg . ': ' . $e->getMessage());
423 * Make sure necessary tables are filled out.
425 function onCheckSchema() {
426 $schema = Schema::get();
427 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
428 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
429 $schema->ensureTable('feedsub', FeedSub::schemaDef());
430 $schema->ensureTable('hubsub', HubSub::schemaDef());
431 $schema->ensureTable('magicsig', Magicsig::schemaDef());
435 public function onEndShowStylesheets(Action $action) {
436 $action->cssLink($this->path('theme/base/css/ostatus.css'));
440 public function onEndShowStatusNetScripts(Action $action) {
441 $action->script($this->path('js/ostatus.js'));
446 * Override the "from ostatus" bit in notice lists to link to the
447 * original post and show the domain it came from.
449 * @param Notice in $notice
450 * @param string out &$name
451 * @param string out &$url
452 * @param string out &$title
453 * @return mixed hook return code
455 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
457 // If we don't handle this, keep the event handler going
458 if ($notice->source != 'ostatus') {
463 $url = $notice->getUrl();
464 // If getUrl() throws exception, $url is never set
466 $bits = parse_url($url);
467 $domain = $bits['host'];
468 if (substr($domain, 0, 4) == 'www.') {
469 $name = substr($domain, 4);
474 // TRANS: Title. %s is a domain name.
475 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
477 // Abort event handler, we have a name and URL!
479 } catch (InvalidUrlException $e) {
480 // This just means we don't have the notice source data
486 * Send incoming PuSH feeds for OStatus endpoints in for processing.
488 * @param FeedSub $feedsub
489 * @param DOMDocument $feed
490 * @return mixed hook return code
492 function onStartFeedSubReceive($feedsub, $feed)
494 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
495 if ($oprofile instanceof Ostatus_profile) {
496 $oprofile->processFeed($feed, 'push');
498 common_debug("No ostatus profile for incoming feed $feedsub->uri");
503 * Tell the FeedSub infrastructure whether we have any active OStatus
504 * usage for the feed; if not it'll be able to garbage-collect the
507 * @param FeedSub $feedsub
508 * @param integer $count in/out
509 * @return mixed hook return code
511 function onFeedSubSubscriberCount($feedsub, &$count)
513 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
514 if ($oprofile instanceof Ostatus_profile) {
515 $count += $oprofile->subscriberCount();
521 * When about to subscribe to a remote user, start a server-to-server
522 * PuSH subscription if needed. If we can't establish that, abort.
524 * @fixme If something else aborts later, we could end up with a stray
525 * PuSH subscription. This is relatively harmless, though.
527 * @param Profile $profile subscriber
528 * @param Profile $other subscribee
530 * @return hook return code
534 function onStartSubscribe(Profile $profile, Profile $other)
536 if (!$profile->isLocal()) {
540 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
541 if (!$oprofile instanceof Ostatus_profile) {
545 $oprofile->subscribe();
549 * Having established a remote subscription, send a notification to the
550 * remote OStatus profile's endpoint.
552 * @param Profile $profile subscriber
553 * @param Profile $other subscribee
555 * @return hook return code
559 function onEndSubscribe(Profile $profile, Profile $other)
561 if (!$profile->isLocal()) {
565 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
566 if (!$oprofile instanceof Ostatus_profile) {
570 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
571 'subscribed' => $other->id));
573 $act = $sub->asActivity();
575 $oprofile->notifyActivity($act, $profile);
581 * Notify remote server and garbage collect unused feeds on unsubscribe.
582 * @todo FIXME: Send these operations to background queues
585 * @param Profile $other
586 * @return hook return value
588 function onEndUnsubscribe(Profile $profile, Profile $other)
590 if (!$profile->isLocal()) {
594 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
595 if (!$oprofile instanceof Ostatus_profile) {
599 // Drop the PuSH subscription if there are no other subscribers.
600 $oprofile->garbageCollect();
602 $act = new Activity();
604 $act->verb = ActivityVerb::UNFOLLOW;
606 $act->id = TagURI::mint('unfollow:%d:%d:%s',
609 common_date_iso8601(time()));
612 // TRANS: Title for unfollowing a remote profile.
613 $act->title = _m('TITLE','Unfollow');
614 // TRANS: Success message for unsubscribe from user attempt through OStatus.
615 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
616 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
617 $profile->getBestName(),
618 $other->getBestName());
620 $act->actor = $profile->asActivityObject();
621 $act->object = $other->asActivityObject();
623 $oprofile->notifyActivity($act, $profile);
629 * When one of our local users tries to join a remote group,
630 * notify the remote server. If the notification is rejected,
633 * @param User_group $group
634 * @param Profile $profile
636 * @return mixed hook return value
637 * @throws Exception of various kinds, some from $oprofile->subscribe();
639 function onStartJoinGroup($group, $profile)
641 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
642 if (!$oprofile instanceof Ostatus_profile) {
646 $oprofile->subscribe();
648 // NOTE: we don't use Group_member::asActivity() since that record
649 // has not yet been created.
651 $act = new Activity();
652 $act->id = TagURI::mint('join:%d:%d:%s',
655 common_date_iso8601(time()));
657 $act->actor = $profile->asActivityObject();
658 $act->verb = ActivityVerb::JOIN;
659 $act->object = $oprofile->asActivityObject();
662 // TRANS: Title for joining a remote groep.
663 $act->title = _m('TITLE','Join');
664 // TRANS: Success message for subscribe to group attempt through OStatus.
665 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
666 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
667 $profile->getBestName(),
668 $oprofile->getBestName());
670 if ($oprofile->notifyActivity($act, $profile)) {
673 $oprofile->garbageCollect();
674 // TRANS: Exception thrown when joining a remote group fails.
675 throw new Exception(_m('Failed joining remote group.'));
680 * When one of our local users leaves a remote group, notify the remote
683 * @fixme Might be good to schedule a resend of the leave notification
684 * if it failed due to a transitory error. We've canceled the local
685 * membership already anyway, but if the remote server comes back up
686 * it'll be left with a stray membership record.
688 * @param User_group $group
689 * @param Profile $profile
691 * @return mixed hook return value
693 function onEndLeaveGroup($group, $profile)
695 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
696 if (!$oprofile instanceof Ostatus_profile) {
700 // Drop the PuSH subscription if there are no other subscribers.
701 $oprofile->garbageCollect();
705 $act = new Activity();
706 $act->id = TagURI::mint('leave:%d:%d:%s',
709 common_date_iso8601(time()));
711 $act->actor = $member->asActivityObject();
712 $act->verb = ActivityVerb::LEAVE;
713 $act->object = $oprofile->asActivityObject();
716 // TRANS: Title for leaving a remote group.
717 $act->title = _m('TITLE','Leave');
718 // TRANS: Success message for unsubscribe from group attempt through OStatus.
719 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
720 $act->content = sprintf(_m('%1$s has left group %2$s.'),
721 $member->getBestName(),
722 $oprofile->getBestName());
724 $oprofile->notifyActivity($act, $member);
728 * When one of our local users tries to subscribe to a remote peopletag,
729 * notify the remote server. If the notification is rejected,
730 * deny the subscription.
732 * @param Profile_list $peopletag
735 * @return mixed hook return value
736 * @throws Exception of various kinds, some from $oprofile->subscribe();
739 function onStartSubscribePeopletag($peopletag, $user)
741 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
742 if (!$oprofile instanceof Ostatus_profile) {
746 $oprofile->subscribe();
748 $sub = $user->getProfile();
749 $tagger = Profile::getKV($peopletag->tagger);
751 $act = new Activity();
752 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
755 common_date_iso8601(time()));
757 $act->actor = $sub->asActivityObject();
758 $act->verb = ActivityVerb::FOLLOW;
759 $act->object = $oprofile->asActivityObject();
762 // TRANS: Title for following a remote list.
763 $act->title = _m('TITLE','Follow list');
764 // TRANS: Success message for remote list follow through OStatus.
765 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
766 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
768 $oprofile->getBestName(),
769 $tagger->getBestName());
771 if ($oprofile->notifyActivity($act, $sub)) {
774 $oprofile->garbageCollect();
775 // TRANS: Exception thrown when subscription to remote list fails.
776 throw new Exception(_m('Failed subscribing to remote list.'));
781 * When one of our local users unsubscribes to a remote peopletag, notify the remote
784 * @param Profile_list $peopletag
787 * @return mixed hook return value
790 function onEndUnsubscribePeopletag($peopletag, $user)
792 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
793 if (!$oprofile instanceof Ostatus_profile) {
797 // Drop the PuSH subscription if there are no other subscribers.
798 $oprofile->garbageCollect();
800 $sub = Profile::getKV($user->id);
801 $tagger = Profile::getKV($peopletag->tagger);
803 $act = new Activity();
804 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
807 common_date_iso8601(time()));
809 $act->actor = $member->asActivityObject();
810 $act->verb = ActivityVerb::UNFOLLOW;
811 $act->object = $oprofile->asActivityObject();
814 // TRANS: Title for unfollowing a remote list.
815 $act->title = _m('Unfollow list');
816 // TRANS: Success message for remote list unfollow through OStatus.
817 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
818 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
820 $oprofile->getBestName(),
821 $tagger->getBestName());
823 $oprofile->notifyActivity($act, $user);
827 * Notify remote users when their notices get favorited.
829 * @param Profile or User $profile of local user doing the faving
830 * @param Notice $notice being favored
831 * @return hook return value
833 function onEndFavorNotice(Profile $profile, Notice $notice)
835 // Only distribute local users' favor actions, remote users
836 // will have already distributed theirs.
837 if (!$profile->isLocal()) {
841 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
842 if (!$oprofile instanceof Ostatus_profile) {
846 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
847 'notice_id' => $notice->id));
849 if (!$fav instanceof Fave) {
851 // TODO: Make pkeyGet throw exception, since this is a critical failure.
855 $act = $fav->asActivity();
857 $oprofile->notifyActivity($act, $profile);
863 * Notify remote user it has got a new people tag
864 * - tag verb is queued
865 * - the subscription is done immediately if not present
867 * @param Profile_tag $ptag the people tag that was created
868 * @return hook return value
869 * @throws Exception of various kinds, some from $oprofile->subscribe();
871 function onEndTagProfile($ptag)
873 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
874 if (!$oprofile instanceof Ostatus_profile) {
878 $plist = $ptag->getMeta();
879 if ($plist->private) {
883 $act = new Activity();
885 $tagger = $plist->getTagger();
886 $tagged = Profile::getKV('id', $ptag->tagged);
888 $act->verb = ActivityVerb::TAG;
889 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
890 $plist->tagger, $plist->id,
891 common_date_iso8601(time()));
893 // TRANS: Title for listing a remote profile.
894 $act->title = _m('TITLE','List');
895 // TRANS: Success message for remote list addition through OStatus.
896 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
897 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
898 $tagger->getBestName(),
899 $tagged->getBestName(),
900 $plist->getBestName());
902 $act->actor = $tagger->asActivityObject();
903 $act->objects = array($tagged->asActivityObject());
904 $act->target = ActivityObject::fromPeopletag($plist);
906 $oprofile->notifyDeferred($act, $tagger);
908 // initiate a PuSH subscription for the person being tagged
909 $oprofile->subscribe();
914 * Notify remote user that a people tag has been removed
915 * - untag verb is queued
916 * - the subscription is undone immediately if not required
917 * i.e garbageCollect()'d
919 * @param Profile_tag $ptag the people tag that was deleted
920 * @return hook return value
922 function onEndUntagProfile($ptag)
924 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
925 if (!$oprofile instanceof Ostatus_profile) {
929 $plist = $ptag->getMeta();
930 if ($plist->private) {
934 $act = new Activity();
936 $tagger = $plist->getTagger();
937 $tagged = Profile::getKV('id', $ptag->tagged);
939 $act->verb = ActivityVerb::UNTAG;
940 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
941 $plist->tagger, $plist->id,
942 common_date_iso8601(time()));
944 // TRANS: Title for unlisting a remote profile.
945 $act->title = _m('TITLE','Unlist');
946 // TRANS: Success message for remote list removal through OStatus.
947 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
948 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
949 $tagger->getBestName(),
950 $tagged->getBestName(),
951 $plist->getBestName());
953 $act->actor = $tagger->asActivityObject();
954 $act->objects = array($tagged->asActivityObject());
955 $act->target = ActivityObject::fromPeopletag($plist);
957 $oprofile->notifyDeferred($act, $tagger);
959 // unsubscribe to PuSH feed if no more required
960 $oprofile->garbageCollect();
966 * Notify remote users when their notices get de-favorited.
968 * @param Profile $profile Profile person doing the de-faving
969 * @param Notice $notice Notice being favored
971 * @return hook return value
973 function onEndDisfavorNotice(Profile $profile, Notice $notice)
975 // Only distribute local users' disfavor actions, remote users
976 // will have already distributed theirs.
977 if (!$profile->isLocal()) {
981 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
982 if (!$oprofile instanceof Ostatus_profile) {
986 $act = new Activity();
988 $act->verb = ActivityVerb::UNFAVORITE;
989 $act->id = TagURI::mint('disfavor:%d:%d:%s',
992 common_date_iso8601(time()));
994 // TRANS: Title for unliking a remote notice.
995 $act->title = _m('Unlike');
996 // TRANS: Success message for remove a favorite notice through OStatus.
997 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
998 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
999 $profile->getBestName(),
1002 $act->actor = $profile->asActivityObject();
1003 $act->object = $notice->asActivityObject();
1005 $oprofile->notifyActivity($act, $profile);
1010 function onStartGetProfileUri($profile, &$uri)
1012 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1013 if ($oprofile instanceof Ostatus_profile) {
1014 $uri = $oprofile->uri;
1020 function onStartUserGroupHomeUrl($group, &$url)
1022 return $this->onStartUserGroupPermalink($group, $url);
1025 function onStartUserGroupPermalink($group, &$url)
1027 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1028 if ($oprofile instanceof Ostatus_profile) {
1029 // @fixme this should probably be in the user_group table
1030 // @fixme this uri not guaranteed to be a profile page
1031 $url = $oprofile->uri;
1036 function onStartShowSubscriptionsContent($action)
1038 $this->showEntityRemoteSubscribe($action);
1043 function onStartShowUserGroupsContent($action)
1045 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1050 function onEndShowSubscriptionsMiniList($action)
1052 $this->showEntityRemoteSubscribe($action);
1057 function onEndShowGroupsMiniList($action)
1059 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1064 function showEntityRemoteSubscribe($action, $target='ostatussub')
1066 $user = common_current_user();
1067 if ($user && ($user->id == $action->profile->id)) {
1068 $action->elementStart('div', 'entity_actions');
1069 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1070 'class' => 'entity_subscribe'));
1071 $action->element('a', array('href' => common_local_url($target),
1072 'class' => 'entity_remote_subscribe'),
1073 // TRANS: Link text for link to remote subscribe.
1075 $action->elementEnd('p');
1076 $action->elementEnd('div');
1081 * Ping remote profiles with updates to this profile.
1082 * Salmon pings are queued for background processing.
1084 function onEndBroadcastProfile(Profile $profile)
1086 $user = User::getKV('id', $profile->id);
1088 // Find foreign accounts I'm subscribed to that support Salmon pings.
1090 // @fixme we could run updates through the PuSH feed too,
1091 // in which case we can skip Salmon pings to folks who
1092 // are also subscribed to me.
1093 $sql = "SELECT * FROM ostatus_profile " .
1094 "WHERE profile_id IN " .
1095 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1097 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1098 $oprofile = new Ostatus_profile();
1099 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1101 if ($oprofile->N == 0) {
1102 common_debug("No OStatus remote subscribees for $profile->nickname");
1106 $act = new Activity();
1108 $act->verb = ActivityVerb::UPDATE_PROFILE;
1109 $act->id = TagURI::mint('update-profile:%d:%s',
1111 common_date_iso8601(time()));
1112 $act->time = time();
1113 // TRANS: Title for activity.
1114 $act->title = _m('Profile update');
1115 // TRANS: Ping text for remote profile update through OStatus.
1116 // TRANS: %s is user that updated their profile.
1117 $act->content = sprintf(_m('%s has updated their profile page.'),
1118 $profile->getBestName());
1120 $act->actor = $profile->asActivityObject();
1121 $act->object = $act->actor;
1123 while ($oprofile->fetch()) {
1124 $oprofile->notifyDeferred($act, $profile);
1130 function onStartProfileListItemActionElements($item, $profile=null)
1132 if (!common_logged_in()) {
1134 $profileUser = User::getKV('id', $item->profile->id);
1136 if (!empty($profileUser)) {
1138 if ($item instanceof Action) {
1140 $profile = $item->profile;
1142 $output = $item->out;
1145 // Add an OStatus subscribe
1146 $output->elementStart('li', 'entity_subscribe');
1147 $url = common_local_url('ostatusinit',
1148 array('nickname' => $profileUser->nickname));
1149 $output->element('a', array('href' => $url,
1150 'class' => 'entity_remote_subscribe'),
1151 // TRANS: Link text for a user to subscribe to an OStatus user.
1153 $output->elementEnd('li');
1155 $output->elementStart('li', 'entity_tag');
1156 $url = common_local_url('ostatustag',
1157 array('nickname' => $profileUser->nickname));
1158 $output->element('a', array('href' => $url,
1159 'class' => 'entity_remote_tag'),
1160 // TRANS: Link text for a user to list an OStatus user.
1162 $output->elementEnd('li');
1169 function onPluginVersion(array &$versions)
1171 $versions[] = array('name' => 'OStatus',
1172 'version' => GNUSOCIAL_VERSION,
1173 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1174 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1175 // TRANS: Plugin description.
1176 'rawdescription' => _m('Follow people across social networks that implement '.
1177 '<a href="http://ostatus.org/">OStatus</a>.'));
1183 * Utility function to check if the given URI is a canonical group profile
1184 * page, and if so return the ID number.
1186 * @param string $url
1187 * @return mixed int or false
1189 public static function localGroupFromUrl($url)
1191 $group = User_group::getKV('uri', $url);
1192 if ($group instanceof User_group) {
1193 if ($group->isLocal()) {
1197 // To find local groups which haven't had their uri fields filled out...
1198 // If the domain has changed since a subscriber got the URI, it'll
1200 $template = common_local_url('groupbyid', array('id' => '31337'));
1201 $template = preg_quote($template, '/');
1202 $template = str_replace('31337', '(\d+)', $template);
1203 if (preg_match("/$template/", $url, $matches)) {
1204 return intval($matches[1]);
1210 public function onStartProfileGetAtomFeed($profile, &$feed)
1212 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1214 if (!$oprofile instanceof Ostatus_profile) {
1218 $feed = $oprofile->feeduri;
1222 function onStartGetProfileFromURI($uri, &$profile)
1224 // Don't want to do Web-based discovery on our own server,
1225 // so we check locally first.
1227 $user = User::getKV('uri', $uri);
1229 if (!empty($user)) {
1230 $profile = $user->getProfile();
1234 // Now, check remotely
1237 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1238 $profile = $oprofile->localProfile();
1239 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1240 } catch (Exception $e) {
1241 return true; // It's not an OStatus profile as far as we know, continue event handling
1245 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1247 $author = $target->getProfile();
1248 $profiletype = $this->profileTypeString($author);
1249 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1250 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1254 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1256 if ($target->getObjectType() === ActivityObject::PERSON) {
1257 $this->addWebFingerPersonLinks($xrd, $target);
1261 $profiletype = $this->profileTypeString($target);
1262 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1264 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1266 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1267 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1268 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1270 // TODO - finalize where the redirect should go on the publisher
1271 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1272 common_local_url('ostatussub') . '?profile={uri}',
1273 null, // type not set
1274 true); // isTemplate
1279 protected function profileTypeString(Profile $target)
1281 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1282 switch ($target->getObjectType()) {
1283 case ActivityObject::PERSON:
1285 case ActivityObject::GROUP:
1288 throw new ServerException('Unknown profile type for WebFinger profile links');
1292 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1294 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1295 common_local_url('ApiTimelineUser',
1296 array('id' => $target->id, 'format' => 'atom')),
1297 'application/atom+xml');
1299 // Get this profile's keypair
1300 $magicsig = Magicsig::getKV('user_id', $target->id);
1301 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1302 $magicsig = Magicsig::generate($target->getUser());
1305 if (!$magicsig instanceof Magicsig) {
1306 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1308 if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1309 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1310 'data:application/magic-public-key,'. $magicsig->toString());
1311 // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1312 Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1316 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1318 list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
1321 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1322 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1325 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1326 $profile = $oprofile->checkAuthorship($activity);
1327 } catch (Exception $e) {
1328 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1335 public function onProfileDeleteRelated(Profile $profile, array &$related)
1337 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1338 $related[] = 'Ostatus_profile';
1340 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1341 $magicsig = Magicsig::getKV('user_id', $profile->id);
1342 if ($magicsig instanceof Magicsig) {
1343 $magicsig->delete();