]> git.mxchange.org Git - friendica.git/blob - mod/pubsubhubbub.php
Merge remote-tracking branch 'upstream/2021.12-rc' into user-banner
[friendica.git] / mod / pubsubhubbub.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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 use Friendica\App;
23 use Friendica\Core\Logger;
24 use Friendica\Database\DBA;
25 use Friendica\DI;
26 use Friendica\Model\PushSubscriber;
27 use Friendica\Util\Strings;
28
29 function pubsubhubbub_init(App $a) {
30         // PuSH subscription must be considered "public" so just block it
31         // if public access isn't enabled.
32         if (DI::config()->get('system', 'block_public')) {
33                 throw new \Friendica\Network\HTTPException\ForbiddenException();
34         }
35
36         // Subscription request from subscriber
37         // https://pubsubhubbub.googlecode.com/git/pubsubhubbub-core-0.4.html#anchor4
38         // Example from GNU Social:
39         // [hub_mode] => subscribe
40         // [hub_callback] => http://status.local/main/push/callback/1
41         // [hub_verify] => sync
42         // [hub_verify_token] => af11...
43         // [hub_secret] => af11...
44         // [hub_topic] => http://friendica.local/dfrn_poll/sazius
45
46         if (DI::args()->getMethod() === App\Router::POST) {
47                 $hub_mode         = $_POST['hub_mode']         ?? '';
48                 $hub_callback     = $_POST['hub_callback']     ?? '';
49                 $hub_verify_token = $_POST['hub_verify_token'] ?? '';
50                 $hub_secret       = $_POST['hub_secret']       ?? '';
51                 $hub_topic        = $_POST['hub_topic']        ?? '';
52
53                 // check for valid hub_mode
54                 if ($hub_mode === 'subscribe') {
55                         $subscribe = 1;
56                 } elseif ($hub_mode === 'unsubscribe') {
57                         $subscribe = 0;
58                 } else {
59                         Logger::notice("Invalid hub_mode=$hub_mode, ignoring.");
60                         throw new \Friendica\Network\HTTPException\NotFoundException();
61                 }
62
63                 Logger::info("$hub_mode request from " . $_SERVER['REMOTE_ADDR']);
64
65                 if (DI::args()->getArgc() > 1) {
66                         // Normally the url should now contain the nick name as last part of the url
67                         $nick = DI::args()->getArgv()[1];
68                 } else {
69                         // Get the nick name from the topic as a fallback
70                         $nick = $hub_topic;
71                 }
72                 // Extract nick name and strip any .atom extension
73                 $nick = basename($nick, '.atom');
74
75                 if (!$nick) {
76                         Logger::notice('Bad hub_topic=$hub_topic, ignoring.');
77                         throw new \Friendica\Network\HTTPException\NotFoundException();
78                 }
79
80                 // fetch user from database given the nickname
81                 $condition = ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false];
82                 $owner = DBA::selectFirst('user', ['uid', 'nickname'], $condition);
83                 if (!DBA::isResult($owner)) {
84                         Logger::notice('Local account not found: ' . $nick . ' - topic: ' . $hub_topic . ' - callback: ' . $hub_callback);
85                         throw new \Friendica\Network\HTTPException\NotFoundException();
86                 }
87
88                 // get corresponding row from contact table
89                 $condition = ['uid' => $owner['uid'], 'blocked' => false,
90                         'pending' => false, 'self' => true];
91                 $contact = DBA::selectFirst('contact', ['poll'], $condition);
92                 if (!DBA::isResult($contact)) {
93                         Logger::notice('Self contact for user ' . $owner['uid'] . ' not found.');
94                         throw new \Friendica\Network\HTTPException\NotFoundException();
95                 }
96
97                 // sanity check that topic URLs are the same
98                 $hub_topic2 = str_replace('/feed/', '/dfrn_poll/', $hub_topic);
99                 $self = DI::baseUrl() . '/api/statuses/user_timeline/' . $owner['nickname'] . '.atom';
100
101                 if (!Strings::compareLink($hub_topic, $contact['poll']) && !Strings::compareLink($hub_topic2, $contact['poll']) && !Strings::compareLink($hub_topic, $self)) {
102                         Logger::notice('Hub topic ' . $hub_topic . ' != ' . $contact['poll']);
103                         throw new \Friendica\Network\HTTPException\NotFoundException();
104                 }
105
106                 // do subscriber verification according to the PuSH protocol
107                 $hub_challenge = Strings::getRandomHex(40);
108
109                 $params = http_build_query([
110                         'hub.mode' => $subscribe == 1 ? 'subscribe' : 'unsubscribe',
111                         'hub.topic' => $hub_topic,
112                         'hub.challenge' => $hub_challenge,
113                         'hub.verify_token' => $hub_verify_token,
114
115                         // lease time is hard coded to one week (in seconds)
116                         // we don't actually enforce the lease time because GNU
117                         // Social/StatusNet doesn't honour it (yet)
118                         'hub.lease_seconds' => 604800,
119                 ]);
120
121                 $hub_callback = rtrim($hub_callback, ' ?&#');
122                 $separator = parse_url($hub_callback, PHP_URL_QUERY) === null ? '?' : '&';
123
124                 $fetchResult = DI::httpClient()->fetchFull($hub_callback . $separator . $params);
125                 $body = $fetchResult->getBody();
126                 $ret = $fetchResult->getReturnCode();
127
128                 // give up if the HTTP return code wasn't a success (2xx)
129                 if ($ret < 200 || $ret > 299) {
130                         Logger::notice("Subscriber verification for $hub_topic at $hub_callback returned $ret, ignoring.");
131                         throw new \Friendica\Network\HTTPException\NotFoundException();
132                 }
133
134                 // check that the correct hub_challenge code was echoed back
135                 if (trim($body) !== $hub_challenge) {
136                         Logger::notice("Subscriber did not echo back hub.challenge, ignoring.");
137                         Logger::notice("\"$hub_challenge\" != \"".trim($body)."\"");
138                         throw new \Friendica\Network\HTTPException\NotFoundException();
139                 }
140
141                 PushSubscriber::renew($owner['uid'], $nick, $subscribe, $hub_callback, $hub_topic, $hub_secret);
142
143                 throw new \Friendica\Network\HTTPException\AcceptedException();
144         }
145         exit();
146 }