]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Delivery.php
Merge branch 'post-reason' of github.com:annando/friendica into post-reason
[friendica.git] / src / Protocol / ActivityPub / Delivery.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 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Core\Logger;
25 use Friendica\Database\DBA;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Model\GServer;
29 use Friendica\Model\Post;
30 use Friendica\Protocol\ActivityPub;
31 use Friendica\Util\HTTPSignature;
32 use Friendica\Worker\Delivery as WorkerDelivery;
33
34 class Delivery
35 {
36         /**
37          * Deliver posts to the given inbox
38          *
39          * @param string $inbox
40          * @return array with the elements "success" and "uri_ids" of the failed posts
41          */
42         public static function deliver(string $inbox): array
43         {
44                 $uri_ids    = [];
45                 $posts      = Post\Delivery::selectForInbox($inbox);
46                 $serverfail = false;
47
48                 foreach ($posts as $post) {
49                         if (!$serverfail) {
50                                 $result = self::deliverToInbox($post['command'], 0, $inbox, $post['uid'], $post['receivers'], $post['uri-id']);
51
52                                 if ($result['serverfailure']) {
53                                         // In a timeout situation we assume that every delivery to that inbox will time out.
54                                         // So we set the flag and try all deliveries at a later time.
55                                         Logger::info('Inbox delivery has a server failure', ['inbox' => $inbox]);
56                                         $serverfail = true;
57                                 }
58                         }
59
60                         if ($serverfail || (!$result['success'] && !$result['drop'])) {
61                                 $uri_ids[] = $post['uri-id'];
62                         }
63                 }
64
65                 Logger::debug('Inbox delivery done', ['inbox' => $inbox, 'posts' => count($posts), 'failed' => count($uri_ids), 'serverfailure' => $serverfail]);
66                 return ['success' => empty($uri_ids), 'uri_ids' => $uri_ids];
67         }
68
69         /**
70          * Deliver the given post to the given inbox
71          *
72          * @param string $cmd
73          * @param integer $item_id
74          * @param string $inbox
75          * @param integer $uid
76          * @param array $receivers
77          * @param integer $uri_id
78          * @return array
79          */
80         public static function deliverToInbox(string $cmd, int $item_id, string $inbox, int $uid, array $receivers, int $uri_id): array
81         {
82                 if (empty($item_id) && !empty($uri_id) && !empty($uid)) {
83                         $item = Post::selectFirst(['id', 'parent', 'origin'], ['uri-id' => $uri_id, 'uid' => [$uid, 0]], ['order' => ['uid' => true]]);
84                         if (empty($item['id'])) {
85                                 Logger::notice('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]);
86                                 Post\Delivery::remove($uri_id, $inbox);
87                                 return true;
88                         } else {
89                                 $item_id = $item['id'];
90                         }
91                 }
92
93                 $success    = true;
94                 $serverfail = false;
95                 $drop       = false;
96
97                 if ($cmd == WorkerDelivery::MAIL) {
98                         $data = ActivityPub\Transmitter::createActivityFromMail($item_id);
99                         if (!empty($data)) {
100                                 $success = HTTPSignature::transmit($data, $inbox, $uid);
101                         }
102                 } elseif ($cmd == WorkerDelivery::SUGGESTION) {
103                         $success = ActivityPub\Transmitter::sendContactSuggestion($uid, $inbox, $item_id);
104                 } elseif ($cmd == WorkerDelivery::RELOCATION) {
105                         // @todo Implementation pending
106                 } elseif ($cmd == WorkerDelivery::POKE) {
107                         // Implementation not planned
108                 } elseif ($cmd == WorkerDelivery::REMOVAL) {
109                         $success = ActivityPub\Transmitter::sendProfileDeletion($uid, $inbox);
110                 } elseif ($cmd == WorkerDelivery::PROFILEUPDATE) {
111                         $success = ActivityPub\Transmitter::sendProfileUpdate($uid, $inbox);
112                 } else {
113                         $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
114                         if (!empty($data)) {
115                                 $timestamp  = microtime(true);
116                                 $response   = HTTPSignature::post($data, $inbox, $uid);
117                                 $runtime    = microtime(true) - $timestamp;
118                                 $success    = $response->isSuccess();
119                                 $serverfail = $response->isTimeout();
120                                 if (!$success) {
121                                         // 5xx errors are problems on the server. We don't need to continue delivery then.
122                                         if (!$serverfail && ($response->getReturnCode() >= 500) && ($response->getReturnCode() <= 599)) {
123                                                 $serverfail = true;
124                                         }
125
126                                         // A 404 means that the inbox doesn't exist. We can stop the delivery here.
127                                         if (!$serverfail && ($response->getReturnCode() == 404)) {
128                                                 $serverfail = true;
129                                         }
130
131                                         $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
132                                         if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
133                                                 $serverfail = true;
134                                         }
135
136                                         $curl_timeout = DI::config()->get('system', 'curl_timeout');
137                                         if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
138                                                 $serverfail = true;
139                                         }
140
141                                         // Resubscribe to relay server upon client error
142                                         if (!$serverfail && ($response->getReturnCode() >= 400) && ($response->getReturnCode() <= 499)) {
143                                                 $actor = self:: fetchActorForRelayInbox($inbox);
144                                                 if (!empty($actor)) {
145                                                         $drop = !ActivityPub\Transmitter::sendRelayFollow($actor);
146                                                         Logger::notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]);
147                                                 } elseif ($cmd = WorkerDelivery::DELETION) {
148                                                         // Remote systems not always accept our deletion requests, so we drop them if rejected.
149                                                         // Situation is: In Friendica we allow the thread owner to delete foreign comments to their thread.
150                                                         // Most AP systems don't allow this, so they will reject the deletion request.
151                                                         $drop = true;
152                                                 }
153
154                                         }
155
156                                         Logger::info('Delivery failed', ['retcode' => $response->getReturnCode(), 'serverfailure' => $serverfail, 'drop' => $drop, 'runtime' => round($runtime, 3), 'uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox]);
157                                 }
158                                 if ($uri_id) {
159                                         if ($success) {
160                                                 Post\Delivery::remove($uri_id, $inbox);
161                                         } else {
162                                                 Post\Delivery::incrementFailed($uri_id, $inbox);
163                                         }
164                                 }
165                         }
166                 }
167
168                 self::setSuccess($receivers, $success);
169
170                 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]);
171
172                 if (($success || $drop) && in_array($cmd, [WorkerDelivery::POST])) {
173                         Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
174                 }
175
176                 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
177         }
178
179         /**
180          * Fetch the actor of the given inbox of an relay server
181          *
182          * @param string $inbox
183          * @return string
184          */
185         private static function fetchActorForRelayInbox(string $inbox): string
186         {
187                 $apcontact = DBA::selectFirst('apcontact', ['url'], ["`sharedinbox` = ? AND `type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)",
188                         $inbox, 'Application', 0, Contact::FRIEND]);
189                 return $apcontact['url'] ?? '';
190         }
191
192         /**
193          * mark or unmark the given receivers for archival upon succoess
194          *
195          * @param array $receivers
196          * @param boolean $success
197          * @return void
198          */
199         private static function setSuccess(array $receivers, bool $success)
200         {
201                 $gsid = null;
202
203                 foreach ($receivers as $receiver) {
204                         $contact = Contact::getById($receiver);
205                         if (empty($contact)) {
206                                 continue;
207                         }
208
209                         $gsid = $gsid ?: $contact['gsid'];
210
211                         if ($success) {
212                                 Contact::unmarkForArchival($contact);
213                         } else {
214                                 Contact::markForArchival($contact);
215                         }
216                 }
217
218                 if (!empty($gsid)) {
219                         GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);
220                 }
221         }
222 }