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['verb'] == Activity::ANNOUNCE) {
90 if ($item['id'] == $parent_id) {
93 if ($item['id'] == $target_id) {
98 DBA::close($itemdata);
100 if (empty($target_item)) {
101 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
105 if (empty($parent)) {
106 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
107 self::setFailedQueue($cmd, $target_item);
111 if (!empty($target_item['contact-uid'])) {
112 $uid = $target_item['contact-uid'];
113 } elseif (!empty($target_item['uid'])) {
114 $uid = $target_item['uid'];
116 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
117 self::setFailedQueue($cmd, $target_item);
121 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
122 $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
123 if (!DBA::isResult($thr_parent)) {
124 // Shouldn't happen. But when this does, we just take the parent as thread parent.
125 // That's totally okay for what we use this variable here.
126 $thr_parent = $parent;
129 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
130 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
131 self::setFailedQueue($cmd, $target_item);
135 // avoid race condition with deleting entries
136 if ($items[0]['deleted']) {
137 foreach ($items as $item) {
138 $item['deleted'] = 1;
142 // When commenting too fast after delivery, a post wasn't recognized as top level post.
143 // The count then showed more than one entry. The additional check should help.
144 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
145 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
146 Logger::log('Top level post');
150 // This is IMPORTANT!!!!
152 // We will only send a "notify owner to relay" or followup message if the referenced post
153 // originated on our system by virtue of having our hostname somewhere
154 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
155 // if $parent['wall'] == 1 we will already have the parent message in our array
156 // and we will relay the whole lot.
158 $localhost = DI::baseUrl()->getHostname();
159 if (strpos($localhost, ':')) {
160 $localhost = substr($localhost, 0, strpos($localhost, ':'));
164 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
165 * have been known to cause runaway conditions which affected several servers, along with
166 * permissions issues.
170 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
171 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
172 // local followup to remote post
176 if (empty($parent['allow_cid'])
177 && empty($parent['allow_gid'])
178 && empty($parent['deny_cid'])
179 && empty($parent['deny_gid'])
180 && ($parent["private"] != Model\Item::PRIVATE)) {
181 $public_message = true;
186 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
189 $owner = Model\User::getOwnerDataById($uid);
190 if (!DBA::isResult($owner)) {
191 self::setFailedQueue($cmd, $target_item);
195 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
196 $contact = DBA::selectFirst('contact', [],
197 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
199 if (!DBA::isResult($contact)) {
200 self::setFailedQueue($cmd, $target_item);
204 if (Network::isUrlBlocked($contact['url'])) {
205 self::setFailedQueue($cmd, $target_item);
209 // Transmit via Diaspora if the thread had started as Diaspora post.
210 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
211 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
212 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
213 $contact['network'] = Protocol::DIASPORA;
216 // Ensure that local contacts are delivered locally
217 if (Model\Contact::isLocal($contact['url'])) {
218 $contact['network'] = Protocol::DFRN;
221 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
223 switch ($contact['network']) {
225 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
228 case Protocol::DIASPORA:
229 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
233 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
244 * Increased the "failed" counter in the item delivery data
246 * @param string $cmd Command
247 * @param array $item Item array
249 private static function setFailedQueue(string $cmd, array $item)
251 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
255 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
259 * Deliver content via DFRN
261 * @param string $cmd Command
262 * @param array $contact Contact record of the receiver
263 * @param array $owner Owner record of the sender
264 * @param array $items Item record of the content and the parent
265 * @param array $target_item Item record of the content
266 * @param boolean $public_message Is the content public?
267 * @param boolean $top_level Is it a thread starter?
268 * @param boolean $followup Is it an answer to a remote post?
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 * @throws \ImagickException
272 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
274 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
275 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
276 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
277 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
281 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
283 if ($cmd == self::MAIL) {
284 $item = $target_item;
285 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
286 $atom = DFRN::mail($item, $owner);
287 } elseif ($cmd == self::SUGGESTION) {
288 $item = $target_item;
289 $atom = DFRN::fsuggest($item, $owner);
290 DBA::delete('fsuggest', ['id' => $item['id']]);
291 } elseif ($cmd == self::RELOCATION) {
292 $atom = DFRN::relocate($owner, $owner['uid']);
293 } elseif ($followup) {
294 $msgitems = [$target_item];
295 $atom = DFRN::entries($msgitems, $owner);
298 foreach ($items as $item) {
299 // Only add the parent when we don't delete other items.
300 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
301 $item["entry:comment-allow"] = true;
302 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
306 $atom = DFRN::entries($msgitems, $owner);
309 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
311 // perform local delivery if we are on the same site
312 if (Model\Contact::isLocal($contact['url'])) {
313 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
314 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
315 if (!DBA::isResult($target_self)) {
318 $target_uid = $target_self['uid'];
320 // Check if the user has got this contact
321 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
323 // Otherwise there should be a public contact
324 $cid = Model\Contact::getIdForURL($owner['url']);
330 $target_importer = DFRN::getImporter($cid, $target_uid);
331 if (empty($target_importer)) {
332 // This should never happen
336 DFRN::import($atom, $target_importer);
338 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
339 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
345 $protocol = Model\Post\DeliveryData::DFRN;
347 // We don't have a relationship with contacts on a public post.
348 // Se we transmit with the new method and via Diaspora as a fallback
349 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
350 // Transmit in public if it's a relay post
351 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
353 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
355 // We never spool failed relay deliveries
357 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
359 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
360 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
361 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
363 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
369 if (($deliver_status < 200) || ($deliver_status > 299)) {
370 // Transmit via Diaspora if not possible via Friendica
371 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
374 } elseif ($cmd != self::RELOCATION) {
375 // DFRN payload over Diaspora transport layer
376 $deliver_status = DFRN::transmit($owner, $contact, $atom);
377 if ($deliver_status < 200) {
379 $deliver_status = DFRN::deliver($owner, $contact, $atom);
380 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
383 $deliver_status = DFRN::deliver($owner, $contact, $atom);
384 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
387 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
389 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
390 // We successfully delivered a message, the contact is alive
391 Model\Contact::unmarkForArchival($contact);
393 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
394 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
397 // The message could not be delivered. We mark the contact as "dead"
398 Model\Contact::markForArchival($contact);
400 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
401 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
402 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
408 * Deliver content via Diaspora
410 * @param string $cmd Command
411 * @param array $contact Contact record of the receiver
412 * @param array $owner Owner record of the sender
413 * @param array $items Item record of the content and the parent
414 * @param array $target_item Item record of the content
415 * @param boolean $public_message Is the content public?
416 * @param boolean $top_level Is it a thread starter?
417 * @param boolean $followup Is it an answer to a remote post?
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 * @throws \ImagickException
421 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
423 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
424 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
426 if ($public_message) {
427 $loc = 'public batch ' . $contact['batch'];
429 $loc = $contact['addr'];
432 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
434 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
438 if ($cmd == self::MAIL) {
439 Diaspora::sendMail($target_item, $owner, $contact);
443 if ($cmd == self::SUGGESTION) {
447 if (!$contact['pubkey'] && !$public_message) {
451 if ($cmd == self::RELOCATION) {
452 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
453 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
454 // top-level retraction
455 Logger::log('diaspora retract: ' . $loc);
456 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
457 } elseif ($followup) {
458 // send comments and likes to owner to relay
459 Logger::log('diaspora followup: ' . $loc);
460 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
461 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
462 // we are the relay - send comments, likes and relayable_retractions to our conversants
463 Logger::log('diaspora relay: ' . $loc);
464 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
465 } elseif ($top_level && !$walltowall) {
466 // currently no workable solution for sending walltowall
467 Logger::log('diaspora status: ' . $loc);
468 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
470 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
474 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
475 // We successfully delivered a message, the contact is alive
476 Model\Contact::unmarkForArchival($contact);
478 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
479 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
482 // The message could not be delivered. We mark the contact as "dead"
483 Model\Contact::markForArchival($contact);
485 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
486 if ($public_message) {
487 Diaspora::markRelayForArchival($contact);
490 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
491 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
492 // defer message for redelivery
493 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
494 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
496 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
497 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
503 * Deliver content via mail
505 * @param string $cmd Command
506 * @param array $contact Contact record of the receiver
507 * @param array $owner Owner record of the sender
508 * @param array $target_item Item record of the content
509 * @param array $thr_parent Item record of the direct parent in the thread
510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
511 * @throws \ImagickException
513 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
515 if (DI::config()->get('system','dfrn_only')) {
519 $addr = $contact['addr'];
520 if (!strlen($addr)) {
524 if (!in_array($cmd, [self::POST, self::POKE])) {
528 if ($target_item['verb'] != Activity::POST) {
532 if (!empty($thr_parent['object'])) {
533 $data = json_decode($thr_parent['object'], true);
534 if (!empty($data['reply_to'])) {
535 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
536 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
537 } elseif (!empty($data['from'])) {
538 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
539 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
543 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
544 if (!DBA::isResult($local_user)) {
548 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
551 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
552 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
553 $reply_to = $mailacct['reply_to'];
556 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
558 // only expose our real email address to true friends
560 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
562 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
563 $headers .= 'Sender: ' . $local_user['email'] . "\n";
565 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
568 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
569 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
572 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
574 if ($target_item['uri'] !== $target_item['parent-uri']) {
575 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
577 // Export more references on deeper nested threads
578 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
579 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
584 if (empty($target_item['title'])) {
585 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
586 $title = Model\Item::selectFirst(['title'], $condition);
588 if (DBA::isResult($title) && ($title['title'] != '')) {
589 $subject = $title['title'];
591 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
592 $title = Model\Item::selectFirst(['title'], $condition);
594 if (DBA::isResult($title) && ($title['title'] != '')) {
595 $subject = $title['title'];
600 if (strncasecmp($subject, 'RE:', 3)) {
601 $subject = 'Re: ' . $subject;
605 Email::send($addr, $subject, $headers, $target_item);
607 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
609 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);