]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge remote branch 'chat-interface-plugins/msn-plugin' into 1.0.x
[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      * Check if we've got remote replies to send via Salmon.
252      *
253      * @fixme push webfinger lookup & sending to a background queue
254      * @fixme also detect short-form name for remote subscribees where not ambiguous
255      */
256
257     function onEndNoticeSave($notice)
258     {
259     }
260
261     /**
262      * Find any explicit remote mentions. Accepted forms:
263      *   Webfinger: @user@example.com
264      *   Profile link: @example.com/mublog/user
265      * @param Profile $sender (os user?)
266      * @param string $text input markup text
267      * @param array &$mention in/out param: set of found mentions
268      * @return boolean hook return value
269      */
270
271     function onEndFindMentions($sender, $text, &$mentions)
272     {
273         $matches = array();
274
275         // Webfinger matches: @user@example.com
276         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
277                        $text,
278                        $wmatches,
279                        PREG_OFFSET_CAPTURE)) {
280             foreach ($wmatches[1] as $wmatch) {
281                 list($target, $pos) = $wmatch;
282                 $this->log(LOG_INFO, "Checking webfinger '$target'");
283                 try {
284                     $oprofile = Ostatus_profile::ensureWebfinger($target);
285                     if ($oprofile && !$oprofile->isGroup()) {
286                         $profile = $oprofile->localProfile();
287                         $matches[$pos] = array('mentioned' => array($profile),
288                                                'text' => $target,
289                                                'position' => $pos,
290                                                'url' => $profile->profileurl);
291                     }
292                 } catch (Exception $e) {
293                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
294                 }
295             }
296         }
297
298         // Profile matches: @example.com/mublog/user
299         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
300                        $text,
301                        $wmatches,
302                        PREG_OFFSET_CAPTURE)) {
303             foreach ($wmatches[1] as $wmatch) {
304                 list($target, $pos) = $wmatch;
305                 $schemes = array('http', 'https');
306                 foreach ($schemes as $scheme) {
307                     $url = "$scheme://$target";
308                     $this->log(LOG_INFO, "Checking profile address '$url'");
309                     try {
310                         $oprofile = Ostatus_profile::ensureProfileURL($url);
311                         if ($oprofile && !$oprofile->isGroup()) {
312                             $profile = $oprofile->localProfile();
313                             $matches[$pos] = array('mentioned' => array($profile),
314                                                    'text' => $target,
315                                                    'position' => $pos,
316                                                    'url' => $profile->profileurl);
317                             break;
318                         }
319                     } catch (Exception $e) {
320                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
321                     }
322                 }
323             }
324         }
325
326         foreach ($mentions as $i => $other) {
327             // If we share a common prefix with a local user, override it!
328             $pos = $other['position'];
329             if (isset($matches[$pos])) {
330                 $mentions[$i] = $matches[$pos];
331                 unset($matches[$pos]);
332             }
333         }
334         foreach ($matches as $mention) {
335             $mentions[] = $mention;
336         }
337
338         return true;
339     }
340
341     /**
342      * Allow remote profile references to be used in commands:
343      *   sub update@status.net
344      *   whois evan@identi.ca
345      *   reply http://identi.ca/evan hey what's up
346      *
347      * @param Command $command
348      * @param string $arg
349      * @param Profile &$profile
350      * @return hook return code
351      */
352     function onStartCommandGetProfile($command, $arg, &$profile)
353     {
354         $oprofile = $this->pullRemoteProfile($arg);
355         if ($oprofile && !$oprofile->isGroup()) {
356             $profile = $oprofile->localProfile();
357             return false;
358         } else {
359             return true;
360         }
361     }
362
363     /**
364      * Allow remote group references to be used in commands:
365      *   join group+statusnet@identi.ca
366      *   join http://identi.ca/group/statusnet
367      *   drop identi.ca/group/statusnet
368      *
369      * @param Command $command
370      * @param string $arg
371      * @param User_group &$group
372      * @return hook return code
373      */
374     function onStartCommandGetGroup($command, $arg, &$group)
375     {
376         $oprofile = $this->pullRemoteProfile($arg);
377         if ($oprofile && $oprofile->isGroup()) {
378             $group = $oprofile->localGroup();
379             return false;
380         } else {
381             return true;
382         }
383     }
384
385     protected function pullRemoteProfile($arg)
386     {
387         $oprofile = null;
388         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
389             // webfinger lookup
390             try {
391                 return Ostatus_profile::ensureWebfinger($arg);
392             } catch (Exception $e) {
393                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
394                                     $arg . ': ' . $e->getMessage());
395             }
396         }
397
398         // Look for profile URLs, with or without scheme:
399         $urls = array();
400         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
401             $urls[] = $arg;
402         }
403         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
404             $schemes = array('http', 'https');
405             foreach ($schemes as $scheme) {
406                 $urls[] = "$scheme://$arg";
407             }
408         }
409
410         foreach ($urls as $url) {
411             try {
412                 return Ostatus_profile::ensureProfileURL($url);
413             } catch (Exception $e) {
414                 common_log(LOG_ERR, 'Profile lookup failed for ' .
415                                     $arg . ': ' . $e->getMessage());
416             }
417         }
418         return null;
419     }
420
421     /**
422      * Make sure necessary tables are filled out.
423      */
424     function onCheckSchema() {
425         $schema = Schema::get();
426         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
427         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
428         $schema->ensureTable('feedsub', FeedSub::schemaDef());
429         $schema->ensureTable('hubsub', HubSub::schemaDef());
430         $schema->ensureTable('magicsig', Magicsig::schemaDef());
431         return true;
432     }
433
434     function onEndShowStatusNetStyles($action) {
435         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
436         return true;
437     }
438
439     function onEndShowStatusNetScripts($action) {
440         $action->script('plugins/OStatus/js/ostatus.js');
441         return true;
442     }
443
444     /**
445      * Override the "from ostatus" bit in notice lists to link to the
446      * original post and show the domain it came from.
447      *
448      * @param Notice in $notice
449      * @param string out &$name
450      * @param string out &$url
451      * @param string out &$title
452      * @return mixed hook return code
453      */
454     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
455     {
456         if ($notice->source == 'ostatus') {
457             if ($notice->url) {
458                 $bits = parse_url($notice->url);
459                 $domain = $bits['host'];
460                 if (substr($domain, 0, 4) == 'www.') {
461                     $name = substr($domain, 4);
462                 } else {
463                     $name = $domain;
464                 }
465
466                 $url = $notice->url;
467                 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
468                 return false;
469             }
470         }
471         return true;
472     }
473
474     /**
475      * Send incoming PuSH feeds for OStatus endpoints in for processing.
476      *
477      * @param FeedSub $feedsub
478      * @param DOMDocument $feed
479      * @return mixed hook return code
480      */
481     function onStartFeedSubReceive($feedsub, $feed)
482     {
483         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
484         if ($oprofile) {
485             $oprofile->processFeed($feed, 'push');
486         } else {
487             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
488         }
489     }
490
491     /**
492      * Tell the FeedSub infrastructure whether we have any active OStatus
493      * usage for the feed; if not it'll be able to garbage-collect the
494      * feed subscription.
495      * 
496      * @param FeedSub $feedsub
497      * @param integer $count in/out
498      * @return mixed hook return code
499      */
500     function onFeedSubSubscriberCount($feedsub, &$count)
501     {
502         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
503         if ($oprofile) {
504             $count += $oprofile->subscriberCount();
505         }
506         return true;
507     }
508
509     /**
510      * When about to subscribe to a remote user, start a server-to-server
511      * PuSH subscription if needed. If we can't establish that, abort.
512      *
513      * @fixme If something else aborts later, we could end up with a stray
514      *        PuSH subscription. This is relatively harmless, though.
515      *
516      * @param Profile $subscriber
517      * @param Profile $other
518      *
519      * @return hook return code
520      *
521      * @throws Exception
522      */
523     function onStartSubscribe($subscriber, $other)
524     {
525         $user = User::staticGet('id', $subscriber->id);
526
527         if (empty($user)) {
528             return true;
529         }
530
531         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
532
533         if (empty($oprofile)) {
534             return true;
535         }
536
537         if (!$oprofile->subscribe()) {
538             throw new Exception(_m('Could not set up remote subscription.'));
539         }
540     }
541
542     /**
543      * Having established a remote subscription, send a notification to the
544      * remote OStatus profile's endpoint.
545      *
546      * @param Profile $subscriber
547      * @param Profile $other
548      *
549      * @return hook return code
550      *
551      * @throws Exception
552      */
553     function onEndSubscribe($subscriber, $other)
554     {
555         $user = User::staticGet('id', $subscriber->id);
556
557         if (empty($user)) {
558             return true;
559         }
560
561         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
562
563         if (empty($oprofile)) {
564             return true;
565         }
566
567         $act = new Activity();
568
569         $act->verb = ActivityVerb::FOLLOW;
570
571         $act->id   = TagURI::mint('follow:%d:%d:%s',
572                                   $subscriber->id,
573                                   $other->id,
574                                   common_date_iso8601(time()));
575
576         $act->time    = time();
577         $act->title   = _("Follow");
578         $act->content = sprintf(_("%s is now following %s."),
579                                $subscriber->getBestName(),
580                                $other->getBestName());
581
582         $act->actor   = ActivityObject::fromProfile($subscriber);
583         $act->object  = ActivityObject::fromProfile($other);
584
585         $oprofile->notifyActivity($act, $subscriber);
586
587         return true;
588     }
589
590     /**
591      * Notify remote server and garbage collect unused feeds on unsubscribe.
592      * @fixme send these operations to background queues
593      *
594      * @param User $user
595      * @param Profile $other
596      * @return hook return value
597      */
598     function onEndUnsubscribe($profile, $other)
599     {
600         $user = User::staticGet('id', $profile->id);
601
602         if (empty($user)) {
603             return true;
604         }
605
606         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
607
608         if (empty($oprofile)) {
609             return true;
610         }
611
612         // Drop the PuSH subscription if there are no other subscribers.
613         $oprofile->garbageCollect();
614
615         $act = new Activity();
616
617         $act->verb = ActivityVerb::UNFOLLOW;
618
619         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
620                                   $profile->id,
621                                   $other->id,
622                                   common_date_iso8601(time()));
623
624         $act->time    = time();
625         $act->title   = _("Unfollow");
626         $act->content = sprintf(_("%s stopped following %s."),
627                                $profile->getBestName(),
628                                $other->getBestName());
629
630         $act->actor   = ActivityObject::fromProfile($profile);
631         $act->object  = ActivityObject::fromProfile($other);
632
633         $oprofile->notifyActivity($act, $profile);
634
635         return true;
636     }
637
638     /**
639      * When one of our local users tries to join a remote group,
640      * notify the remote server. If the notification is rejected,
641      * deny the join.
642      *
643      * @param User_group $group
644      * @param User $user
645      *
646      * @return mixed hook return value
647      */
648
649     function onStartJoinGroup($group, $user)
650     {
651         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
652         if ($oprofile) {
653             if (!$oprofile->subscribe()) {
654                 throw new Exception(_m('Could not set up remote group membership.'));
655             }
656
657             $member = Profile::staticGet($user->id);
658
659             $act = new Activity();
660             $act->id = TagURI::mint('join:%d:%d:%s',
661                                     $member->id,
662                                     $group->id,
663                                     common_date_iso8601(time()));
664
665             $act->actor = ActivityObject::fromProfile($member);
666             $act->verb = ActivityVerb::JOIN;
667             $act->object = $oprofile->asActivityObject();
668
669             $act->time = time();
670             $act->title = _m("Join");
671             $act->content = sprintf(_m("%s has joined group %s."),
672                                     $member->getBestName(),
673                                     $oprofile->getBestName());
674
675             if ($oprofile->notifyActivity($act, $member)) {
676                 return true;
677             } else {
678                 $oprofile->garbageCollect();
679                 throw new Exception(_m("Failed joining remote group."));
680             }
681         }
682     }
683
684     /**
685      * When one of our local users leaves a remote group, notify the remote
686      * server.
687      *
688      * @fixme Might be good to schedule a resend of the leave notification
689      * if it failed due to a transitory error. We've canceled the local
690      * membership already anyway, but if the remote server comes back up
691      * it'll be left with a stray membership record.
692      *
693      * @param User_group $group
694      * @param User $user
695      *
696      * @return mixed hook return value
697      */
698
699     function onEndLeaveGroup($group, $user)
700     {
701         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
702         if ($oprofile) {
703             // Drop the PuSH subscription if there are no other subscribers.
704             $oprofile->garbageCollect();
705
706             $member = Profile::staticGet($user->id);
707
708             $act = new Activity();
709             $act->id = TagURI::mint('leave:%d:%d:%s',
710                                     $member->id,
711                                     $group->id,
712                                     common_date_iso8601(time()));
713
714             $act->actor = ActivityObject::fromProfile($member);
715             $act->verb = ActivityVerb::LEAVE;
716             $act->object = $oprofile->asActivityObject();
717
718             $act->time = time();
719             $act->title = _m("Leave");
720             $act->content = sprintf(_m("%s has left group %s."),
721                                     $member->getBestName(),
722                                     $oprofile->getBestName());
723
724             $oprofile->notifyActivity($act, $member);
725         }
726     }
727
728     /**
729      * Notify remote users when their notices get favorited.
730      *
731      * @param Profile or User $profile of local user doing the faving
732      * @param Notice $notice being favored
733      * @return hook return value
734      */
735
736     function onEndFavorNotice(Profile $profile, Notice $notice)
737     {
738         $user = User::staticGet('id', $profile->id);
739
740         if (empty($user)) {
741             return true;
742         }
743
744         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
745
746         if (empty($oprofile)) {
747             return true;
748         }
749
750         $act = new Activity();
751
752         $act->verb = ActivityVerb::FAVORITE;
753         $act->id   = TagURI::mint('favor:%d:%d:%s',
754                                   $profile->id,
755                                   $notice->id,
756                                   common_date_iso8601(time()));
757
758         $act->time    = time();
759         $act->title   = _("Favor");
760         $act->content = sprintf(_("%s marked notice %s as a favorite."),
761                                $profile->getBestName(),
762                                $notice->uri);
763
764         $act->actor   = ActivityObject::fromProfile($profile);
765         $act->object  = ActivityObject::fromNotice($notice);
766
767         $oprofile->notifyActivity($act, $profile);
768
769         return true;
770     }
771
772     /**
773      * Notify remote users when their notices get de-favorited.
774      *
775      * @param Profile $profile Profile person doing the de-faving
776      * @param Notice  $notice  Notice being favored
777      *
778      * @return hook return value
779      */
780
781     function onEndDisfavorNotice(Profile $profile, Notice $notice)
782     {
783         $user = User::staticGet('id', $profile->id);
784
785         if (empty($user)) {
786             return true;
787         }
788
789         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
790
791         if (empty($oprofile)) {
792             return true;
793         }
794
795         $act = new Activity();
796
797         $act->verb = ActivityVerb::UNFAVORITE;
798         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
799                                   $profile->id,
800                                   $notice->id,
801                                   common_date_iso8601(time()));
802         $act->time    = time();
803         $act->title   = _("Disfavor");
804         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
805                                $profile->getBestName(),
806                                $notice->uri);
807
808         $act->actor   = ActivityObject::fromProfile($profile);
809         $act->object  = ActivityObject::fromNotice($notice);
810
811         $oprofile->notifyActivity($act, $profile);
812
813         return true;
814     }
815
816     function onStartGetProfileUri($profile, &$uri)
817     {
818         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
819         if (!empty($oprofile)) {
820             $uri = $oprofile->uri;
821             return false;
822         }
823         return true;
824     }
825
826     function onStartUserGroupHomeUrl($group, &$url)
827     {
828         return $this->onStartUserGroupPermalink($group, $url);
829     }
830
831     function onStartUserGroupPermalink($group, &$url)
832     {
833         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
834         if ($oprofile) {
835             // @fixme this should probably be in the user_group table
836             // @fixme this uri not guaranteed to be a profile page
837             $url = $oprofile->uri;
838             return false;
839         }
840     }
841
842     function onStartShowSubscriptionsContent($action)
843     {
844         $this->showEntityRemoteSubscribe($action);
845
846         return true;
847     }
848
849     function onStartShowUserGroupsContent($action)
850     {
851         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
852
853         return true;
854     }
855
856     function onEndShowSubscriptionsMiniList($action)
857     {
858         $this->showEntityRemoteSubscribe($action);
859
860         return true;
861     }
862
863     function onEndShowGroupsMiniList($action)
864     {
865         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
866
867         return true;
868     }
869
870     function showEntityRemoteSubscribe($action, $target='ostatussub')
871     {
872         $user = common_current_user();
873         if ($user && ($user->id == $action->profile->id)) {
874             $action->elementStart('div', 'entity_actions');
875             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
876                                              'class' => 'entity_subscribe'));
877             $action->element('a', array('href' => common_local_url($target),
878                                         'class' => 'entity_remote_subscribe')
879                                 , _m('Remote'));
880             $action->elementEnd('p');
881             $action->elementEnd('div');
882         }
883     }
884
885     /**
886      * Ping remote profiles with updates to this profile.
887      * Salmon pings are queued for background processing.
888      */
889     function onEndBroadcastProfile(Profile $profile)
890     {
891         $user = User::staticGet('id', $profile->id);
892
893         // Find foreign accounts I'm subscribed to that support Salmon pings.
894         //
895         // @fixme we could run updates through the PuSH feed too,
896         // in which case we can skip Salmon pings to folks who
897         // are also subscribed to me.
898         $sql = "SELECT * FROM ostatus_profile " .
899                "WHERE profile_id IN " .
900                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
901                "OR group_id IN " .
902                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
903         $oprofile = new Ostatus_profile();
904         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
905
906         if ($oprofile->N == 0) {
907             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
908             return true;
909         }
910
911         $act = new Activity();
912
913         $act->verb = ActivityVerb::UPDATE_PROFILE;
914         $act->id   = TagURI::mint('update-profile:%d:%s',
915                                   $profile->id,
916                                   common_date_iso8601(time()));
917         $act->time    = time();
918         $act->title   = _m("Profile update");
919         $act->content = sprintf(_m("%s has updated their profile page."),
920                                $profile->getBestName());
921
922         $act->actor   = ActivityObject::fromProfile($profile);
923         $act->object  = $act->actor;
924
925         while ($oprofile->fetch()) {
926             $oprofile->notifyDeferred($act, $profile);
927         }
928
929         return true;
930     }
931
932     function onStartProfileListItemActionElements($item)
933     {
934         if (!common_logged_in()) {
935
936             $profileUser = User::staticGet('id', $item->profile->id);
937
938             if (!empty($profileUser)) {
939
940                 $output = $item->out;
941
942                 // Add an OStatus subscribe
943                 $output->elementStart('li', 'entity_subscribe');
944                 $url = common_local_url('ostatusinit',
945                                         array('nickname' => $profileUser->nickname));
946                 $output->element('a', array('href' => $url,
947                                             'class' => 'entity_remote_subscribe'),
948                                  _m('Subscribe'));
949                 $output->elementEnd('li');
950             }
951         }
952
953         return true;
954     }
955
956     function onPluginVersion(&$versions)
957     {
958         $versions[] = array('name' => 'OStatus',
959                             'version' => STATUSNET_VERSION,
960                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
961                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
962                             'rawdescription' =>
963                             _m('Follow people across social networks that implement '.
964                                '<a href="http://ostatus.org/">OStatus</a>.'));
965
966         return true;
967     }
968
969     /**
970      * Utility function to check if the given URL is a canonical group profile
971      * page, and if so return the ID number.
972      *
973      * @param string $url
974      * @return mixed int or false
975      */
976     public static function localGroupFromUrl($url)
977     {
978         $template = common_local_url('groupbyid', array('id' => '31337'));
979         $template = preg_quote($template, '/');
980         $template = str_replace('31337', '(\d+)', $template);
981         if (preg_match("/$template/", $url, $matches)) {
982             return intval($matches[1]);
983         }
984         return false;
985     }
986
987     public function onStartProfileGetAtomFeed($profile, &$feed)
988     {
989         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
990
991         if (empty($oprofile)) {
992             return true;
993         }
994
995         $feed = $oprofile->feeduri;
996         return false;
997     }
998 }