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\Model\User;
33 use Friendica\Protocol\ActivityPub;
34 use Friendica\Protocol\Delivery as ProtocolDelivery;
35 use Friendica\Util\HTTPSignature;
40 * Deliver posts to the given inbox
42 * @param string $inbox
43 * @return array with the elements "success" and "uri_ids" of the failed posts
45 public static function deliver(string $inbox): array
48 $posts = Post\Delivery::selectForInbox($inbox);
51 foreach ($posts as $post) {
52 $owner = User::getOwnerDataById($post['uid']);
54 Post\Delivery::remove($post['uri-id'], $inbox);
55 Post\Delivery::incrementFailed($post['uri-id'], $inbox);
60 $result = self::deliverToInbox($post['command'], 0, $inbox, $owner, $post['receivers'], $post['uri-id']);
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]);
71 if ($serverfail || (!$result['success'] && !$result['drop'])) {
72 $uri_ids[] = $post['uri-id'];
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];
81 * Deliver the given post to the given inbox
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
91 public static function deliverToInbox(string $cmd, int $item_id, string $inbox, array $owner, array $receivers, int $uri_id): array
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];
107 $item_id = $item['id'];
115 if ($cmd == ProtocolDelivery::MAIL) {
116 $data = ActivityPub\Transmitter::createActivityFromMail($item_id);
118 $success = HTTPSignature::transmit($data, $inbox, $owner);
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);
129 $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
131 $timestamp = microtime(true);
132 $response = HTTPSignature::post($data, $inbox, $owner);
133 $runtime = microtime(true) - $timestamp;
134 $success = $response->isSuccess();
135 $serverfail = $response->isTimeout();
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)) {
142 // A 404 means that the inbox doesn't exist. We can stop the delivery here.
143 if (!$serverfail && ($response->getReturnCode() == 404)) {
147 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
148 if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
152 $curl_timeout = DI::config()->get('system', 'curl_timeout');
153 if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
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.
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]);
176 Post\Delivery::remove($uri_id, $inbox);
178 Post\Delivery::incrementFailed($uri_id, $inbox);
182 Post\Delivery::remove($uri_id, $inbox);
186 self::setSuccess($receivers, $success);
188 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]);
190 if (($success || $drop) && in_array($cmd, [ProtocolDelivery::POST])) {
191 Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
194 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
198 * Fetch the actor of the given inbox of an relay server
200 * @param string $inbox
203 private static function fetchActorForRelayInbox(string $inbox): string
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'] ?? '';
211 * mark or unmark the given receivers for archival upon succoess
213 * @param array $receivers
214 * @param boolean $success
217 private static function setSuccess(array $receivers, bool $success)
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)) {
228 $contact = Contact::getById($receiver);
229 if (empty($contact)) {
233 $gsid = $gsid ?: $contact['gsid'];
236 Contact::unmarkForArchival($contact);
238 Contact::markForArchival($contact);
243 GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);