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;
24 use Friendica\Contact\FriendSuggest\Collection\FriendSuggests;
25 use Friendica\Contact\FriendSuggest\Exception\FriendSuggestNotFoundException;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\GServer;
33 use Friendica\Model\Item;
34 use Friendica\Model\Post;
35 use Friendica\Model\User;
36 use Friendica\Util\Network;
41 const SUGGESTION = 'suggest';
42 const RELOCATION = 'relocate';
43 const DELETION = 'drop';
44 const POST = 'wall-new';
45 const REMOVAL = 'removeme';
46 const PROFILEUPDATE = 'profileupdate';
48 public static function deliver(string $cmd, int $post_uriid, int $contact_id, int $sender_uid = 0)
50 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]);
54 $public_message = false;
57 if ($cmd == self::MAIL) {
58 $target_item = DBA::selectFirst('mail', [], ['id' => $post_uriid]);
59 if (!DBA::isResult($target_item)) {
62 $uid = $target_item['uid'];
63 } elseif ($cmd == self::SUGGESTION) {
65 $target_item = DI::fsuggest()->selectOneById($post_uriid)->toArray();
66 } catch (FriendSuggestNotFoundException $e) {
67 DI::logger()->info('Cannot find FriendSuggestion', ['id' => $post_uriid]);
70 $uid = $target_item['uid'];
71 } elseif ($cmd == self::RELOCATION) {
75 $item = Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
76 if (!DBA::isResult($item) || empty($item['parent'])) {
77 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
80 $target_id = intval($item['id']);
81 $parent_id = intval($item['parent']);
83 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
84 $params = ['order' => ['id']];
85 $itemdata = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
87 while ($item = Post::fetch($itemdata)) {
88 if ($item['verb'] == Activity::ANNOUNCE) {
92 if ($item['id'] == $parent_id) {
95 if ($item['id'] == $target_id) {
100 DBA::close($itemdata);
102 if (empty($target_item)) {
103 Logger::warning("No target item data. Quitting here.", ['id' => $target_id]);
107 if (empty($parent)) {
108 Logger::warning('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
109 self::setFailedQueue($cmd, $target_item);
113 if (!empty($target_item['contact-uid'])) {
114 $uid = $target_item['contact-uid'];
115 } elseif (!empty($target_item['uid'])) {
116 $uid = $target_item['uid'];
118 Logger::info('Only public users for item ' . $target_id);
119 self::setFailedQueue($cmd, $target_item);
123 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
124 $thr_parent = Post::selectFirst(['network', 'object'], $condition);
125 if (!DBA::isResult($thr_parent)) {
126 // Shouldn't happen. But when this does, we just take the parent as thread parent.
127 // That's totally okay for what we use this variable here.
128 $thr_parent = $parent;
131 if (!empty($contact_id) && Contact::isArchived($contact_id)) {
132 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
133 self::setFailedQueue($cmd, $target_item);
137 // avoid race condition with deleting entries
138 if ($items[0]['deleted']) {
139 foreach ($items as $item) {
140 $item['deleted'] = 1;
144 $top_level = $target_item['gravity'] == Item::GRAVITY_PARENT;
146 // This is IMPORTANT!!!!
148 // We will only send a "notify owner to relay" or followup message if the referenced post
149 // originated on our system by virtue of having our hostname somewhere
150 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
151 // if $parent['wall'] == 1 we will already have the parent message in our array
152 // and we will relay the whole lot.
154 $localhost = DI::baseUrl()->getHostname();
155 if (strpos($localhost, ':')) {
156 $localhost = substr($localhost, 0, strpos($localhost, ':'));
160 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
161 * have been known to cause runaway conditions which affected several servers, along with
162 * permissions issues.
166 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
167 Logger::info('Followup ' . $target_item["guid"]);
168 // local followup to remote post
172 if (empty($parent['allow_cid'])
173 && empty($parent['allow_gid'])
174 && empty($parent['deny_cid'])
175 && empty($parent['deny_gid'])
176 && ($parent['private'] != Item::PRIVATE)) {
177 $public_message = true;
182 Logger::warning('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]);
185 $owner = User::getOwnerDataById($uid);
186 if (!DBA::isResult($owner)) {
187 self::setFailedQueue($cmd, $target_item);
191 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
192 $contact = DBA::selectFirst('contact', [],
193 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
195 if (!DBA::isResult($contact)) {
196 self::setFailedQueue($cmd, $target_item);
200 if (Network::isUrlBlocked($contact['url'])) {
201 self::setFailedQueue($cmd, $target_item);
205 $protocol = GServer::getProtocol($contact['gsid'] ?? 0);
207 // Transmit via Diaspora if the thread had started as Diaspora post.
208 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
209 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
210 // Also transmit relayed posts from Diaspora contacts via Diaspora.
211 if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network'] ?? ''])) {
212 Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]);
213 $contact['network'] = Protocol::DIASPORA;
216 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
218 switch ($contact['network']) {
220 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
223 case Protocol::DIASPORA:
224 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
228 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
239 * Increased the "failed" counter in the item delivery data
241 * @param string $cmd Command
242 * @param array $item Item array
246 private static function setFailedQueue(string $cmd, array $item)
248 if ($cmd != Delivery::POST) {
252 Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
256 * Deliver content via DFRN
258 * @param string $cmd Command
259 * @param array $contact Contact record of the receiver
260 * @param array $owner Owner record of the sender
261 * @param array $items Item record of the content and the parent
262 * @param array $target_item Item record of the content
263 * @param boolean $public_message Is the content public?
264 * @param boolean $top_level Is it a thread starter?
265 * @param boolean $followup Is it an answer to a remote post?
266 * @param int|null $server_protocol The protocol of the server
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 * @throws \ImagickException
272 private static function deliverDFRN(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup, int $server_protocol = null)
274 $target_item_id = $target_item['guid'] ?? '' ?: $target_item['id'] ?? null;
276 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
277 if (Diaspora::getReshareDetails($target_item) && Diaspora::isSupportedByContactUrl($contact['addr'])) {
278 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => $target_item_id]);
279 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
283 Logger::info('Deliver ' . ($target_item_id ?? 'relocation') . ' via DFRN to ' . ($contact['addr'] ?? '' ?: $contact['url']));
285 if ($cmd == self::MAIL) {
286 $item = $target_item;
287 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
288 $atom = DFRN::mail($item, $owner);
289 } elseif ($cmd == self::SUGGESTION) {
290 $item = $target_item;
291 $atom = DFRN::fsuggest($item, $owner);
292 DI::fsuggest()->delete(new FriendSuggests([DI::fsuggest()->selectOneById($item['id'])]));
293 } elseif ($cmd == self::RELOCATION) {
294 $atom = DFRN::relocate($owner, $owner['uid']);
295 } elseif ($followup) {
296 $msgitems = [$target_item];
297 $atom = DFRN::entries($msgitems, $owner);
299 if ($target_item['deleted']) {
300 $msgitems = [$target_item];
303 foreach ($items as $item) {
304 // Only add the parent when we don't delete other items.
305 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
306 $item['entry:comment-allow'] = true;
307 $item['entry:cid'] = ($top_level ? $contact['id'] : 0);
312 $atom = DFRN::entries($msgitems, $owner);
315 Logger::debug('Notifier entry: ' . $contact['url'] . ' ' . ($target_item_id ?? 'relocation') . ' entry: ' . $atom);
317 $protocol = Post\DeliveryData::DFRN;
319 // We don't have a relationship with contacts on a public post.
320 // Se we transmit with the new method and via Diaspora as a fallback
321 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
322 // Transmit in public if it's a relay post
323 $public_dfrn = ($contact['contact-type'] == Contact::TYPE_RELAY);
325 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
327 // We never spool failed relay deliveries
329 Logger::info('Relay delivery to ' . $contact['url'] . ' with guid ' . $target_item['guid'] . ' returns ' . $deliver_status);
331 if ($cmd == Delivery::POST) {
332 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
333 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
335 GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
337 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
343 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Post\DeliveryData::LEGACY_DFRN))) {
344 // Transmit via Diaspora if not possible via Friendica
345 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
349 // DFRN payload over Diaspora transport layer
350 $deliver_status = DFRN::transmit($owner, $contact, $atom);
353 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => $target_item_id, 'return' => $deliver_status]);
355 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
356 // We successfully delivered a message, the contact is alive
357 Contact::unmarkForArchival($contact);
359 GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
361 if ($cmd == Delivery::POST) {
362 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
365 // The message could not be delivered. We mark the contact as "dead"
366 Contact::markForArchival($contact);
368 Logger::info('Delivery failed: defer message', ['id' => $target_item_id]);
369 if (!Worker::defer() && $cmd == Delivery::POST) {
370 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
376 * Deliver content via Diaspora
378 * @param string $cmd Command
379 * @param array $contact Contact record of the receiver
380 * @param array $owner Owner record of the sender
381 * @param array $items Item record of the content and the parent
382 * @param array $target_item Item record of the content
383 * @param boolean $public_message Is the content public?
384 * @param boolean $top_level Is it a thread starter?
385 * @param boolean $followup Is it an answer to a remote post?
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 * @throws \ImagickException
391 private static function deliverDiaspora(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup)
393 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
394 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
396 if ($public_message) {
397 $loc = 'public batch ' . $contact['batch'];
399 $loc = $contact['addr'];
402 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
404 if (!DI::config()->get('system', 'diaspora_enabled')) {
408 if ($cmd == self::MAIL) {
409 Diaspora::sendMail($target_item, $owner, $contact);
413 if ($cmd == self::SUGGESTION) {
417 if (!$contact['pubkey'] && !$public_message) {
421 if ($cmd == self::RELOCATION) {
422 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
423 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
424 // top-level retraction
425 Logger::notice('diaspora retract: ' . $loc);
426 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
427 } elseif ($followup) {
428 // send comments and likes to owner to relay
429 Logger::notice('diaspora followup: ' . $loc);
430 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
431 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
432 // we are the relay - send comments, likes and relayable_retractions to our conversants
433 Logger::notice('diaspora relay: ' . $loc);
434 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
435 } elseif ($top_level && !$walltowall) {
436 // currently no workable solution for sending walltowall
437 Logger::notice('diaspora status: ' . $loc);
438 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
440 Logger::warning('Unknown mode', ['command' => $cmd, 'target' => $loc]);
444 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
445 // We successfully delivered a message, the contact is alive
446 Contact::unmarkForArchival($contact);
448 GServer::setProtocol($contact['gsid'] ?? 0, Post\DeliveryData::DIASPORA);
450 if ($cmd == Delivery::POST) {
451 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::DIASPORA);
454 // The message could not be delivered. We mark the contact as "dead"
455 Contact::markForArchival($contact);
457 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
458 if ($public_message) {
459 Relay::markForArchival($contact);
462 if (empty($contact['contact-type']) || ($contact['contact-type'] != Contact::TYPE_RELAY)) {
463 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
464 // defer message for redelivery
465 if (!Worker::defer() && $cmd == Delivery::POST) {
466 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
468 } elseif ($cmd == Delivery::POST) {
469 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
475 * Deliver content via mail
477 * @param string $cmd Command
478 * @param array $contact Contact record of the receiver
479 * @param array $owner Owner record of the sender
480 * @param array $target_item Item record of the content
481 * @param array $thr_parent Item record of the direct parent in the thread
484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
485 * @throws \ImagickException
487 private static function deliverMail(string $cmd, array $contact, array $owner, array $target_item, array $thr_parent)
489 if (DI::config()->get('system', 'imap_disabled')) {
493 $addr = $contact['addr'];
494 if (!strlen($addr)) {
498 if ($cmd != self::POST) {
502 if ($target_item['verb'] != Activity::POST) {
506 if (!empty($thr_parent['object'])) {
507 $data = json_decode($thr_parent['object'], true);
508 if (!empty($data['reply_to'])) {
509 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
510 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
511 } elseif (!empty($data['from'])) {
512 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
513 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
517 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
518 if (!DBA::isResult($local_user)) {
522 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
525 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
526 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
527 $reply_to = $mailacct['reply_to'];
530 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
532 // only expose our real email address to true friends
534 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
536 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
537 $headers .= 'Sender: ' . $local_user['email'] . "\n";
539 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
542 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
543 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
546 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
548 if ($target_item['uri'] !== $target_item['parent-uri']) {
549 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
551 // Export more references on deeper nested threads
552 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
553 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
558 if (empty($target_item['title'])) {
559 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
560 $title = Post::selectFirst(['title'], $condition);
562 if (DBA::isResult($title) && ($title['title'] != '')) {
563 $subject = $title['title'];
565 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
566 $title = Post::selectFirst(['title'], $condition);
568 if (DBA::isResult($title) && ($title['title'] != '')) {
569 $subject = $title['title'];
574 if (strncasecmp($subject, 'RE:', 3)) {
575 $subject = 'Re: ' . $subject;
580 $success = Email::send($addr, $subject, $headers, $target_item);
584 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::MAIL);
585 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);
588 Logger::warning('Delivery of mail has FAILED', ['to' => $addr, 'subject' => $subject, 'guid' => $target_item['guid']]);