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