3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBA;
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;
39 * Deliver posts to the given inbox
41 * @param string $inbox
42 * @return array with the elements "success" and "uri_ids" of the failed posts
44 public static function deliver(string $inbox): array
47 $posts = Post\Delivery::selectForInbox($inbox);
50 foreach ($posts as $post) {
52 $result = self::deliverToInbox($post['command'], 0, $inbox, $post['uid'], $post['receivers'], $post['uri-id']);
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]);
63 if ($serverfail || (!$result['success'] && !$result['drop'])) {
64 $uri_ids[] = $post['uri-id'];
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];
73 * Deliver the given post to the given inbox
76 * @param integer $item_id
77 * @param string $inbox
79 * @param array $receivers
80 * @param integer $uri_id
83 public static function deliverToInbox(string $cmd, int $item_id, string $inbox, int $uid, array $receivers, int $uri_id): array
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];
96 $item_id = $item['id'];
104 if ($cmd == WorkerDelivery::MAIL) {
105 $data = ActivityPub\Transmitter::createActivityFromMail($item_id);
107 $success = HTTPSignature::transmit($data, $inbox, $uid);
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);
118 $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
120 $timestamp = microtime(true);
121 $response = HTTPSignature::post($data, $inbox, $uid);
122 $runtime = microtime(true) - $timestamp;
123 $success = $response->isSuccess();
124 $serverfail = $response->isTimeout();
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)) {
131 // A 404 means that the inbox doesn't exist. We can stop the delivery here.
132 if (!$serverfail && ($response->getReturnCode() == 404)) {
136 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
137 if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
141 $curl_timeout = DI::config()->get('system', 'curl_timeout');
142 if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
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.
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]);
165 Post\Delivery::remove($uri_id, $inbox);
167 Post\Delivery::incrementFailed($uri_id, $inbox);
171 Post\Delivery::remove($uri_id, $inbox);
175 self::setSuccess($receivers, $success);
177 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]);
179 if (($success || $drop) && in_array($cmd, [WorkerDelivery::POST])) {
180 Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
183 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
187 * Fetch the actor of the given inbox of an relay server
189 * @param string $inbox
192 private static function fetchActorForRelayInbox(string $inbox): string
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'] ?? '';
200 * mark or unmark the given receivers for archival upon succoess
202 * @param array $receivers
203 * @param boolean $success
206 private static function setSuccess(array $receivers, bool $success)
210 foreach ($receivers as $receiver) {
211 $contact = Contact::getById($receiver);
212 if (empty($contact)) {
216 $gsid = $gsid ?: $contact['gsid'];
219 Contact::unmarkForArchival($contact);
221 Contact::markForArchival($contact);
226 GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);