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\FContact;
41 const SUGGESTION = 'suggest';
42 const RELOCATION = 'relocate';
43 const DELETION = 'drop';
44 const POST = 'wall-new';
46 const UPLINK = 'uplink';
47 const REMOVAL = 'removeme';
48 const PROFILEUPDATE = 'profileupdate';
50 public static function execute($cmd, $target_id, $contact_id)
52 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
56 $public_message = false;
59 if ($cmd == self::MAIL) {
60 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
61 if (!DBA::isResult($target_item)) {
64 $uid = $target_item['uid'];
65 } elseif ($cmd == self::SUGGESTION) {
66 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
67 if (!DBA::isResult($target_item)) {
70 $uid = $target_item['uid'];
71 } elseif ($cmd == self::RELOCATION) {
75 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
76 if (!DBA::isResult($item) || empty($item['parent'])) {
79 $parent_id = intval($item['parent']);
81 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
82 $params = ['order' => ['id']];
83 $itemdata = Model\Item::select([], $condition, $params);
85 while ($item = Model\Item::fetch($itemdata)) {
86 if ($item['id'] == $parent_id) {
89 if ($item['id'] == $target_id) {
94 DBA::close($itemdata);
96 if (empty($target_item)) {
97 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
101 if (empty($parent)) {
102 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
103 self::setFailedQueue($cmd, $target_item);
107 if (!empty($target_item['contact-uid'])) {
108 $uid = $target_item['contact-uid'];
109 } elseif (!empty($target_item['uid'])) {
110 $uid = $target_item['uid'];
112 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
113 self::setFailedQueue($cmd, $target_item);
117 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
118 $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
119 if (!DBA::isResult($thr_parent)) {
120 // Shouldn't happen. But when this does, we just take the parent as thread parent.
121 // That's totally okay for what we use this variable here.
122 $thr_parent = $parent;
125 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
126 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
127 self::setFailedQueue($cmd, $target_item);
131 // avoid race condition with deleting entries
132 if ($items[0]['deleted']) {
133 foreach ($items as $item) {
134 $item['deleted'] = 1;
138 // When commenting too fast after delivery, a post wasn't recognized as top level post.
139 // The count then showed more than one entry. The additional check should help.
140 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
141 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
142 Logger::log('Top level post');
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::log('Followup ' . $target_item["guid"], Logger::DEBUG);
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"] != Model\Item::PRIVATE)) {
177 $public_message = true;
182 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
185 $owner = Model\User::getOwnerDataById($uid);
186 if (!DBA::isResult($owner)) {
187 self::setFailedQueue($cmd, $target_item);
191 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
192 $contact = DBA::selectFirst('contact', [],
193 ['id' => $contact_id, '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 // Transmit via Diaspora if the thread had started as Diaspora post.
206 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
207 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
208 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
209 $contact['network'] = Protocol::DIASPORA;
212 // Ensure that local contacts are delivered locally
213 if (Model\Contact::isLocal($contact['url'])) {
214 $contact['network'] = Protocol::DFRN;
217 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
219 switch ($contact['network']) {
221 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
224 case Protocol::DIASPORA:
225 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
229 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
240 * Increased the "failed" counter in the item delivery data
242 * @param string $cmd Command
243 * @param array $item Item array
245 private static function setFailedQueue(string $cmd, array $item)
247 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
251 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
255 * Deliver content via DFRN
257 * @param string $cmd Command
258 * @param array $contact Contact record of the receiver
259 * @param array $owner Owner record of the sender
260 * @param array $items Item record of the content and the parent
261 * @param array $target_item Item record of the content
262 * @param boolean $public_message Is the content public?
263 * @param boolean $top_level Is it a thread starter?
264 * @param boolean $followup Is it an answer to a remote post?
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266 * @throws \ImagickException
268 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
270 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
271 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
272 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
273 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
277 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
279 if ($cmd == self::MAIL) {
280 $item = $target_item;
281 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
282 $atom = DFRN::mail($item, $owner);
283 } elseif ($cmd == self::SUGGESTION) {
284 $item = $target_item;
285 $atom = DFRN::fsuggest($item, $owner);
286 DBA::delete('fsuggest', ['id' => $item['id']]);
287 } elseif ($cmd == self::RELOCATION) {
288 $atom = DFRN::relocate($owner, $owner['uid']);
289 } elseif ($followup) {
290 $msgitems = [$target_item];
291 $atom = DFRN::entries($msgitems, $owner);
294 foreach ($items as $item) {
295 // Only add the parent when we don't delete other items.
296 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
297 $item["entry:comment-allow"] = true;
298 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
302 $atom = DFRN::entries($msgitems, $owner);
305 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
307 // perform local delivery if we are on the same site
308 if (Model\Contact::isLocal($contact['url'])) {
309 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
310 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
311 if (!DBA::isResult($target_self)) {
314 $target_uid = $target_self['uid'];
316 // Check if the user has got this contact
317 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
319 // Otherwise there should be a public contact
320 $cid = Model\Contact::getIdForURL($owner['url']);
326 $target_importer = DFRN::getImporter($cid, $target_uid);
327 if (empty($target_importer)) {
328 // This should never happen
332 DFRN::import($atom, $target_importer);
334 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
335 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
341 $protocol = Model\Post\DeliveryData::DFRN;
343 // We don't have a relationship with contacts on a public post.
344 // Se we transmit with the new method and via Diaspora as a fallback
345 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
346 // Transmit in public if it's a relay post
347 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
349 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
351 // We never spool failed relay deliveries
353 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
355 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
356 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
357 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
359 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
365 if (($deliver_status < 200) || ($deliver_status > 299)) {
366 // Transmit via Diaspora if not possible via Friendica
367 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
370 } elseif ($cmd != self::RELOCATION) {
371 // DFRN payload over Diaspora transport layer
372 $deliver_status = DFRN::transmit($owner, $contact, $atom);
373 if ($deliver_status < 200) {
375 $deliver_status = DFRN::deliver($owner, $contact, $atom);
376 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
379 $deliver_status = DFRN::deliver($owner, $contact, $atom);
380 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
383 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
385 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
386 // We successfully delivered a message, the contact is alive
387 Model\Contact::unmarkForArchival($contact);
389 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
390 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
393 // The message could not be delivered. We mark the contact as "dead"
394 Model\Contact::markForArchival($contact);
396 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
397 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
398 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
404 * Deliver content via Diaspora
406 * @param string $cmd Command
407 * @param array $contact Contact record of the receiver
408 * @param array $owner Owner record of the sender
409 * @param array $items Item record of the content and the parent
410 * @param array $target_item Item record of the content
411 * @param boolean $public_message Is the content public?
412 * @param boolean $top_level Is it a thread starter?
413 * @param boolean $followup Is it an answer to a remote post?
414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
415 * @throws \ImagickException
417 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
419 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
420 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
422 if ($public_message) {
423 $loc = 'public batch ' . $contact['batch'];
425 $loc = $contact['addr'];
428 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
430 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
434 if ($cmd == self::MAIL) {
435 Diaspora::sendMail($target_item, $owner, $contact);
439 if ($cmd == self::SUGGESTION) {
443 if (!$contact['pubkey'] && !$public_message) {
447 if ($cmd == self::RELOCATION) {
448 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
449 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
450 // top-level retraction
451 Logger::log('diaspora retract: ' . $loc);
452 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
453 } elseif ($followup) {
454 // send comments and likes to owner to relay
455 Logger::log('diaspora followup: ' . $loc);
456 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
457 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
458 // we are the relay - send comments, likes and relayable_retractions to our conversants
459 Logger::log('diaspora relay: ' . $loc);
460 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
461 } elseif ($top_level && !$walltowall) {
462 // currently no workable solution for sending walltowall
463 Logger::log('diaspora status: ' . $loc);
464 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
466 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
470 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
471 // We successfully delivered a message, the contact is alive
472 Model\Contact::unmarkForArchival($contact);
474 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
475 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
478 // The message could not be delivered. We mark the contact as "dead"
479 Model\Contact::markForArchival($contact);
481 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
482 if ($public_message) {
483 Diaspora::markRelayForArchival($contact);
486 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
487 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
488 // defer message for redelivery
489 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
490 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
492 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
493 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
499 * Deliver content via mail
501 * @param string $cmd Command
502 * @param array $contact Contact record of the receiver
503 * @param array $owner Owner record of the sender
504 * @param array $target_item Item record of the content
505 * @param array $thr_parent Item record of the direct parent in the thread
506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
507 * @throws \ImagickException
509 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
511 if (DI::config()->get('system','dfrn_only')) {
515 $addr = $contact['addr'];
516 if (!strlen($addr)) {
520 if (!in_array($cmd, [self::POST, self::POKE])) {
524 if ($target_item['verb'] != Activity::POST) {
528 if (!empty($thr_parent['object'])) {
529 $data = json_decode($thr_parent['object'], true);
530 if (!empty($data['reply_to'])) {
531 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
532 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
533 } elseif (!empty($data['from'])) {
534 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
535 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
539 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
540 if (!DBA::isResult($local_user)) {
544 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
547 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
548 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
549 $reply_to = $mailacct['reply_to'];
552 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
554 // only expose our real email address to true friends
556 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
558 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
559 $headers .= 'Sender: ' . $local_user['email'] . "\n";
561 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
564 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
565 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
568 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
570 if ($target_item['uri'] !== $target_item['parent-uri']) {
571 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
573 // Export more references on deeper nested threads
574 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
575 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
580 if (empty($target_item['title'])) {
581 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
582 $title = Model\Item::selectFirst(['title'], $condition);
584 if (DBA::isResult($title) && ($title['title'] != '')) {
585 $subject = $title['title'];
587 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
588 $title = Model\Item::selectFirst(['title'], $condition);
590 if (DBA::isResult($title) && ($title['title'] != '')) {
591 $subject = $title['title'];
596 if (strncasecmp($subject, 'RE:', 3)) {
597 $subject = 'Re: ' . $subject;
601 Email::send($addr, $subject, $headers, $target_item);
603 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
605 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);