3 * @copyright Copyright (C) 2020, Friendica
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\Worker;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Database\DBA;
29 use Friendica\Protocol\DFRN;
30 use Friendica\Protocol\Diaspora;
31 use Friendica\Protocol\Email;
32 use Friendica\Protocol\Activity;
33 use Friendica\Util\Strings;
34 use Friendica\Util\Network;
35 use Friendica\Core\Worker;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\FContact;
38 use Friendica\Model\Item;
39 use Friendica\Model\Post;
40 use Friendica\Protocol\Relay;
45 const SUGGESTION = 'suggest';
46 const RELOCATION = 'relocate';
47 const DELETION = 'drop';
48 const POST = 'wall-new';
50 const UPLINK = 'uplink';
51 const REMOVAL = 'removeme';
52 const PROFILEUPDATE = 'profileupdate';
54 public static function execute(string $cmd, int $post_uriid, int $contact_id, int $sender_uid = 0)
56 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]);
58 if (!empty($sender_uid)) {
59 $post = Post::selectFirst(['id'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
60 if (!DBA::isResult($post)) {
61 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
64 $target_id = $post['id'];
66 $target_id = $post_uriid;
71 $public_message = false;
74 if ($cmd == self::MAIL) {
75 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
76 if (!DBA::isResult($target_item)) {
79 $uid = $target_item['uid'];
80 } elseif ($cmd == self::SUGGESTION) {
81 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
82 if (!DBA::isResult($target_item)) {
85 $uid = $target_item['uid'];
86 } elseif ($cmd == self::RELOCATION) {
90 $item = Model\Post::selectFirst(['parent'], ['id' => $target_id]);
91 if (!DBA::isResult($item) || empty($item['parent'])) {
94 $parent_id = intval($item['parent']);
96 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
97 $params = ['order' => ['id']];
98 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
100 while ($item = Model\Post::fetch($itemdata)) {
101 if ($item['verb'] == Activity::ANNOUNCE) {
105 if ($item['id'] == $parent_id) {
108 if ($item['id'] == $target_id) {
109 $target_item = $item;
113 DBA::close($itemdata);
115 if (empty($target_item)) {
116 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
120 if (empty($parent)) {
121 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
122 self::setFailedQueue($cmd, $target_item);
126 if (!empty($target_item['contact-uid'])) {
127 $uid = $target_item['contact-uid'];
128 } elseif (!empty($target_item['uid'])) {
129 $uid = $target_item['uid'];
131 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
132 self::setFailedQueue($cmd, $target_item);
136 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
137 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
138 if (!DBA::isResult($thr_parent)) {
139 // Shouldn't happen. But when this does, we just take the parent as thread parent.
140 // That's totally okay for what we use this variable here.
141 $thr_parent = $parent;
144 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
145 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
146 self::setFailedQueue($cmd, $target_item);
150 // avoid race condition with deleting entries
151 if ($items[0]['deleted']) {
152 foreach ($items as $item) {
153 $item['deleted'] = 1;
157 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
159 // This is IMPORTANT!!!!
161 // We will only send a "notify owner to relay" or followup message if the referenced post
162 // originated on our system by virtue of having our hostname somewhere
163 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
164 // if $parent['wall'] == 1 we will already have the parent message in our array
165 // and we will relay the whole lot.
167 $localhost = DI::baseUrl()->getHostname();
168 if (strpos($localhost, ':')) {
169 $localhost = substr($localhost, 0, strpos($localhost, ':'));
173 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
174 * have been known to cause runaway conditions which affected several servers, along with
175 * permissions issues.
179 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
180 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
181 // local followup to remote post
185 if (empty($parent['allow_cid'])
186 && empty($parent['allow_gid'])
187 && empty($parent['deny_cid'])
188 && empty($parent['deny_gid'])
189 && ($parent["private"] != Model\Item::PRIVATE)) {
190 $public_message = true;
195 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
198 $owner = Model\User::getOwnerDataById($uid);
199 if (!DBA::isResult($owner)) {
200 self::setFailedQueue($cmd, $target_item);
204 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
205 $contact = DBA::selectFirst('contact', [],
206 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
208 if (!DBA::isResult($contact)) {
209 self::setFailedQueue($cmd, $target_item);
213 if (Network::isUrlBlocked($contact['url'])) {
214 self::setFailedQueue($cmd, $target_item);
218 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
220 // Transmit via Diaspora if the thread had started as Diaspora post.
221 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
222 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
223 // Also transmit relayed posts from Diaspora contacts via Diaspora.
224 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network'], $target_item['network']])) {
225 $contact['network'] = Protocol::DIASPORA;
228 // Ensure that local contacts are delivered locally
229 if (Model\Contact::isLocal($contact['url'])) {
230 $contact['network'] = Protocol::DFRN;
233 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
235 switch ($contact['network']) {
237 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
240 case Protocol::DIASPORA:
241 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
245 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
256 * Increased the "failed" counter in the item delivery data
258 * @param string $cmd Command
259 * @param array $item Item array
261 private static function setFailedQueue(string $cmd, array $item)
263 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
267 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
271 * Deliver content via DFRN
273 * @param string $cmd Command
274 * @param array $contact Contact record of the receiver
275 * @param array $owner Owner record of the sender
276 * @param array $items Item record of the content and the parent
277 * @param array $target_item Item record of the content
278 * @param boolean $public_message Is the content public?
279 * @param boolean $top_level Is it a thread starter?
280 * @param boolean $followup Is it an answer to a remote post?
281 * @param int $server_protocol The protocol of the server
282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
283 * @throws \ImagickException
285 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $server_protocol)
287 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
288 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
289 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
290 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
294 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
296 if ($cmd == self::MAIL) {
297 $item = $target_item;
298 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
299 $atom = DFRN::mail($item, $owner);
300 } elseif ($cmd == self::SUGGESTION) {
301 $item = $target_item;
302 $atom = DFRN::fsuggest($item, $owner);
303 DBA::delete('fsuggest', ['id' => $item['id']]);
304 } elseif ($cmd == self::RELOCATION) {
305 $atom = DFRN::relocate($owner, $owner['uid']);
306 } elseif ($followup) {
307 $msgitems = [$target_item];
308 $atom = DFRN::entries($msgitems, $owner);
310 if ($target_item['deleted']) {
311 $msgitems = [$target_item];
314 foreach ($items as $item) {
315 // Only add the parent when we don't delete other items.
316 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
317 $item["entry:comment-allow"] = true;
318 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
323 $atom = DFRN::entries($msgitems, $owner);
326 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
328 // perform local delivery if we are on the same site
329 if (Model\Contact::isLocal($contact['url'])) {
330 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
331 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
332 if (!DBA::isResult($target_self)) {
335 $target_uid = $target_self['uid'];
337 // Check if the user has got this contact
338 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
340 // Otherwise there should be a public contact
341 $cid = Model\Contact::getIdForURL($owner['url']);
347 $target_importer = DFRN::getImporter($cid, $target_uid);
348 if (empty($target_importer)) {
349 // This should never happen
353 DFRN::import($atom, $target_importer, Conversation::PARCEL_LOCAL_DFRN, Conversation::PUSH);
355 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
356 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
362 $protocol = Model\Post\DeliveryData::DFRN;
364 // We don't have a relationship with contacts on a public post.
365 // Se we transmit with the new method and via Diaspora as a fallback
366 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
367 // Transmit in public if it's a relay post
368 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
370 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
372 // We never spool failed relay deliveries
374 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
376 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
377 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
378 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
380 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
382 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
388 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
389 // Transmit via Diaspora if not possible via Friendica
390 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
393 } elseif ($cmd != self::RELOCATION) {
394 // DFRN payload over Diaspora transport layer
395 $deliver_status = DFRN::transmit($owner, $contact, $atom);
396 if (($deliver_status < 200) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
398 $deliver_status = DFRN::deliver($owner, $contact, $atom);
399 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
402 $deliver_status = DFRN::deliver($owner, $contact, $atom);
403 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
406 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
408 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
409 // We successfully delivered a message, the contact is alive
410 Model\Contact::unmarkForArchival($contact);
412 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
414 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
415 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
418 // The message could not be delivered. We mark the contact as "dead"
419 Model\Contact::markForArchival($contact);
421 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
422 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
423 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
429 * Deliver content via Diaspora
431 * @param string $cmd Command
432 * @param array $contact Contact record of the receiver
433 * @param array $owner Owner record of the sender
434 * @param array $items Item record of the content and the parent
435 * @param array $target_item Item record of the content
436 * @param boolean $public_message Is the content public?
437 * @param boolean $top_level Is it a thread starter?
438 * @param boolean $followup Is it an answer to a remote post?
439 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
440 * @throws \ImagickException
442 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
444 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
445 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
447 if ($public_message) {
448 $loc = 'public batch ' . $contact['batch'];
450 $loc = $contact['addr'];
453 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
455 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
459 if ($cmd == self::MAIL) {
460 Diaspora::sendMail($target_item, $owner, $contact);
464 if ($cmd == self::SUGGESTION) {
468 if (!$contact['pubkey'] && !$public_message) {
472 if ($cmd == self::RELOCATION) {
473 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
474 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
475 // top-level retraction
476 Logger::log('diaspora retract: ' . $loc);
477 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
478 } elseif ($followup) {
479 // send comments and likes to owner to relay
480 Logger::log('diaspora followup: ' . $loc);
481 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
482 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
483 // we are the relay - send comments, likes and relayable_retractions to our conversants
484 Logger::log('diaspora relay: ' . $loc);
485 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
486 } elseif ($top_level && !$walltowall) {
487 // currently no workable solution for sending walltowall
488 Logger::log('diaspora status: ' . $loc);
489 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
491 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
495 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
496 // We successfully delivered a message, the contact is alive
497 Model\Contact::unmarkForArchival($contact);
499 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
501 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
502 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
505 // The message could not be delivered. We mark the contact as "dead"
506 Model\Contact::markForArchival($contact);
508 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
509 if ($public_message) {
510 Relay::markForArchival($contact);
513 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
514 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
515 // defer message for redelivery
516 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
517 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
519 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
520 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
526 * Deliver content via mail
528 * @param string $cmd Command
529 * @param array $contact Contact record of the receiver
530 * @param array $owner Owner record of the sender
531 * @param array $target_item Item record of the content
532 * @param array $thr_parent Item record of the direct parent in the thread
533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
534 * @throws \ImagickException
536 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
538 if (DI::config()->get('system','dfrn_only')) {
542 $addr = $contact['addr'];
543 if (!strlen($addr)) {
547 if (!in_array($cmd, [self::POST, self::POKE])) {
551 if ($target_item['verb'] != Activity::POST) {
555 if (!empty($thr_parent['object'])) {
556 $data = json_decode($thr_parent['object'], true);
557 if (!empty($data['reply_to'])) {
558 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
559 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
560 } elseif (!empty($data['from'])) {
561 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
562 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
566 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
567 if (!DBA::isResult($local_user)) {
571 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
574 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
575 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
576 $reply_to = $mailacct['reply_to'];
579 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
581 // only expose our real email address to true friends
583 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
585 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
586 $headers .= 'Sender: ' . $local_user['email'] . "\n";
588 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
591 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
592 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
595 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
597 if ($target_item['uri'] !== $target_item['parent-uri']) {
598 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
600 // Export more references on deeper nested threads
601 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
602 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
607 if (empty($target_item['title'])) {
608 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
609 $title = Model\Post::selectFirst(['title'], $condition);
611 if (DBA::isResult($title) && ($title['title'] != '')) {
612 $subject = $title['title'];
614 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
615 $title = Model\Post::selectFirst(['title'], $condition);
617 if (DBA::isResult($title) && ($title['title'] != '')) {
618 $subject = $title['title'];
623 if (strncasecmp($subject, 'RE:', 3)) {
624 $subject = 'Re: ' . $subject;
628 Email::send($addr, $subject, $headers, $target_item);
630 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
632 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);