]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Delivery.php
Return the actor, not the array
[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                                                 }
148
149                                         }
150
151                                         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]);
152                                 }
153                                 if ($uri_id) {
154                                         if ($success) {
155                                                 Post\Delivery::remove($uri_id, $inbox);
156                                         } else {
157                                                 Post\Delivery::incrementFailed($uri_id, $inbox);
158                                         }
159                                 }
160                         }
161                 }
162
163                 self::setSuccess($receivers, $success);
164
165                 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success]);
166
167                 if ($success && in_array($cmd, [WorkerDelivery::POST])) {
168                         Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
169                 }
170
171                 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
172         }
173
174         /**
175          * Fetch the actor of the given inbox of an relay server
176          *
177          * @param string $inbox
178          * @return string
179          */
180         private static function fetchActorForRelayInbox(string $inbox): string
181         {
182                 $apcontact = DBA::selectFirst('apcontact', ['url'], ['sharedinbox' => $inbox, 'type' => 'Application']);
183                 return $apcontact['url'] ?? '';
184         }
185
186         /**
187          * mark or unmark the given receivers for archival upon succoess
188          *
189          * @param array $receivers
190          * @param boolean $success
191          * @return void
192          */
193         private static function setSuccess(array $receivers, bool $success)
194         {
195                 $gsid = null;
196
197                 foreach ($receivers as $receiver) {
198                         $contact = Contact::getById($receiver);
199                         if (empty($contact)) {
200                                 continue;
201                         }
202
203                         $gsid = $gsid ?: $contact['gsid'];
204
205                         if ($success) {
206                                 Contact::unmarkForArchival($contact);
207                         } else {
208                                 Contact::markForArchival($contact);
209                         }
210                 }
211
212                 if (!empty($gsid)) {
213                         GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);
214                 }
215         }
216 }