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