]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge branch 'master' into testing
[quix0rs-gnu-social.git] / plugins / OStatus / OStatusPlugin.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-2010, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 /**
21  * @package OStatusPlugin
22  * @maintainer Brion Vibber <brion@status.net>
23  */
24
25 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
26
27 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/');
28
29 class FeedSubException extends Exception
30 {
31     function __construct($msg=null)
32     {
33         $type = get_class($this);
34         if ($msg) {
35             parent::__construct("$type: $msg");
36         } else {
37             parent::__construct($type);
38         }
39     }
40 }
41
42 class OStatusPlugin extends Plugin
43 {
44     /**
45      * Hook for RouterInitialized event.
46      *
47      * @param Net_URL_Mapper $m path-to-action mapper
48      * @return boolean hook return
49      */
50     function onRouterInitialized($m)
51     {
52         // Discovery actions
53         $m->connect('.well-known/host-meta',
54                     array('action' => 'hostmeta'));
55         $m->connect('main/xrd',
56                     array('action' => 'userxrd'));
57         $m->connect('main/ownerxrd',
58                     array('action' => 'ownerxrd'));
59         $m->connect('main/ostatus',
60                     array('action' => 'ostatusinit'));
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/ostatussub',
66                     array('action' => 'ostatussub'));
67         $m->connect('main/ostatusgroup',
68                     array('action' => 'ostatusgroup'));
69
70         // PuSH actions
71         $m->connect('main/push/hub', array('action' => 'pushhub'));
72
73         $m->connect('main/push/callback/:feed',
74                     array('action' => 'pushcallback'),
75                     array('feed' => '[0-9]+'));
76
77         // Salmon endpoint
78         $m->connect('main/salmon/user/:id',
79                     array('action' => 'usersalmon'),
80                     array('id' => '[0-9]+'));
81         $m->connect('main/salmon/group/:id',
82                     array('action' => 'groupsalmon'),
83                     array('id' => '[0-9]+'));
84         return true;
85     }
86
87     /**
88      * Set up queue handlers for outgoing hub pushes
89      * @param QueueManager $qm
90      * @return boolean hook return
91      */
92     function onEndInitializeQueueManager(QueueManager $qm)
93     {
94         // Prepare outgoing distributions after notice save.
95         $qm->connect('ostatus', 'OStatusQueueHandler');
96
97         // Outgoing from our internal PuSH hub
98         $qm->connect('hubconf', 'HubConfQueueHandler');
99         $qm->connect('hubprep', 'HubPrepQueueHandler');
100
101         $qm->connect('hubout', 'HubOutQueueHandler');
102
103         // Outgoing Salmon replies (when we don't need a return value)
104         $qm->connect('salmon', 'SalmonQueueHandler');
105
106         // Incoming from a foreign PuSH hub
107         $qm->connect('pushin', 'PushInQueueHandler');
108         return true;
109     }
110
111     /**
112      * Put saved notices into the queue for pubsub distribution.
113      */
114     function onStartEnqueueNotice($notice, &$transports)
115     {
116         if ($notice->isLocal()) {
117             // put our transport first, in case there's any conflict (like OMB)
118             array_unshift($transports, 'ostatus');
119         }
120         return true;
121     }
122
123     /**
124      * Add a link header for LRDD Discovery
125      */
126     function onStartShowHTML($action)
127     {
128         if ($action instanceof ShowstreamAction) {
129             $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
130             $url = common_local_url('userxrd');
131             $url.= '?uri='. $acct;
132
133             header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
134         }
135     }
136
137     /**
138      * Set up a PuSH hub link to our internal link for canonical timeline
139      * Atom feeds for users and groups.
140      */
141     function onStartApiAtom($feed)
142     {
143         $id = null;
144
145         if ($feed instanceof AtomUserNoticeFeed) {
146             $salmonAction = 'usersalmon';
147             $user = $feed->getUser();
148             $id   = $user->id;
149             $profile = $user->getProfile();
150             $feed->setActivitySubject($profile->asActivityNoun('subject'));
151         } else if ($feed instanceof AtomGroupNoticeFeed) {
152             $salmonAction = 'groupsalmon';
153             $group = $feed->getGroup();
154             $id = $group->id;
155             $feed->setActivitySubject($group->asActivitySubject());
156         } else {
157             return true;
158         }
159
160         if (!empty($id)) {
161             $hub = common_config('ostatus', 'hub');
162             if (empty($hub)) {
163                 // Updates will be handled through our internal PuSH hub.
164                 $hub = common_local_url('pushhub');
165             }
166             $feed->addLink($hub, array('rel' => 'hub'));
167
168             // Also, we'll add in the salmon link
169             $salmon = common_local_url($salmonAction, array('id' => $id));
170             $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
171
172             // XXX: these are deprecated
173             $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
174             $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
175         }
176
177         return true;
178     }
179
180     /**
181      * Automatically load the actions and libraries used by the plugin
182      *
183      * @param Class $cls the class
184      *
185      * @return boolean hook return
186      *
187      */
188     function onAutoload($cls)
189     {
190         $base = dirname(__FILE__);
191         $lower = strtolower($cls);
192         $map = array('activityverb' => 'activity',
193                      'activityobject' => 'activity',
194                      'activityutils' => 'activity');
195         if (isset($map[$lower])) {
196             $lower = $map[$lower];
197         }
198         $files = array("$base/classes/$cls.php",
199                        "$base/lib/$lower.php");
200         if (substr($lower, -6) == 'action') {
201             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
202         }
203         foreach ($files as $file) {
204             if (file_exists($file)) {
205                 include_once $file;
206                 return false;
207             }
208         }
209         return true;
210     }
211
212     /**
213      * Add in an OStatus subscribe button
214      */
215     function onStartProfileRemoteSubscribe($output, $profile)
216     {
217         $cur = common_current_user();
218
219         if (empty($cur)) {
220             // Add an OStatus subscribe
221             $output->elementStart('li', 'entity_subscribe');
222             $url = common_local_url('ostatusinit',
223                                     array('nickname' => $profile->nickname));
224             $output->element('a', array('href' => $url,
225                                         'class' => 'entity_remote_subscribe'),
226                                 _m('Subscribe'));
227
228             $output->elementEnd('li');
229         }
230
231         return false;
232     }
233
234     function onStartGroupSubscribe($output, $group)
235     {
236         $cur = common_current_user();
237
238         if (empty($cur)) {
239             // Add an OStatus subscribe
240             $url = common_local_url('ostatusinit',
241                                     array('group' => $group->nickname));
242             $output->element('a', array('href' => $url,
243                                         'class' => 'entity_remote_subscribe'),
244                                 _m('Join'));
245         }
246
247         return true;
248     }
249
250     /**
251      * Find any explicit remote mentions. Accepted forms:
252      *   Webfinger: @user@example.com
253      *   Profile link: @example.com/mublog/user
254      * @param Profile $sender (os user?)
255      * @param string $text input markup text
256      * @param array &$mention in/out param: set of found mentions
257      * @return boolean hook return value
258      */
259
260     function onEndFindMentions($sender, $text, &$mentions)
261     {
262         $matches = array();
263
264         // Webfinger matches: @user@example.com
265         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
266                        $text,
267                        $wmatches,
268                        PREG_OFFSET_CAPTURE)) {
269             foreach ($wmatches[1] as $wmatch) {
270                 list($target, $pos) = $wmatch;
271                 $this->log(LOG_INFO, "Checking webfinger '$target'");
272                 try {
273                     $oprofile = Ostatus_profile::ensureWebfinger($target);
274                     if ($oprofile && !$oprofile->isGroup()) {
275                         $profile = $oprofile->localProfile();
276                         $matches[$pos] = array('mentioned' => array($profile),
277                                                'text' => $target,
278                                                'position' => $pos,
279                                                'url' => $profile->profileurl);
280                     }
281                 } catch (Exception $e) {
282                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
283                 }
284             }
285         }
286
287         // Profile matches: @example.com/mublog/user
288         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
289                        $text,
290                        $wmatches,
291                        PREG_OFFSET_CAPTURE)) {
292             foreach ($wmatches[1] as $wmatch) {
293                 list($target, $pos) = $wmatch;
294                 $schemes = array('http', 'https');
295                 foreach ($schemes as $scheme) {
296                     $url = "$scheme://$target";
297                     $this->log(LOG_INFO, "Checking profile address '$url'");
298                     try {
299                         $oprofile = Ostatus_profile::ensureProfileURL($url);
300                         if ($oprofile && !$oprofile->isGroup()) {
301                             $profile = $oprofile->localProfile();
302                             $matches[$pos] = array('mentioned' => array($profile),
303                                                    'text' => $target,
304                                                    'position' => $pos,
305                                                    'url' => $profile->profileurl);
306                             break;
307                         }
308                     } catch (Exception $e) {
309                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
310                     }
311                 }
312             }
313         }
314
315         foreach ($mentions as $i => $other) {
316             // If we share a common prefix with a local user, override it!
317             $pos = $other['position'];
318             if (isset($matches[$pos])) {
319                 $mentions[$i] = $matches[$pos];
320                 unset($matches[$pos]);
321             }
322         }
323         foreach ($matches as $mention) {
324             $mentions[] = $mention;
325         }
326
327         return true;
328     }
329
330     /**
331      * Allow remote profile references to be used in commands:
332      *   sub update@status.net
333      *   whois evan@identi.ca
334      *   reply http://identi.ca/evan hey what's up
335      *
336      * @param Command $command
337      * @param string $arg
338      * @param Profile &$profile
339      * @return hook return code
340      */
341     function onStartCommandGetProfile($command, $arg, &$profile)
342     {
343         $oprofile = $this->pullRemoteProfile($arg);
344         if ($oprofile && !$oprofile->isGroup()) {
345             $profile = $oprofile->localProfile();
346             return false;
347         } else {
348             return true;
349         }
350     }
351
352     /**
353      * Allow remote group references to be used in commands:
354      *   join group+statusnet@identi.ca
355      *   join http://identi.ca/group/statusnet
356      *   drop identi.ca/group/statusnet
357      *
358      * @param Command $command
359      * @param string $arg
360      * @param User_group &$group
361      * @return hook return code
362      */
363     function onStartCommandGetGroup($command, $arg, &$group)
364     {
365         $oprofile = $this->pullRemoteProfile($arg);
366         if ($oprofile && $oprofile->isGroup()) {
367             $group = $oprofile->localGroup();
368             return false;
369         } else {
370             return true;
371         }
372     }
373
374     protected function pullRemoteProfile($arg)
375     {
376         $oprofile = null;
377         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
378             // webfinger lookup
379             try {
380                 return Ostatus_profile::ensureWebfinger($arg);
381             } catch (Exception $e) {
382                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
383                                     $arg . ': ' . $e->getMessage());
384             }
385         }
386
387         // Look for profile URLs, with or without scheme:
388         $urls = array();
389         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
390             $urls[] = $arg;
391         }
392         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
393             $schemes = array('http', 'https');
394             foreach ($schemes as $scheme) {
395                 $urls[] = "$scheme://$arg";
396             }
397         }
398
399         foreach ($urls as $url) {
400             try {
401                 return Ostatus_profile::ensureProfileURL($url);
402             } catch (Exception $e) {
403                 common_log(LOG_ERR, 'Profile lookup failed for ' .
404                                     $arg . ': ' . $e->getMessage());
405             }
406         }
407         return null;
408     }
409
410     /**
411      * Make sure necessary tables are filled out.
412      */
413     function onCheckSchema() {
414         $schema = Schema::get();
415         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
416         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
417         $schema->ensureTable('feedsub', FeedSub::schemaDef());
418         $schema->ensureTable('hubsub', HubSub::schemaDef());
419         $schema->ensureTable('magicsig', Magicsig::schemaDef());
420         return true;
421     }
422
423     function onEndShowStatusNetStyles($action) {
424         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
425         return true;
426     }
427
428     function onEndShowStatusNetScripts($action) {
429         $action->script('plugins/OStatus/js/ostatus.js');
430         return true;
431     }
432
433     /**
434      * Override the "from ostatus" bit in notice lists to link to the
435      * original post and show the domain it came from.
436      *
437      * @param Notice in $notice
438      * @param string out &$name
439      * @param string out &$url
440      * @param string out &$title
441      * @return mixed hook return code
442      */
443     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
444     {
445         if ($notice->source == 'ostatus') {
446             if ($notice->url) {
447                 $bits = parse_url($notice->url);
448                 $domain = $bits['host'];
449                 if (substr($domain, 0, 4) == 'www.') {
450                     $name = substr($domain, 4);
451                 } else {
452                     $name = $domain;
453                 }
454
455                 $url = $notice->url;
456                 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
457                 return false;
458             }
459         }
460         return true;
461     }
462
463     /**
464      * Send incoming PuSH feeds for OStatus endpoints in for processing.
465      *
466      * @param FeedSub $feedsub
467      * @param DOMDocument $feed
468      * @return mixed hook return code
469      */
470     function onStartFeedSubReceive($feedsub, $feed)
471     {
472         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
473         if ($oprofile) {
474             $oprofile->processFeed($feed, 'push');
475         } else {
476             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
477         }
478     }
479
480     /**
481      * Tell the FeedSub infrastructure whether we have any active OStatus
482      * usage for the feed; if not it'll be able to garbage-collect the
483      * feed subscription.
484      *
485      * @param FeedSub $feedsub
486      * @param integer $count in/out
487      * @return mixed hook return code
488      */
489     function onFeedSubSubscriberCount($feedsub, &$count)
490     {
491         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
492         if ($oprofile) {
493             $count += $oprofile->subscriberCount();
494         }
495         return true;
496     }
497
498     /**
499      * When about to subscribe to a remote user, start a server-to-server
500      * PuSH subscription if needed. If we can't establish that, abort.
501      *
502      * @fixme If something else aborts later, we could end up with a stray
503      *        PuSH subscription. This is relatively harmless, though.
504      *
505      * @param Profile $subscriber
506      * @param Profile $other
507      *
508      * @return hook return code
509      *
510      * @throws Exception
511      */
512     function onStartSubscribe($subscriber, $other)
513     {
514         $user = User::staticGet('id', $subscriber->id);
515
516         if (empty($user)) {
517             return true;
518         }
519
520         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
521
522         if (empty($oprofile)) {
523             return true;
524         }
525
526         if (!$oprofile->subscribe()) {
527             throw new Exception(_m('Could not set up remote subscription.'));
528         }
529     }
530
531     /**
532      * Having established a remote subscription, send a notification to the
533      * remote OStatus profile's endpoint.
534      *
535      * @param Profile $subscriber
536      * @param Profile $other
537      *
538      * @return hook return code
539      *
540      * @throws Exception
541      */
542     function onEndSubscribe($subscriber, $other)
543     {
544         $user = User::staticGet('id', $subscriber->id);
545
546         if (empty($user)) {
547             return true;
548         }
549
550         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
551
552         if (empty($oprofile)) {
553             return true;
554         }
555
556         $act = new Activity();
557
558         $act->verb = ActivityVerb::FOLLOW;
559
560         $act->id   = TagURI::mint('follow:%d:%d:%s',
561                                   $subscriber->id,
562                                   $other->id,
563                                   common_date_iso8601(time()));
564
565         $act->time    = time();
566         $act->title   = _("Follow");
567         $act->content = sprintf(_("%s is now following %s."),
568                                $subscriber->getBestName(),
569                                $other->getBestName());
570
571         $act->actor   = ActivityObject::fromProfile($subscriber);
572         $act->object  = ActivityObject::fromProfile($other);
573
574         $oprofile->notifyActivity($act, $subscriber);
575
576         return true;
577     }
578
579     /**
580      * Notify remote server and garbage collect unused feeds on unsubscribe.
581      * @fixme send these operations to background queues
582      *
583      * @param User $user
584      * @param Profile $other
585      * @return hook return value
586      */
587     function onEndUnsubscribe($profile, $other)
588     {
589         $user = User::staticGet('id', $profile->id);
590
591         if (empty($user)) {
592             return true;
593         }
594
595         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
596
597         if (empty($oprofile)) {
598             return true;
599         }
600
601         // Drop the PuSH subscription if there are no other subscribers.
602         $oprofile->garbageCollect();
603
604         $act = new Activity();
605
606         $act->verb = ActivityVerb::UNFOLLOW;
607
608         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
609                                   $profile->id,
610                                   $other->id,
611                                   common_date_iso8601(time()));
612
613         $act->time    = time();
614         $act->title   = _("Unfollow");
615         $act->content = sprintf(_("%s stopped following %s."),
616                                $profile->getBestName(),
617                                $other->getBestName());
618
619         $act->actor   = ActivityObject::fromProfile($profile);
620         $act->object  = ActivityObject::fromProfile($other);
621
622         $oprofile->notifyActivity($act, $profile);
623
624         return true;
625     }
626
627     /**
628      * When one of our local users tries to join a remote group,
629      * notify the remote server. If the notification is rejected,
630      * deny the join.
631      *
632      * @param User_group $group
633      * @param User $user
634      *
635      * @return mixed hook return value
636      */
637
638     function onStartJoinGroup($group, $user)
639     {
640         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
641         if ($oprofile) {
642             if (!$oprofile->subscribe()) {
643                 throw new Exception(_m('Could not set up remote group membership.'));
644             }
645
646             $member = Profile::staticGet($user->id);
647
648             $act = new Activity();
649             $act->id = TagURI::mint('join:%d:%d:%s',
650                                     $member->id,
651                                     $group->id,
652                                     common_date_iso8601(time()));
653
654             $act->actor = ActivityObject::fromProfile($member);
655             $act->verb = ActivityVerb::JOIN;
656             $act->object = $oprofile->asActivityObject();
657
658             $act->time = time();
659             $act->title = _m("Join");
660             $act->content = sprintf(_m("%s has joined group %s."),
661                                     $member->getBestName(),
662                                     $oprofile->getBestName());
663
664             if ($oprofile->notifyActivity($act, $member)) {
665                 return true;
666             } else {
667                 $oprofile->garbageCollect();
668                 throw new Exception(_m("Failed joining remote group."));
669             }
670         }
671     }
672
673     /**
674      * When one of our local users leaves a remote group, notify the remote
675      * server.
676      *
677      * @fixme Might be good to schedule a resend of the leave notification
678      * if it failed due to a transitory error. We've canceled the local
679      * membership already anyway, but if the remote server comes back up
680      * it'll be left with a stray membership record.
681      *
682      * @param User_group $group
683      * @param User $user
684      *
685      * @return mixed hook return value
686      */
687
688     function onEndLeaveGroup($group, $user)
689     {
690         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
691         if ($oprofile) {
692             // Drop the PuSH subscription if there are no other subscribers.
693             $oprofile->garbageCollect();
694
695             $member = Profile::staticGet($user->id);
696
697             $act = new Activity();
698             $act->id = TagURI::mint('leave:%d:%d:%s',
699                                     $member->id,
700                                     $group->id,
701                                     common_date_iso8601(time()));
702
703             $act->actor = ActivityObject::fromProfile($member);
704             $act->verb = ActivityVerb::LEAVE;
705             $act->object = $oprofile->asActivityObject();
706
707             $act->time = time();
708             $act->title = _m("Leave");
709             $act->content = sprintf(_m("%s has left group %s."),
710                                     $member->getBestName(),
711                                     $oprofile->getBestName());
712
713             $oprofile->notifyActivity($act, $member);
714         }
715     }
716
717     /**
718      * Notify remote users when their notices get favorited.
719      *
720      * @param Profile or User $profile of local user doing the faving
721      * @param Notice $notice being favored
722      * @return hook return value
723      */
724
725     function onEndFavorNotice(Profile $profile, Notice $notice)
726     {
727         $user = User::staticGet('id', $profile->id);
728
729         if (empty($user)) {
730             return true;
731         }
732
733         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
734
735         if (empty($oprofile)) {
736             return true;
737         }
738
739         $act = new Activity();
740
741         $act->verb = ActivityVerb::FAVORITE;
742         $act->id   = TagURI::mint('favor:%d:%d:%s',
743                                   $profile->id,
744                                   $notice->id,
745                                   common_date_iso8601(time()));
746
747         $act->time    = time();
748         $act->title   = _("Favor");
749         $act->content = sprintf(_("%s marked notice %s as a favorite."),
750                                $profile->getBestName(),
751                                $notice->uri);
752
753         $act->actor   = ActivityObject::fromProfile($profile);
754         $act->object  = ActivityObject::fromNotice($notice);
755
756         $oprofile->notifyActivity($act, $profile);
757
758         return true;
759     }
760
761     /**
762      * Notify remote users when their notices get de-favorited.
763      *
764      * @param Profile $profile Profile person doing the de-faving
765      * @param Notice  $notice  Notice being favored
766      *
767      * @return hook return value
768      */
769
770     function onEndDisfavorNotice(Profile $profile, Notice $notice)
771     {
772         $user = User::staticGet('id', $profile->id);
773
774         if (empty($user)) {
775             return true;
776         }
777
778         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
779
780         if (empty($oprofile)) {
781             return true;
782         }
783
784         $act = new Activity();
785
786         $act->verb = ActivityVerb::UNFAVORITE;
787         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
788                                   $profile->id,
789                                   $notice->id,
790                                   common_date_iso8601(time()));
791         $act->time    = time();
792         $act->title   = _("Disfavor");
793         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
794                                $profile->getBestName(),
795                                $notice->uri);
796
797         $act->actor   = ActivityObject::fromProfile($profile);
798         $act->object  = ActivityObject::fromNotice($notice);
799
800         $oprofile->notifyActivity($act, $profile);
801
802         return true;
803     }
804
805     function onStartGetProfileUri($profile, &$uri)
806     {
807         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
808         if (!empty($oprofile)) {
809             $uri = $oprofile->uri;
810             return false;
811         }
812         return true;
813     }
814
815     function onStartUserGroupHomeUrl($group, &$url)
816     {
817         return $this->onStartUserGroupPermalink($group, $url);
818     }
819
820     function onStartUserGroupPermalink($group, &$url)
821     {
822         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
823         if ($oprofile) {
824             // @fixme this should probably be in the user_group table
825             // @fixme this uri not guaranteed to be a profile page
826             $url = $oprofile->uri;
827             return false;
828         }
829     }
830
831     function onStartShowSubscriptionsContent($action)
832     {
833         $this->showEntityRemoteSubscribe($action);
834
835         return true;
836     }
837
838     function onStartShowUserGroupsContent($action)
839     {
840         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
841
842         return true;
843     }
844
845     function onEndShowSubscriptionsMiniList($action)
846     {
847         $this->showEntityRemoteSubscribe($action);
848
849         return true;
850     }
851
852     function onEndShowGroupsMiniList($action)
853     {
854         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
855
856         return true;
857     }
858
859     function showEntityRemoteSubscribe($action, $target='ostatussub')
860     {
861         $user = common_current_user();
862         if ($user && ($user->id == $action->profile->id)) {
863             $action->elementStart('div', 'entity_actions');
864             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
865                                              'class' => 'entity_subscribe'));
866             $action->element('a', array('href' => common_local_url($target),
867                                         'class' => 'entity_remote_subscribe')
868                                 , _m('Remote'));
869             $action->elementEnd('p');
870             $action->elementEnd('div');
871         }
872     }
873
874     /**
875      * Ping remote profiles with updates to this profile.
876      * Salmon pings are queued for background processing.
877      */
878     function onEndBroadcastProfile(Profile $profile)
879     {
880         $user = User::staticGet('id', $profile->id);
881
882         // Find foreign accounts I'm subscribed to that support Salmon pings.
883         //
884         // @fixme we could run updates through the PuSH feed too,
885         // in which case we can skip Salmon pings to folks who
886         // are also subscribed to me.
887         $sql = "SELECT * FROM ostatus_profile " .
888                "WHERE profile_id IN " .
889                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
890                "OR group_id IN " .
891                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
892         $oprofile = new Ostatus_profile();
893         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
894
895         if ($oprofile->N == 0) {
896             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
897             return true;
898         }
899
900         $act = new Activity();
901
902         $act->verb = ActivityVerb::UPDATE_PROFILE;
903         $act->id   = TagURI::mint('update-profile:%d:%s',
904                                   $profile->id,
905                                   common_date_iso8601(time()));
906         $act->time    = time();
907         $act->title   = _m("Profile update");
908         $act->content = sprintf(_m("%s has updated their profile page."),
909                                $profile->getBestName());
910
911         $act->actor   = ActivityObject::fromProfile($profile);
912         $act->object  = $act->actor;
913
914         while ($oprofile->fetch()) {
915             $oprofile->notifyDeferred($act, $profile);
916         }
917
918         return true;
919     }
920
921     function onStartProfileListItemActionElements($item)
922     {
923         if (!common_logged_in()) {
924
925             $profileUser = User::staticGet('id', $item->profile->id);
926
927             if (!empty($profileUser)) {
928
929                 $output = $item->out;
930
931                 // Add an OStatus subscribe
932                 $output->elementStart('li', 'entity_subscribe');
933                 $url = common_local_url('ostatusinit',
934                                         array('nickname' => $profileUser->nickname));
935                 $output->element('a', array('href' => $url,
936                                             'class' => 'entity_remote_subscribe'),
937                                  _m('Subscribe'));
938                 $output->elementEnd('li');
939             }
940         }
941
942         return true;
943     }
944
945     function onPluginVersion(&$versions)
946     {
947         $versions[] = array('name' => 'OStatus',
948                             'version' => STATUSNET_VERSION,
949                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
950                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
951                             'rawdescription' =>
952                             _m('Follow people across social networks that implement '.
953                                '<a href="http://ostatus.org/">OStatus</a>.'));
954
955         return true;
956     }
957
958     /**
959      * Utility function to check if the given URL is a canonical group profile
960      * page, and if so return the ID number.
961      *
962      * @param string $url
963      * @return mixed int or false
964      */
965     public static function localGroupFromUrl($url)
966     {
967         $template = common_local_url('groupbyid', array('id' => '31337'));
968         $template = preg_quote($template, '/');
969         $template = str_replace('31337', '(\d+)', $template);
970         if (preg_match("/$template/", $url, $matches)) {
971             return intval($matches[1]);
972         }
973         return false;
974     }
975
976     public function onStartProfileGetAtomFeed($profile, &$feed)
977     {
978         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
979
980         if (empty($oprofile)) {
981             return true;
982         }
983
984         $feed = $oprofile->feeduri;
985         return false;
986     }
987
988     function onStartGetProfileFromURI($uri, &$profile) {
989
990         // XXX: do discovery here instead (OStatus_profile::ensureProfileURI($uri))
991
992         $oprofile = Ostatus_profile::staticGet('uri', $uri);
993
994         if (!empty($oprofile) && !$oprofile->isGroup()) {
995             $profile = $oprofile->localProfile();
996             return false;
997         }
998
999         return true;
1000     }
1001 }