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