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