]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Delivery.php
Detect and remove contact duplicates
[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::notice('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::warning('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]);
86                                 Post\Delivery::remove($uri_id, $inbox);
87                                 return ['success' => true, 'serverfailure' => false, 'drop' => false];
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::REMOVAL) {
107                         $success = ActivityPub\Transmitter::sendProfileDeletion($uid, $inbox);
108                 } elseif ($cmd == WorkerDelivery::PROFILEUPDATE) {
109                         $success = ActivityPub\Transmitter::sendProfileUpdate($uid, $inbox);
110                 } else {
111                         $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
112                         if (!empty($data)) {
113                                 $timestamp  = microtime(true);
114                                 $response   = HTTPSignature::post($data, $inbox, $uid);
115                                 $runtime    = microtime(true) - $timestamp;
116                                 $success    = $response->isSuccess();
117                                 $serverfail = $response->isTimeout();
118                                 if (!$success) {
119                                         // 5xx errors are problems on the server. We don't need to continue delivery then.
120                                         if (!$serverfail && ($response->getReturnCode() >= 500) && ($response->getReturnCode() <= 599)) {
121                                                 $serverfail = true;
122                                         }
123
124                                         // A 404 means that the inbox doesn't exist. We can stop the delivery here.
125                                         if (!$serverfail && ($response->getReturnCode() == 404)) {
126                                                 $serverfail = true;
127                                         }
128
129                                         $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
130                                         if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
131                                                 $serverfail = true;
132                                         }
133
134                                         $curl_timeout = DI::config()->get('system', 'curl_timeout');
135                                         if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
136                                                 $serverfail = true;
137                                         }
138
139                                         // Resubscribe to relay server upon client error
140                                         if (!$serverfail && ($response->getReturnCode() >= 400) && ($response->getReturnCode() <= 499)) {
141                                                 $actor = self:: fetchActorForRelayInbox($inbox);
142                                                 if (!empty($actor)) {
143                                                         $drop = !ActivityPub\Transmitter::sendRelayFollow($actor);
144                                                         Logger::notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]);
145                                                 } elseif ($cmd = WorkerDelivery::DELETION) {
146                                                         // Remote systems not always accept our deletion requests, so we drop them if rejected.
147                                                         // Situation is: In Friendica we allow the thread owner to delete foreign comments to their thread.
148                                                         // Most AP systems don't allow this, so they will reject the deletion request.
149                                                         $drop = true;
150                                                 }
151
152                                         }
153
154                                         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]);
155                                 }
156                                 if ($uri_id) {
157                                         if ($success) {
158                                                 Post\Delivery::remove($uri_id, $inbox);
159                                         } else {
160                                                 Post\Delivery::incrementFailed($uri_id, $inbox);
161                                         }
162                                 }
163                         }
164                 }
165
166                 self::setSuccess($receivers, $success);
167
168                 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]);
169
170                 if (($success || $drop) && in_array($cmd, [WorkerDelivery::POST])) {
171                         Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
172                 }
173
174                 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
175         }
176
177         /**
178          * Fetch the actor of the given inbox of an relay server
179          *
180          * @param string $inbox
181          * @return string
182          */
183         private static function fetchActorForRelayInbox(string $inbox): string
184         {
185                 $apcontact = DBA::selectFirst('apcontact', ['url'], ["`sharedinbox` = ? AND `type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)",
186                         $inbox, 'Application', 0, Contact::FRIEND]);
187                 return $apcontact['url'] ?? '';
188         }
189
190         /**
191          * mark or unmark the given receivers for archival upon succoess
192          *
193          * @param array $receivers
194          * @param boolean $success
195          * @return void
196          */
197         private static function setSuccess(array $receivers, bool $success)
198         {
199                 $gsid = null;
200
201                 foreach ($receivers as $receiver) {
202                         $contact = Contact::getById($receiver);
203                         if (empty($contact)) {
204                                 continue;
205                         }
206
207                         $gsid = $gsid ?: $contact['gsid'];
208
209                         if ($success) {
210                                 Contact::unmarkForArchival($contact);
211                         } else {
212                                 Contact::markForArchival($contact);
213                         }
214                 }
215
216                 if (!empty($gsid)) {
217                         GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);
218                 }
219         }
220 }