]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
7db385b1a9a94e8b439532955e4fcb4c9665a512
[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  * OStatusPlugin implementation for GNU Social
22  *
23  * Depends on: WebFinger plugin
24  *
25  * @package OStatusPlugin
26  * @maintainer Brion Vibber <brion@status.net>
27  */
28
29 if (!defined('GNUSOCIAL')) { exit(1); }
30
31 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phpseclib');
32
33 class OStatusPlugin extends Plugin
34 {
35     /**
36      * Hook for RouterInitialized event.
37      *
38      * @param URLMapper $m path-to-action mapper
39      * @return boolean hook return
40      */
41     public function onRouterInitialized(URLMapper $m)
42     {
43         // Discovery actions
44         $m->connect('main/ostatustag',
45                     array('action' => 'ostatustag'));
46         $m->connect('main/ostatustag?nickname=:nickname',
47                     array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
48         $m->connect('main/ostatus/nickname/:nickname',
49                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
50         $m->connect('main/ostatus/group/:group',
51                   array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
52         $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
53                   array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
54                                                           'peopletag' => '[A-Za-z0-9_-]+'));
55         $m->connect('main/ostatus',
56                     array('action' => 'ostatusinit'));
57
58         // Remote subscription actions
59         $m->connect('main/ostatussub',
60                     array('action' => 'ostatussub'));
61         $m->connect('main/ostatusgroup',
62                     array('action' => 'ostatusgroup'));
63         $m->connect('main/ostatuspeopletag',
64                     array('action' => 'ostatuspeopletag'));
65
66         // PuSH actions
67         $m->connect('main/push/hub', array('action' => 'pushhub'));
68
69         $m->connect('main/push/callback/:feed',
70                     array('action' => 'pushcallback'),
71                     array('feed' => '[0-9]+'));
72
73         // Salmon endpoint
74         $m->connect('main/salmon/user/:id',
75                     array('action' => 'usersalmon'),
76                     array('id' => '[0-9]+'));
77         $m->connect('main/salmon/group/:id',
78                     array('action' => 'groupsalmon'),
79                     array('id' => '[0-9]+'));
80         $m->connect('main/salmon/peopletag/:id',
81                     array('action' => 'peopletagsalmon'),
82                     array('id' => '[0-9]+'));
83         return true;
84     }
85
86     public function onAutoload($cls)
87     {
88         switch ($cls) {
89         case 'Crypt_AES':
90         case 'Crypt_RSA':
91             // Crypt_AES becomes Crypt/AES.php which is found in extlib/phpseclib/
92             // which has been added to our include_path before
93             require_once str_replace('_', '/', $cls) . '.php';
94             return false;
95         }
96
97         return parent::onAutoload($cls);
98     }
99
100     /**
101      * Set up queue handlers for outgoing hub pushes
102      * @param QueueManager $qm
103      * @return boolean hook return
104      */
105     function onEndInitializeQueueManager(QueueManager $qm)
106     {
107         // Prepare outgoing distributions after notice save.
108         $qm->connect('ostatus', 'OStatusQueueHandler');
109
110         // Outgoing from our internal PuSH hub
111         $qm->connect('hubconf', 'HubConfQueueHandler');
112         $qm->connect('hubprep', 'HubPrepQueueHandler');
113
114         $qm->connect('hubout', 'HubOutQueueHandler');
115
116         // Outgoing Salmon replies (when we don't need a return value)
117         $qm->connect('salmon', 'SalmonQueueHandler');
118
119         // Incoming from a foreign PuSH hub
120         $qm->connect('pushin', 'PushInQueueHandler');
121
122         // Re-subscribe feeds that need renewal
123         $qm->connect('pushrenew', 'PushRenewQueueHandler');
124         return true;
125     }
126
127     /**
128      * Put saved notices into the queue for pubsub distribution.
129      */
130     function onStartEnqueueNotice($notice, &$transports)
131     {
132         if ($notice->inScope(null)) {
133             // put our transport first, in case there's any conflict (like OMB)
134             array_unshift($transports, 'ostatus');
135             $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
136         } else {
137             // FIXME: we don't do privacy-controlled OStatus updates yet.
138             // once that happens, finer grain of control here.
139             $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
140         }
141         return true;
142     }
143
144     /**
145      * Set up a PuSH hub link to our internal link for canonical timeline
146      * Atom feeds for users and groups.
147      */
148     function onStartApiAtom($feed)
149     {
150         $id = null;
151
152         if ($feed instanceof AtomUserNoticeFeed) {
153             $salmonAction = 'usersalmon';
154             $user = $feed->getUser();
155             $id   = $user->id;
156             $profile = $user->getProfile();
157         } else if ($feed instanceof AtomGroupNoticeFeed) {
158             $salmonAction = 'groupsalmon';
159             $group = $feed->getGroup();
160             $id = $group->id;
161         } else if ($feed instanceof AtomListNoticeFeed) {
162             $salmonAction = 'peopletagsalmon';
163             $peopletag = $feed->getList();
164             $id = $peopletag->id;
165         } else {
166             return true;
167         }
168
169         if (!empty($id)) {
170             $hub = common_config('ostatus', 'hub');
171             if (empty($hub)) {
172                 // Updates will be handled through our internal PuSH hub.
173                 $hub = common_local_url('pushhub');
174             }
175             $feed->addLink($hub, array('rel' => 'hub'));
176
177             // Also, we'll add in the salmon link
178             $salmon = common_local_url($salmonAction, array('id' => $id));
179             $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
180
181             // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
182             $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
183             $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
184         }
185
186         return true;
187     }
188
189     /**
190      * Add in an OStatus subscribe button
191      */
192     function onStartProfileRemoteSubscribe($output, $profile)
193     {
194         $this->onStartProfileListItemActionElements($output, $profile);
195         return false;
196     }
197
198     function onStartGroupSubscribe($widget, $group)
199     {
200         $cur = common_current_user();
201
202         if (empty($cur)) {
203             $widget->out->elementStart('li', 'entity_subscribe');
204
205             $url = common_local_url('ostatusinit',
206                                     array('group' => $group->nickname));
207             $widget->out->element('a', array('href' => $url,
208                                              'class' => 'entity_remote_subscribe'),
209                                 // TRANS: Link to subscribe to a remote entity.
210                                 _m('Subscribe'));
211
212             $widget->out->elementEnd('li');
213             return false;
214         }
215
216         return true;
217     }
218
219     function onStartSubscribePeopletagForm($output, $peopletag)
220     {
221         $cur = common_current_user();
222
223         if (empty($cur)) {
224             $output->elementStart('li', 'entity_subscribe');
225             $profile = $peopletag->getTagger();
226             $url = common_local_url('ostatusinit',
227                                     array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
228             $output->element('a', array('href' => $url,
229                                         'class' => 'entity_remote_subscribe'),
230                                 // TRANS: Link to subscribe to a remote entity.
231                                 _m('Subscribe'));
232
233             $output->elementEnd('li');
234             return false;
235         }
236
237         return true;
238     }
239
240     /*
241      * If the field being looked for is URI look for the profile
242      */
243     function onStartProfileCompletionSearch($action, $profile, $search_engine) {
244         if ($action->field == 'uri') {
245             $profile->joinAdd(array('id', 'user:id'));
246             $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
247             $profile->query();
248
249             $validate = new Validate();
250
251             if ($profile->N == 0) {
252                 try {
253                     if ($validate->email($q)) {
254                         $oprofile = Ostatus_profile::ensureWebfinger($q);
255                     } else if ($validate->uri($q)) {
256                         $oprofile = Ostatus_profile::ensureProfileURL($q);
257                     } else {
258                         // TRANS: Exception in OStatus when invalid URI was entered.
259                         throw new Exception(_m('Invalid URI.'));
260                     }
261                     return $this->filter(array($oprofile->localProfile()));
262
263                 } catch (Exception $e) {
264                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
265                 // TRANS: and example.net, as these are official standard domain names for use in examples.
266                     $this->msg = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
267                     return array();
268                 }
269             }
270             return false;
271         }
272         return true;
273     }
274
275     /**
276      * Find any explicit remote mentions. Accepted forms:
277      *   Webfinger: @user@example.com
278      *   Profile link: @example.com/mublog/user
279      * @param Profile $sender
280      * @param string $text input markup text
281      * @param array &$mention in/out param: set of found mentions
282      * @return boolean hook return value
283      */
284     function onEndFindMentions(Profile $sender, $text, &$mentions)
285     {
286         $matches = array();
287
288         // Webfinger matches: @user@example.com
289         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
290                        $text,
291                        $wmatches,
292                        PREG_OFFSET_CAPTURE)) {
293             foreach ($wmatches[1] as $wmatch) {
294                 list($target, $pos) = $wmatch;
295                 $this->log(LOG_INFO, "Checking webfinger '$target'");
296                 try {
297                     $oprofile = Ostatus_profile::ensureWebfinger($target);
298                     if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
299                         $profile = $oprofile->localProfile();
300                         $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
301                                 $profile->nickname : $target;
302                         $matches[$pos] = array('mentioned' => array($profile),
303                                                'type' => 'mention',
304                                                'text' => $text,
305                                                'position' => $pos,
306                                                'length' => mb_strlen($target),
307                                                'url' => $profile->getUrl());
308                     }
309                 } catch (Exception $e) {
310                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
311                 }
312             }
313         }
314
315         // Profile matches: @example.com/mublog/user
316         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)*)!',
317                        $text,
318                        $wmatches,
319                        PREG_OFFSET_CAPTURE)) {
320             foreach ($wmatches[1] as $wmatch) {
321                 list($target, $pos) = $wmatch;
322                 $schemes = array('http', 'https');
323                 foreach ($schemes as $scheme) {
324                     $url = "$scheme://$target";
325                     $this->log(LOG_INFO, "Checking profile address '$url'");
326                     try {
327                         $oprofile = Ostatus_profile::ensureProfileURL($url);
328                         if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
329                             $profile = $oprofile->localProfile();
330                             $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
331                                     $profile->nickname : $target;
332                             $matches[$pos] = array('mentioned' => array($profile),
333                                                    'type' => 'mention',
334                                                    'text' => $text,
335                                                    'position' => $pos,
336                                                    'length' => mb_strlen($target),
337                                                    'url' => $profile->getUrl());
338                             break;
339                         }
340                     } catch (Exception $e) {
341                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
342                     }
343                 }
344             }
345         }
346
347         foreach ($mentions as $i => $other) {
348             // If we share a common prefix with a local user, override it!
349             $pos = $other['position'];
350             if (isset($matches[$pos])) {
351                 $mentions[$i] = $matches[$pos];
352                 unset($matches[$pos]);
353             }
354         }
355         foreach ($matches as $mention) {
356             $mentions[] = $mention;
357         }
358
359         return true;
360     }
361
362     /**
363      * Allow remote profile references to be used in commands:
364      *   sub update@status.net
365      *   whois evan@identi.ca
366      *   reply http://identi.ca/evan hey what's up
367      *
368      * @param Command $command
369      * @param string $arg
370      * @param Profile &$profile
371      * @return hook return code
372      */
373     function onStartCommandGetProfile($command, $arg, &$profile)
374     {
375         $oprofile = $this->pullRemoteProfile($arg);
376         if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
377             try {
378                 $profile = $oprofile->localProfile();
379             } catch (NoProfileException $e) {
380                 // No locally stored profile found for remote profile
381                 return true;
382             }
383             return false;
384         } else {
385             return true;
386         }
387     }
388
389     /**
390      * Allow remote group references to be used in commands:
391      *   join group+statusnet@identi.ca
392      *   join http://identi.ca/group/statusnet
393      *   drop identi.ca/group/statusnet
394      *
395      * @param Command $command
396      * @param string $arg
397      * @param User_group &$group
398      * @return hook return code
399      */
400     function onStartCommandGetGroup($command, $arg, &$group)
401     {
402         $oprofile = $this->pullRemoteProfile($arg);
403         if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
404             $group = $oprofile->localGroup();
405             return false;
406         } else {
407             return true;
408         }
409     }
410
411     protected function pullRemoteProfile($arg)
412     {
413         $oprofile = null;
414         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
415             // webfinger lookup
416             try {
417                 return Ostatus_profile::ensureWebfinger($arg);
418             } catch (Exception $e) {
419                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
420                                     $arg . ': ' . $e->getMessage());
421             }
422         }
423
424         // Look for profile URLs, with or without scheme:
425         $urls = array();
426         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
427             $urls[] = $arg;
428         }
429         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
430             $schemes = array('http', 'https');
431             foreach ($schemes as $scheme) {
432                 $urls[] = "$scheme://$arg";
433             }
434         }
435
436         foreach ($urls as $url) {
437             try {
438                 return Ostatus_profile::ensureProfileURL($url);
439             } catch (Exception $e) {
440                 common_log(LOG_ERR, 'Profile lookup failed for ' .
441                                     $arg . ': ' . $e->getMessage());
442             }
443         }
444         return null;
445     }
446
447     /**
448      * Make sure necessary tables are filled out.
449      */
450     function onCheckSchema() {
451         $schema = Schema::get();
452         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
453         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
454         $schema->ensureTable('feedsub', FeedSub::schemaDef());
455         $schema->ensureTable('hubsub', HubSub::schemaDef());
456         $schema->ensureTable('magicsig', Magicsig::schemaDef());
457         return true;
458     }
459
460     public function onEndShowStylesheets(Action $action) {
461         $action->cssLink($this->path('theme/base/css/ostatus.css'));
462         return true;
463     }
464
465     function onEndShowStatusNetScripts($action) {
466         $action->script($this->path('js/ostatus.js'));
467         return true;
468     }
469
470     /**
471      * Override the "from ostatus" bit in notice lists to link to the
472      * original post and show the domain it came from.
473      *
474      * @param Notice in $notice
475      * @param string out &$name
476      * @param string out &$url
477      * @param string out &$title
478      * @return mixed hook return code
479      */
480     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
481     {
482         // If we don't handle this, keep the event handler going
483         if (!in_array($notice->source, array('ostatus', 'share'))) {
484             return true;
485         }
486
487         try {
488             $url = $notice->getUrl();
489             // If getUrl() throws exception, $url is never set
490             
491             $bits = parse_url($url);
492             $domain = $bits['host'];
493             if (substr($domain, 0, 4) == 'www.') {
494                 $name = substr($domain, 4);
495             } else {
496                 $name = $domain;
497             }
498
499             // TRANS: Title. %s is a domain name.
500             $title = sprintf(_m('Sent from %s via OStatus'), $domain);
501
502             // Abort event handler, we have a name and URL!
503             return false;
504         } catch (InvalidUrlException $e) {
505             // This just means we don't have the notice source data
506             return true;
507         }
508     }
509
510     /**
511      * Send incoming PuSH feeds for OStatus endpoints in for processing.
512      *
513      * @param FeedSub $feedsub
514      * @param DOMDocument $feed
515      * @return mixed hook return code
516      */
517     function onStartFeedSubReceive($feedsub, $feed)
518     {
519         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
520         if ($oprofile instanceof Ostatus_profile) {
521             $oprofile->processFeed($feed, 'push');
522         } else {
523             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
524         }
525     }
526
527     /**
528      * Tell the FeedSub infrastructure whether we have any active OStatus
529      * usage for the feed; if not it'll be able to garbage-collect the
530      * feed subscription.
531      *
532      * @param FeedSub $feedsub
533      * @param integer $count in/out
534      * @return mixed hook return code
535      */
536     function onFeedSubSubscriberCount($feedsub, &$count)
537     {
538         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
539         if ($oprofile instanceof Ostatus_profile) {
540             $count += $oprofile->subscriberCount();
541         }
542         return true;
543     }
544
545     /**
546      * When about to subscribe to a remote user, start a server-to-server
547      * PuSH subscription if needed. If we can't establish that, abort.
548      *
549      * @fixme If something else aborts later, we could end up with a stray
550      *        PuSH subscription. This is relatively harmless, though.
551      *
552      * @param Profile $profile  subscriber
553      * @param Profile $other    subscribee
554      *
555      * @return hook return code
556      *
557      * @throws Exception
558      */
559     function onStartSubscribe(Profile $profile, Profile $other)
560     {
561         if (!$profile->isLocal()) {
562             return true;
563         }
564
565         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
566         if (!$oprofile instanceof Ostatus_profile) {
567             return true;
568         }
569
570         $oprofile->subscribe();
571     }
572
573     /**
574      * Having established a remote subscription, send a notification to the
575      * remote OStatus profile's endpoint.
576      *
577      * @param Profile $profile  subscriber
578      * @param Profile $other    subscribee
579      *
580      * @return hook return code
581      *
582      * @throws Exception
583      */
584     function onEndSubscribe(Profile $profile, Profile $other)
585     {
586         if (!$profile->isLocal()) {
587             return true;
588         }
589
590         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
591         if (!$oprofile instanceof Ostatus_profile) {
592             return true;
593         }
594
595         $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
596                                            'subscribed' => $other->id));
597
598         $act = $sub->asActivity();
599
600         $oprofile->notifyActivity($act, $profile);
601
602         return true;
603     }
604
605     /**
606      * Notify remote server and garbage collect unused feeds on unsubscribe.
607      * @todo FIXME: Send these operations to background queues
608      *
609      * @param User $user
610      * @param Profile $other
611      * @return hook return value
612      */
613     function onEndUnsubscribe(Profile $profile, Profile $other)
614     {
615         if (!$profile->isLocal()) {
616             return true;
617         }
618
619         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
620         if (!$oprofile instanceof Ostatus_profile) {
621             return true;
622         }
623
624         // Drop the PuSH subscription if there are no other subscribers.
625         $oprofile->garbageCollect();
626
627         $act = new Activity();
628
629         $act->verb = ActivityVerb::UNFOLLOW;
630
631         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
632                                   $profile->id,
633                                   $other->id,
634                                   common_date_iso8601(time()));
635
636         $act->time    = time();
637         // TRANS: Title for unfollowing a remote profile.
638         $act->title   = _m('TITLE','Unfollow');
639         // TRANS: Success message for unsubscribe from user attempt through OStatus.
640         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
641         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
642                                $profile->getBestName(),
643                                $other->getBestName());
644
645         $act->actor   = $profile->asActivityObject();
646         $act->object  = $other->asActivityObject();
647
648         $oprofile->notifyActivity($act, $profile);
649
650         return true;
651     }
652
653     /**
654      * When one of our local users tries to join a remote group,
655      * notify the remote server. If the notification is rejected,
656      * deny the join.
657      *
658      * @param User_group $group
659      * @param Profile    $profile
660      *
661      * @return mixed hook return value
662      * @throws Exception of various kinds, some from $oprofile->subscribe();
663      */
664     function onStartJoinGroup($group, $profile)
665     {
666         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
667         if (!$oprofile instanceof Ostatus_profile) {
668             return true;
669         }
670
671         $oprofile->subscribe();
672
673         // NOTE: we don't use Group_member::asActivity() since that record
674         // has not yet been created.
675
676         $act = new Activity();
677         $act->id = TagURI::mint('join:%d:%d:%s',
678                                 $profile->id,
679                                 $group->id,
680                                 common_date_iso8601(time()));
681
682         $act->actor = $profile->asActivityObject();
683         $act->verb = ActivityVerb::JOIN;
684         $act->object = $oprofile->asActivityObject();
685
686         $act->time = time();
687         // TRANS: Title for joining a remote groep.
688         $act->title = _m('TITLE','Join');
689         // TRANS: Success message for subscribe to group attempt through OStatus.
690         // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
691         $act->content = sprintf(_m('%1$s has joined group %2$s.'),
692                                 $profile->getBestName(),
693                                 $oprofile->getBestName());
694
695         if ($oprofile->notifyActivity($act, $profile)) {
696             return true;
697         } else {
698             $oprofile->garbageCollect();
699             // TRANS: Exception thrown when joining a remote group fails.
700             throw new Exception(_m('Failed joining remote group.'));
701         }
702     }
703
704     /**
705      * When one of our local users leaves a remote group, notify the remote
706      * server.
707      *
708      * @fixme Might be good to schedule a resend of the leave notification
709      * if it failed due to a transitory error. We've canceled the local
710      * membership already anyway, but if the remote server comes back up
711      * it'll be left with a stray membership record.
712      *
713      * @param User_group $group
714      * @param Profile $profile
715      *
716      * @return mixed hook return value
717      */
718     function onEndLeaveGroup($group, $profile)
719     {
720         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
721         if (!$oprofile instanceof Ostatus_profile) {
722             return true;
723         }
724
725         // Drop the PuSH subscription if there are no other subscribers.
726         $oprofile->garbageCollect();
727
728         $member = $profile;
729
730         $act = new Activity();
731         $act->id = TagURI::mint('leave:%d:%d:%s',
732                                 $member->id,
733                                 $group->id,
734                                 common_date_iso8601(time()));
735
736         $act->actor = $member->asActivityObject();
737         $act->verb = ActivityVerb::LEAVE;
738         $act->object = $oprofile->asActivityObject();
739
740         $act->time = time();
741         // TRANS: Title for leaving a remote group.
742         $act->title = _m('TITLE','Leave');
743         // TRANS: Success message for unsubscribe from group attempt through OStatus.
744         // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
745         $act->content = sprintf(_m('%1$s has left group %2$s.'),
746                                 $member->getBestName(),
747                                 $oprofile->getBestName());
748
749         $oprofile->notifyActivity($act, $member);
750     }
751
752     /**
753      * When one of our local users tries to subscribe to a remote peopletag,
754      * notify the remote server. If the notification is rejected,
755      * deny the subscription.
756      *
757      * @param Profile_list $peopletag
758      * @param User         $user
759      *
760      * @return mixed hook return value
761      * @throws Exception of various kinds, some from $oprofile->subscribe();
762      */
763
764     function onStartSubscribePeopletag($peopletag, $user)
765     {
766         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
767         if (!$oprofile instanceof Ostatus_profile) {
768             return true;
769         }
770
771         $oprofile->subscribe();
772
773         $sub = $user->getProfile();
774         $tagger = Profile::getKV($peopletag->tagger);
775
776         $act = new Activity();
777         $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
778                                 $sub->id,
779                                 $peopletag->id,
780                                 common_date_iso8601(time()));
781
782         $act->actor = $sub->asActivityObject();
783         $act->verb = ActivityVerb::FOLLOW;
784         $act->object = $oprofile->asActivityObject();
785
786         $act->time = time();
787         // TRANS: Title for following a remote list.
788         $act->title = _m('TITLE','Follow list');
789         // TRANS: Success message for remote list follow through OStatus.
790         // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
791         $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
792                                 $sub->getBestName(),
793                                 $oprofile->getBestName(),
794                                 $tagger->getBestName());
795
796         if ($oprofile->notifyActivity($act, $sub)) {
797             return true;
798         } else {
799             $oprofile->garbageCollect();
800             // TRANS: Exception thrown when subscription to remote list fails.
801             throw new Exception(_m('Failed subscribing to remote list.'));
802         }
803     }
804
805     /**
806      * When one of our local users unsubscribes to a remote peopletag, notify the remote
807      * server.
808      *
809      * @param Profile_list $peopletag
810      * @param User         $user
811      *
812      * @return mixed hook return value
813      */
814
815     function onEndUnsubscribePeopletag($peopletag, $user)
816     {
817         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
818         if (!$oprofile instanceof Ostatus_profile) {
819             return true;
820         }
821
822         // Drop the PuSH subscription if there are no other subscribers.
823         $oprofile->garbageCollect();
824
825         $sub = Profile::getKV($user->id);
826         $tagger = Profile::getKV($peopletag->tagger);
827
828         $act = new Activity();
829         $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
830                                 $sub->id,
831                                 $peopletag->id,
832                                 common_date_iso8601(time()));
833
834         $act->actor = $member->asActivityObject();
835         $act->verb = ActivityVerb::UNFOLLOW;
836         $act->object = $oprofile->asActivityObject();
837
838         $act->time = time();
839         // TRANS: Title for unfollowing a remote list.
840         $act->title = _m('Unfollow list');
841         // TRANS: Success message for remote list unfollow through OStatus.
842         // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
843         $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
844                                 $sub->getBestName(),
845                                 $oprofile->getBestName(),
846                                 $tagger->getBestName());
847
848         $oprofile->notifyActivity($act, $user);
849     }
850
851     /**
852      * Notify remote users when their notices get favorited.
853      *
854      * @param Profile or User $profile of local user doing the faving
855      * @param Notice $notice being favored
856      * @return hook return value
857      */
858     function onEndFavorNotice(Profile $profile, Notice $notice)
859     {
860         // Only distribute local users' favor actions, remote users
861         // will have already distributed theirs.
862         if (!$profile->isLocal()) {
863             return true;
864         }
865
866         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
867         if (!$oprofile instanceof Ostatus_profile) {
868             return true;
869         }
870
871         $fav = Fave::pkeyGet(array('user_id' => $profile->id,
872                                    'notice_id' => $notice->id));
873
874         if (!$fav instanceof Fave) {
875             // That's weird.
876             // TODO: Make pkeyGet throw exception, since this is a critical failure.
877             return true;
878         }
879
880         $act = $fav->asActivity();
881
882         $oprofile->notifyActivity($act, $profile);
883
884         return true;
885     }
886
887     /**
888      * Notify remote user it has got a new people tag
889      *   - tag verb is queued
890      *   - the subscription is done immediately if not present
891      *
892      * @param Profile_tag $ptag the people tag that was created
893      * @return hook return value
894      * @throws Exception of various kinds, some from $oprofile->subscribe();
895      */
896     function onEndTagProfile($ptag)
897     {
898         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
899         if (!$oprofile instanceof Ostatus_profile) {
900             return true;
901         }
902
903         $plist = $ptag->getMeta();
904         if ($plist->private) {
905             return true;
906         }
907
908         $act = new Activity();
909
910         $tagger = $plist->getTagger();
911         $tagged = Profile::getKV('id', $ptag->tagged);
912
913         $act->verb = ActivityVerb::TAG;
914         $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
915                                   $plist->tagger, $plist->id,
916                                   common_date_iso8601(time()));
917         $act->time = time();
918         // TRANS: Title for listing a remote profile.
919         $act->title = _m('TITLE','List');
920         // TRANS: Success message for remote list addition through OStatus.
921         // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
922         $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
923                                 $tagger->getBestName(),
924                                 $tagged->getBestName(),
925                                 $plist->getBestName());
926
927         $act->actor  = $tagger->asActivityObject();
928         $act->objects = array($tagged->asActivityObject());
929         $act->target = ActivityObject::fromPeopletag($plist);
930
931         $oprofile->notifyDeferred($act, $tagger);
932
933         // initiate a PuSH subscription for the person being tagged
934         $oprofile->subscribe();
935         return true;
936     }
937
938     /**
939      * Notify remote user that a people tag has been removed
940      *   - untag verb is queued
941      *   - the subscription is undone immediately if not required
942      *     i.e garbageCollect()'d
943      *
944      * @param Profile_tag $ptag the people tag that was deleted
945      * @return hook return value
946      */
947     function onEndUntagProfile($ptag)
948     {
949         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
950         if (!$oprofile instanceof Ostatus_profile) {
951             return true;
952         }
953
954         $plist = $ptag->getMeta();
955         if ($plist->private) {
956             return true;
957         }
958
959         $act = new Activity();
960
961         $tagger = $plist->getTagger();
962         $tagged = Profile::getKV('id', $ptag->tagged);
963
964         $act->verb = ActivityVerb::UNTAG;
965         $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
966                                   $plist->tagger, $plist->id,
967                                   common_date_iso8601(time()));
968         $act->time = time();
969         // TRANS: Title for unlisting a remote profile.
970         $act->title = _m('TITLE','Unlist');
971         // TRANS: Success message for remote list removal through OStatus.
972         // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
973         $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
974                                 $tagger->getBestName(),
975                                 $tagged->getBestName(),
976                                 $plist->getBestName());
977
978         $act->actor  = $tagger->asActivityObject();
979         $act->objects = array($tagged->asActivityObject());
980         $act->target = ActivityObject::fromPeopletag($plist);
981
982         $oprofile->notifyDeferred($act, $tagger);
983
984         // unsubscribe to PuSH feed if no more required
985         $oprofile->garbageCollect();
986
987         return true;
988     }
989
990     /**
991      * Notify remote users when their notices get de-favorited.
992      *
993      * @param Profile $profile Profile person doing the de-faving
994      * @param Notice  $notice  Notice being favored
995      *
996      * @return hook return value
997      */
998     function onEndDisfavorNotice(Profile $profile, Notice $notice)
999     {
1000         // Only distribute local users' disfavor actions, remote users
1001         // will have already distributed theirs.
1002         if (!$profile->isLocal()) {
1003             return true;
1004         }
1005
1006         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1007         if (!$oprofile instanceof Ostatus_profile) {
1008             return true;
1009         }
1010
1011         $act = new Activity();
1012
1013         $act->verb = ActivityVerb::UNFAVORITE;
1014         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
1015                                   $profile->id,
1016                                   $notice->id,
1017                                   common_date_iso8601(time()));
1018         $act->time    = time();
1019         // TRANS: Title for unliking a remote notice.
1020         $act->title   = _m('Unlike');
1021         // TRANS: Success message for remove a favorite notice through OStatus.
1022         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1023         $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1024                                $profile->getBestName(),
1025                                $notice->getUrl());
1026
1027         $act->actor   = $profile->asActivityObject();
1028         $act->object  = $notice->asActivityObject();
1029
1030         $oprofile->notifyActivity($act, $profile);
1031
1032         return true;
1033     }
1034
1035     function onStartGetProfileUri($profile, &$uri)
1036     {
1037         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1038         if ($oprofile instanceof Ostatus_profile) {
1039             $uri = $oprofile->uri;
1040             return false;
1041         }
1042         return true;
1043     }
1044
1045     function onStartUserGroupHomeUrl($group, &$url)
1046     {
1047         return $this->onStartUserGroupPermalink($group, $url);
1048     }
1049
1050     function onStartUserGroupPermalink($group, &$url)
1051     {
1052         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1053         if ($oprofile instanceof Ostatus_profile) {
1054             // @fixme this should probably be in the user_group table
1055             // @fixme this uri not guaranteed to be a profile page
1056             $url = $oprofile->uri;
1057             return false;
1058         }
1059     }
1060
1061     function onStartShowSubscriptionsContent($action)
1062     {
1063         $this->showEntityRemoteSubscribe($action);
1064
1065         return true;
1066     }
1067
1068     function onStartShowUserGroupsContent($action)
1069     {
1070         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1071
1072         return true;
1073     }
1074
1075     function onEndShowSubscriptionsMiniList($action)
1076     {
1077         $this->showEntityRemoteSubscribe($action);
1078
1079         return true;
1080     }
1081
1082     function onEndShowGroupsMiniList($action)
1083     {
1084         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1085
1086         return true;
1087     }
1088
1089     function showEntityRemoteSubscribe($action, $target='ostatussub')
1090     {
1091         if (!$action->getScoped() instanceof Profile) {
1092             // early return if we're not logged in
1093             return true;
1094         }
1095
1096         if ($action->getScoped()->sameAs($action->getTarget())) {
1097             $action->elementStart('div', 'entity_actions');
1098             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1099                                              'class' => 'entity_subscribe'));
1100             $action->element('a', array('href' => common_local_url($target),
1101                                         'class' => 'entity_remote_subscribe'),
1102                                 // TRANS: Link text for link to remote subscribe.
1103                                 _m('Remote'));
1104             $action->elementEnd('p');
1105             $action->elementEnd('div');
1106         }
1107     }
1108
1109     /**
1110      * Ping remote profiles with updates to this profile.
1111      * Salmon pings are queued for background processing.
1112      */
1113     function onEndBroadcastProfile(Profile $profile)
1114     {
1115         $user = User::getKV('id', $profile->id);
1116
1117         // Find foreign accounts I'm subscribed to that support Salmon pings.
1118         //
1119         // @fixme we could run updates through the PuSH feed too,
1120         // in which case we can skip Salmon pings to folks who
1121         // are also subscribed to me.
1122         $sql = "SELECT * FROM ostatus_profile " .
1123                "WHERE profile_id IN " .
1124                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1125                "OR group_id IN " .
1126                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1127         $oprofile = new Ostatus_profile();
1128         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1129
1130         if ($oprofile->N == 0) {
1131             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1132             return true;
1133         }
1134
1135         $act = new Activity();
1136
1137         $act->verb = ActivityVerb::UPDATE_PROFILE;
1138         $act->id   = TagURI::mint('update-profile:%d:%s',
1139                                   $profile->id,
1140                                   common_date_iso8601(time()));
1141         $act->time    = time();
1142         // TRANS: Title for activity.
1143         $act->title   = _m('Profile update');
1144         // TRANS: Ping text for remote profile update through OStatus.
1145         // TRANS: %s is user that updated their profile.
1146         $act->content = sprintf(_m('%s has updated their profile page.'),
1147                                $profile->getBestName());
1148
1149         $act->actor   = $profile->asActivityObject();
1150         $act->object  = $act->actor;
1151
1152         while ($oprofile->fetch()) {
1153             $oprofile->notifyDeferred($act, $profile);
1154         }
1155
1156         return true;
1157     }
1158
1159     // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1160     function onStartProfileListItemActionElements($item)
1161     {
1162         if (common_logged_in()) {
1163             // only non-logged in users get to see the "remote subscribe" form
1164             return true;
1165         } elseif (!$item->getTarget()->isLocal()) {
1166             // we can (for now) only provide remote subscribe forms for local users
1167             return true;
1168         }
1169
1170         if ($item instanceof ProfileAction) {
1171             $output = $item;
1172         } elseif ($item instanceof Widget) {
1173             $output = $item->out;
1174         } else {
1175             // Bad $item class, don't know how to use this for outputting!
1176             throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1177         }
1178
1179         // Add an OStatus subscribe
1180         $output->elementStart('li', 'entity_subscribe');
1181         $url = common_local_url('ostatusinit',
1182                                 array('nickname' => $item->getTarget()->getNickname()));
1183         $output->element('a', array('href' => $url,
1184                                     'class' => 'entity_remote_subscribe'),
1185                           // TRANS: Link text for a user to subscribe to an OStatus user.
1186                          _m('Subscribe'));
1187         $output->elementEnd('li');
1188
1189         $output->elementStart('li', 'entity_tag');
1190         $url = common_local_url('ostatustag',
1191                                 array('nickname' => $item->getTarget()->getNickname()));
1192         $output->element('a', array('href' => $url,
1193                                     'class' => 'entity_remote_tag'),
1194                           // TRANS: Link text for a user to list an OStatus user.
1195                          _m('List'));
1196         $output->elementEnd('li');
1197
1198         return true;
1199     }
1200
1201     function onPluginVersion(array &$versions)
1202     {
1203         $versions[] = array('name' => 'OStatus',
1204                             'version' => GNUSOCIAL_VERSION,
1205                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1206                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1207                             // TRANS: Plugin description.
1208                             'rawdescription' => _m('Follow people across social networks that implement '.
1209                                '<a href="http://ostatus.org/">OStatus</a>.'));
1210
1211         return true;
1212     }
1213
1214     /**
1215      * Utility function to check if the given URI is a canonical group profile
1216      * page, and if so return the ID number.
1217      *
1218      * @param string $url
1219      * @return mixed int or false
1220      */
1221     public static function localGroupFromUrl($url)
1222     {
1223         $group = User_group::getKV('uri', $url);
1224         if ($group instanceof User_group) {
1225             if ($group->isLocal()) {
1226                 return $group->id;
1227             }
1228         } else {
1229             // To find local groups which haven't had their uri fields filled out...
1230             // If the domain has changed since a subscriber got the URI, it'll
1231             // be broken.
1232             $template = common_local_url('groupbyid', array('id' => '31337'));
1233             $template = preg_quote($template, '/');
1234             $template = str_replace('31337', '(\d+)', $template);
1235             if (preg_match("/$template/", $url, $matches)) {
1236                 return intval($matches[1]);
1237             }
1238         }
1239         return false;
1240     }
1241
1242     public function onStartProfileGetAtomFeed($profile, &$feed)
1243     {
1244         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1245
1246         if (!$oprofile instanceof Ostatus_profile) {
1247             return true;
1248         }
1249
1250         $feed = $oprofile->feeduri;
1251         return false;
1252     }
1253
1254     function onStartGetProfileFromURI($uri, &$profile)
1255     {
1256         // Don't want to do Web-based discovery on our own server,
1257         // so we check locally first.
1258
1259         $user = User::getKV('uri', $uri);
1260
1261         if (!empty($user)) {
1262             $profile = $user->getProfile();
1263             return false;
1264         }
1265
1266         // Now, check remotely
1267
1268         try {
1269             $oprofile = Ostatus_profile::ensureProfileURI($uri);
1270             $profile = $oprofile->localProfile();
1271             return !($profile instanceof Profile);  // localProfile won't throw exception but can return null
1272         } catch (Exception $e) {
1273             return true; // It's not an OStatus profile as far as we know, continue event handling
1274         }
1275     }
1276
1277     function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1278     {
1279         $author = $target->getProfile();
1280         $profiletype = $this->profileTypeString($author);
1281         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1282         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1283         return true;
1284     }
1285
1286     function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1287     {
1288         if ($target->getObjectType() === ActivityObject::PERSON) {
1289             $this->addWebFingerPersonLinks($xrd, $target);
1290         }
1291
1292         // Salmon
1293         $profiletype = $this->profileTypeString($target);
1294         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1295
1296         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1297
1298         // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1299         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1300         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1301
1302         // TODO - finalize where the redirect should go on the publisher
1303         $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1304                               common_local_url('ostatussub') . '?profile={uri}',
1305                               null, // type not set
1306                               true); // isTemplate
1307
1308         return true;
1309     }
1310
1311     protected function profileTypeString(Profile $target)
1312     {
1313         // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1314         switch ($target->getObjectType()) {
1315         case ActivityObject::PERSON:
1316             return 'user';
1317         case ActivityObject::GROUP:
1318             return 'group';
1319         default:
1320             throw new ServerException('Unknown profile type for WebFinger profile links');
1321         }
1322     }
1323
1324     protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1325     {
1326         $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1327                             common_local_url('ApiTimelineUser',
1328                                 array('id' => $target->id, 'format' => 'atom')),
1329                             'application/atom+xml');
1330
1331         // Get this profile's keypair
1332         $magicsig = Magicsig::getKV('user_id', $target->id);
1333         if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1334             $magicsig = Magicsig::generate($target->getUser());
1335         }
1336
1337         if (!$magicsig instanceof Magicsig) {
1338             return false;   // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1339         }
1340         if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1341             $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1342                                 'data:application/magic-public-key,'. $magicsig->toString());
1343             // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1344             Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1345         }
1346     }
1347
1348     public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1349     {
1350         list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
1351     }
1352
1353     // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1354     static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1355     {
1356         try {
1357             $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1358             $profile = $oprofile->checkAuthorship($activity);
1359         } catch (Exception $e) {
1360             common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1361             $profile = null;
1362             return false;
1363         }
1364         return true;
1365     }
1366
1367     public function onProfileDeleteRelated($profile, &$related)
1368     {
1369         // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1370         $related[] = 'Ostatus_profile';
1371
1372         // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1373         $magicsig = Magicsig::getKV('user_id', $profile->id);
1374         if ($magicsig instanceof Magicsig) {
1375             $magicsig->delete();
1376         }
1377         return true;
1378     }
1379
1380     public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
1381     {
1382         $envxml = $magic_env->toXML($target);
1383
1384         $headers = array('Content-Type: application/magic-envelope+xml');
1385
1386         try {
1387             $client = new HTTPClient();
1388             $client->setBody($envxml);
1389             $response = $client->post($endpoint_uri, $headers);
1390         } catch (HTTP_Request2_Exception $e) {
1391             common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
1392             return false;
1393         }
1394         if ($response->getStatus() === 422) {
1395             common_debug(sprintf('Salmon (from profile %d) endpoint %s returned status %s. We assume it is a Diaspora seed; will adapt and try again if that plugin is enabled!', $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus()));
1396             return true;
1397         }
1398
1399         // 200 OK is the best response
1400         // 202 Accepted is what we get from Diaspora for example
1401         if (!in_array($response->getStatus(), array(200, 202))) {
1402             common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
1403                                 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
1404             return true;
1405         }
1406
1407         // Since we completed the salmon slap, we discontinue the event
1408         return false;
1409     }
1410
1411     public function onCronDaily()
1412     {
1413         try {
1414             $sub = FeedSub::renewalCheck();
1415         } catch (NoResultException $e) {
1416             common_log(LOG_INFO, "There were no expiring feeds.");
1417             return;
1418         }
1419
1420         $qm = QueueManager::get();
1421         while ($sub->fetch()) {
1422             $item = array('feedsub_id' => $sub->id);
1423             $qm->enqueue($item, 'pushrenew');
1424         }
1425     }
1426 }