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\Post;
31 use Friendica\Protocol\ActivityPub;
32 use Friendica\Util\HTTPSignature;
33 use Friendica\Worker\Delivery as WorkerDelivery;
38 * Deliver posts to the given inbox
40 * @param string $inbox
41 * @return array with the elements "success" and "uri_ids" of the failed posts
43 public static function deliver(string $inbox): array
46 $posts = Post\Delivery::selectForInbox($inbox);
49 foreach ($posts as $post) {
51 $result = self::deliverToInbox($post['command'], 0, $inbox, $post['uid'], $post['receivers'], $post['uri-id']);
53 if ($result['serverfailure']) {
54 // In a timeout situation we assume that every delivery to that inbox will time out.
55 // So we set the flag and try all deliveries at a later time.
56 Logger::notice('Inbox delivery has a server failure', ['inbox' => $inbox]);
62 if ($serverfail || (!$result['success'] && !$result['drop'])) {
63 $uri_ids[] = $post['uri-id'];
67 Logger::debug('Inbox delivery done', ['inbox' => $inbox, 'posts' => count($posts), 'failed' => count($uri_ids), 'serverfailure' => $serverfail]);
68 return ['success' => empty($uri_ids), 'uri_ids' => $uri_ids];
72 * Deliver the given post to the given inbox
75 * @param integer $item_id
76 * @param string $inbox
78 * @param array $receivers
79 * @param integer $uri_id
82 public static function deliverToInbox(string $cmd, int $item_id, string $inbox, int $uid, array $receivers, int $uri_id): array
84 if (empty($item_id) && !empty($uri_id) && !empty($uid)) {
85 $item = Post::selectFirst(['id', 'parent', 'origin', 'gravity'], ['uri-id' => $uri_id, 'uid' => [$uid, 0]], ['order' => ['uid' => true]]);
86 if (empty($item['id'])) {
87 Logger::warning('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]);
88 Post\Delivery::remove($uri_id, $inbox);
89 return ['success' => true, 'serverfailure' => false, 'drop' => false];
90 } elseif (!$item['origin'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
91 Logger::notice('Activities are not relayed, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]);
92 Post\Delivery::remove($uri_id, $inbox);
93 return ['success' => true, 'serverfailure' => false, 'drop' => false];
95 $item_id = $item['id'];
103 if ($cmd == WorkerDelivery::MAIL) {
104 $data = ActivityPub\Transmitter::createActivityFromMail($item_id);
106 $success = HTTPSignature::transmit($data, $inbox, $uid);
108 } elseif ($cmd == WorkerDelivery::SUGGESTION) {
109 $success = ActivityPub\Transmitter::sendContactSuggestion($uid, $inbox, $item_id);
110 } elseif ($cmd == WorkerDelivery::RELOCATION) {
111 // @todo Implementation pending
112 } elseif ($cmd == WorkerDelivery::REMOVAL) {
113 $success = ActivityPub\Transmitter::sendProfileDeletion($uid, $inbox);
114 } elseif ($cmd == WorkerDelivery::PROFILEUPDATE) {
115 $success = ActivityPub\Transmitter::sendProfileUpdate($uid, $inbox);
117 $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
119 $timestamp = microtime(true);
120 $response = HTTPSignature::post($data, $inbox, $uid);
121 $runtime = microtime(true) - $timestamp;
122 $success = $response->isSuccess();
123 $serverfail = $response->isTimeout();
125 // 5xx errors are problems on the server. We don't need to continue delivery then.
126 if (!$serverfail && ($response->getReturnCode() >= 500) && ($response->getReturnCode() <= 599)) {
130 // A 404 means that the inbox doesn't exist. We can stop the delivery here.
131 if (!$serverfail && ($response->getReturnCode() == 404)) {
135 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
136 if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
140 $curl_timeout = DI::config()->get('system', 'curl_timeout');
141 if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
145 // Resubscribe to relay server upon client error
146 if (!$serverfail && ($response->getReturnCode() >= 400) && ($response->getReturnCode() <= 499)) {
147 $actor = self:: fetchActorForRelayInbox($inbox);
148 if (!empty($actor)) {
149 $drop = !ActivityPub\Transmitter::sendRelayFollow($actor);
150 Logger::notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]);
151 } elseif ($cmd = WorkerDelivery::DELETION) {
152 // Remote systems not always accept our deletion requests, so we drop them if rejected.
153 // Situation is: In Friendica we allow the thread owner to delete foreign comments to their thread.
154 // Most AP systems don't allow this, so they will reject the deletion request.
160 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]);
164 Post\Delivery::remove($uri_id, $inbox);
166 Post\Delivery::incrementFailed($uri_id, $inbox);
170 Post\Delivery::remove($uri_id, $inbox);
174 self::setSuccess($receivers, $success);
176 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]);
178 if (($success || $drop) && in_array($cmd, [WorkerDelivery::POST])) {
179 Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
182 return ['success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop];
186 * Fetch the actor of the given inbox of an relay server
188 * @param string $inbox
191 private static function fetchActorForRelayInbox(string $inbox): string
193 $apcontact = DBA::selectFirst('apcontact', ['url'], ["`sharedinbox` = ? AND `type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)",
194 $inbox, 'Application', 0, Contact::FRIEND]);
195 return $apcontact['url'] ?? '';
199 * mark or unmark the given receivers for archival upon succoess
201 * @param array $receivers
202 * @param boolean $success
205 private static function setSuccess(array $receivers, bool $success)
209 foreach ($receivers as $receiver) {
210 $contact = Contact::getById($receiver);
211 if (empty($contact)) {
215 $gsid = $gsid ?: $contact['gsid'];
218 Contact::unmarkForArchival($contact);
220 Contact::markForArchival($contact);
225 GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);