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