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