]> git.mxchange.org Git - friendica.git/blob - src/Module/OStatus/PubSubHubBub.php
Use the post language for the language detection / config for quality
[friendica.git] / src / Module / OStatus / PubSubHubBub.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\OStatus;
23
24 use Friendica\App;
25 use Friendica\Core\Config\Capability\IManageConfigValues;
26 use Friendica\Core\L10n;
27 use Friendica\Database\Database;
28 use Friendica\Model\PushSubscriber;
29 use Friendica\Module\Response;
30 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
31 use Friendica\Network\HTTPException;
32 use Friendica\Util\Profiler;
33 use Friendica\Util\Strings;
34 use Psr\Log\LoggerInterface;
35
36 /**
37  * An open, simple, web-scale and decentralized pubsub protocol.
38  *
39  * Part of the OStatus stack.
40  *
41  * See https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html
42  *
43  * @version 0.4
44  */
45 class PubSubHubBub extends \Friendica\BaseModule
46 {
47         /** @var IManageConfigValues */
48         private $config;
49         /** @var Database */
50         private $database;
51         /** @var ICanSendHttpRequests */
52         private $httpClient;
53         /** @var App\Request */
54         private $request;
55
56         public function __construct(App\Request $request, ICanSendHttpRequests $httpClient, Database $database, IManageConfigValues $config, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
57         {
58                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
59
60                 $this->config     = $config;
61                 $this->database   = $database;
62                 $this->httpClient = $httpClient;
63                 $this->request    = $request;
64         }
65
66         protected function post(array $request = [])
67         {
68                 // PuSH subscription must be considered "public" so just block it
69                 // if public access isn't enabled.
70                 if ($this->config->get('system', 'block_public')) {
71                         throw new HTTPException\ForbiddenException();
72                 }
73
74                 $this->logger->debug('Got request data.', ['request' => $request]);
75
76                 // Subscription request from subscriber
77                 // https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html#rfc.section.5.1
78                 // Example from GNU Social:
79                 // [hub_mode] => subscribe
80                 // [hub_callback] => http://status.local/main/push/callback/1
81                 // [hub_verify] => sync
82                 // [hub_verify_token] => af11...
83                 // [hub_secret] => af11...
84                 // [hub_topic] => http://friendica.local/dfrn_poll/sazius
85
86                 $hub_mode         = $request['hub_mode']         ?? '';
87                 $hub_callback     = $request['hub_callback']     ?? '';
88                 $hub_verify_token = $request['hub_verify_token'] ?? '';
89                 $hub_secret       = $request['hub_secret']       ?? '';
90                 $hub_topic        = $request['hub_topic']        ?? '';
91
92                 // check for valid hub_mode
93                 if ($hub_mode === 'subscribe') {
94                         $subscribe = 1;
95                 } elseif ($hub_mode === 'unsubscribe') {
96                         $subscribe = 0;
97                 } else {
98                         $this->logger->notice('Invalid hub_mod - ignored.', ['mode' => $hub_mode]);
99                         throw new HTTPException\NotFoundException();
100                 }
101
102                 $this->logger->info('hub_mode request details.', ['from' => $this->request->getRemoteAddress(), 'mode' => $hub_mode]);
103
104                 $nickname = $this->parameters['nickname'] ?? $hub_topic;
105
106                 // Extract nickname and strip any .atom extension
107                 $nickname = basename($nickname, '.atom');
108                 if (!$nickname) {
109                         $this->logger->notice('Empty nick, ignoring.');
110                         throw new HTTPException\NotFoundException();
111                 }
112
113                 // fetch user from database given the nickname
114                 $condition = ['nickname' => $nickname, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
115                 $owner     = $this->database->selectFirst('user', ['uid', 'nickname'], $condition);
116                 if (!$owner) {
117                         $this->logger->notice('Local account not found', ['nickname' => $nickname, 'topic' => $hub_topic, 'callback' => $hub_callback]);
118                         throw new HTTPException\NotFoundException();
119                 }
120
121                 // get corresponding row from contact table
122                 $condition = ['uid' => $owner['uid'], 'blocked' => false, 'pending' => false, 'self' => true];
123                 $contact   = $this->database->selectFirst('contact', ['poll'], $condition);
124                 if (!$contact) {
125                         $this->logger->notice('Self contact for user not found.', ['uid' => $owner['uid']]);
126                         throw new HTTPException\NotFoundException();
127                 }
128
129                 // sanity check that topic URLs are the same
130                 $hub_topic2 = str_replace('/feed/', '/dfrn_poll/', $hub_topic);
131                 $self       = $this->baseUrl . '/api/statuses/user_timeline/' . $owner['nickname'] . '.atom';
132
133                 if (!Strings::compareLink($hub_topic, $contact['poll']) && !Strings::compareLink($hub_topic2, $contact['poll']) && !Strings::compareLink($hub_topic, $self)) {
134                         $this->logger->notice('Hub topic invalid', ['hub_topic' => $hub_topic, 'poll' => $contact['poll']]);
135                         throw new HTTPException\NotFoundException();
136                 }
137
138                 // do subscriber verification according to the PuSH protocol
139                 $hub_challenge = Strings::getRandomHex(40);
140
141                 $params = http_build_query([
142                         'hub.mode'         => $subscribe == 1 ? 'subscribe' : 'unsubscribe',
143                         'hub.topic'        => $hub_topic,
144                         'hub.challenge'    => $hub_challenge,
145                         'hub.verify_token' => $hub_verify_token,
146
147                         // lease time is hard coded to one week (in seconds)
148                         // we don't actually enforce the lease time because GNU
149                         // Social/StatusNet doesn't honour it (yet)
150                         'hub.lease_seconds' => 604800,
151                 ]);
152
153                 $hub_callback = rtrim($hub_callback, ' ?&#');
154                 $separator    = parse_url($hub_callback, PHP_URL_QUERY) === null ? '?' : '&';
155
156                 $fetchResult = $this->httpClient->fetchFull($hub_callback . $separator . $params);
157                 $body        = $fetchResult->getBody();
158                 $returnCode  = $fetchResult->getReturnCode();
159
160                 // give up if the HTTP return code wasn't a success (2xx)
161                 if ($returnCode < 200 || $returnCode > 299) {
162                         $this->logger->notice('Subscriber verification ignored', ['hub_topic' => $hub_topic, 'callback' => $hub_callback, 'returnCode' => $returnCode]);
163                         throw new HTTPException\NotFoundException();
164                 }
165
166                 // check that the correct hub_challenge code was echoed back
167                 if (trim($body) !== $hub_challenge) {
168                         $this->logger->notice('Subscriber did not echo back hub.challenge, ignoring.', ['hub_challenge' => $hub_challenge, 'body' => trim($body)]);
169                         throw new HTTPException\NotFoundException();
170                 }
171
172                 PushSubscriber::renew($owner['uid'], $nickname, $subscribe, $hub_callback, $hub_topic, $hub_secret);
173
174                 throw new HTTPException\AcceptedException();
175         }
176 }