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\Protocol\Relay;
43 const SUGGESTION = 'suggest';
44 const RELOCATION = 'relocate';
45 const DELETION = 'drop';
46 const POST = 'wall-new';
48 const UPLINK = 'uplink';
49 const REMOVAL = 'removeme';
50 const PROFILEUPDATE = 'profileupdate';
52 public static function execute($cmd, $target_id, $contact_id)
54 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
58 $public_message = false;
61 if ($cmd == self::MAIL) {
62 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
63 if (!DBA::isResult($target_item)) {
66 $uid = $target_item['uid'];
67 } elseif ($cmd == self::SUGGESTION) {
68 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
69 if (!DBA::isResult($target_item)) {
72 $uid = $target_item['uid'];
73 } elseif ($cmd == self::RELOCATION) {
77 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
78 if (!DBA::isResult($item) || empty($item['parent'])) {
81 $parent_id = intval($item['parent']);
83 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
84 $params = ['order' => ['id']];
85 $itemdata = Model\Item::select([], $condition, $params);
87 while ($item = Model\Item::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::log('Item ' . $target_id . "wasn't found. Quitting here.");
107 if (empty($parent)) {
108 Logger::log('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::log('Only public users for item ' . $target_id, Logger::DEBUG);
119 self::setFailedQueue($cmd, $target_item);
123 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
124 $thr_parent = Model\Item::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) && Model\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'] == 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::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, 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 // 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 // Also transmit relayed posts from Diaspora contacts via Diaspora.
209 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network'], $target_item['network']])) {
210 $contact['network'] = Protocol::DIASPORA;
213 // Ensure that local contacts are delivered locally
214 if (Model\Contact::isLocal($contact['url'])) {
215 $contact['network'] = Protocol::DFRN;
218 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
220 switch ($contact['network']) {
222 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
225 case Protocol::DIASPORA:
226 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
230 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
241 * Increased the "failed" counter in the item delivery data
243 * @param string $cmd Command
244 * @param array $item Item array
246 private static function setFailedQueue(string $cmd, array $item)
248 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
252 Model\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 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 * @throws \ImagickException
269 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
271 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
272 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
273 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
274 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
278 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
280 if ($cmd == self::MAIL) {
281 $item = $target_item;
282 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
283 $atom = DFRN::mail($item, $owner);
284 } elseif ($cmd == self::SUGGESTION) {
285 $item = $target_item;
286 $atom = DFRN::fsuggest($item, $owner);
287 DBA::delete('fsuggest', ['id' => $item['id']]);
288 } elseif ($cmd == self::RELOCATION) {
289 $atom = DFRN::relocate($owner, $owner['uid']);
290 } elseif ($followup) {
291 $msgitems = [$target_item];
292 $atom = DFRN::entries($msgitems, $owner);
294 if ($target_item['deleted']) {
295 $msgitems = [$target_item];
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);
307 $atom = DFRN::entries($msgitems, $owner);
310 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
312 // perform local delivery if we are on the same site
313 if (Model\Contact::isLocal($contact['url'])) {
314 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
315 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
316 if (!DBA::isResult($target_self)) {
319 $target_uid = $target_self['uid'];
321 // Check if the user has got this contact
322 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
324 // Otherwise there should be a public contact
325 $cid = Model\Contact::getIdForURL($owner['url']);
331 $target_importer = DFRN::getImporter($cid, $target_uid);
332 if (empty($target_importer)) {
333 // This should never happen
337 DFRN::import($atom, $target_importer, false, Conversation::PARCEL_LOCAL_DFRN);
339 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
340 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
346 $protocol = Model\Post\DeliveryData::DFRN;
348 // We don't have a relationship with contacts on a public post.
349 // Se we transmit with the new method and via Diaspora as a fallback
350 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
351 // Transmit in public if it's a relay post
352 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
354 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
356 // We never spool failed relay deliveries
358 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
360 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
361 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
362 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
364 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
370 if (($deliver_status < 200) || ($deliver_status > 299)) {
371 // Transmit via Diaspora if not possible via Friendica
372 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
375 } elseif ($cmd != self::RELOCATION) {
376 // DFRN payload over Diaspora transport layer
377 $deliver_status = DFRN::transmit($owner, $contact, $atom);
378 if ($deliver_status < 200) {
380 $deliver_status = DFRN::deliver($owner, $contact, $atom);
381 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
384 $deliver_status = DFRN::deliver($owner, $contact, $atom);
385 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
388 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
390 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
391 // We successfully delivered a message, the contact is alive
392 Model\Contact::unmarkForArchival($contact);
394 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
395 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
398 // The message could not be delivered. We mark the contact as "dead"
399 Model\Contact::markForArchival($contact);
401 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
402 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
403 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
409 * Deliver content via Diaspora
411 * @param string $cmd Command
412 * @param array $contact Contact record of the receiver
413 * @param array $owner Owner record of the sender
414 * @param array $items Item record of the content and the parent
415 * @param array $target_item Item record of the content
416 * @param boolean $public_message Is the content public?
417 * @param boolean $top_level Is it a thread starter?
418 * @param boolean $followup Is it an answer to a remote post?
419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 * @throws \ImagickException
422 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
424 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
425 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
427 if ($public_message) {
428 $loc = 'public batch ' . $contact['batch'];
430 $loc = $contact['addr'];
433 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
435 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
439 if ($cmd == self::MAIL) {
440 Diaspora::sendMail($target_item, $owner, $contact);
444 if ($cmd == self::SUGGESTION) {
448 if (!$contact['pubkey'] && !$public_message) {
452 if ($cmd == self::RELOCATION) {
453 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
454 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
455 // top-level retraction
456 Logger::log('diaspora retract: ' . $loc);
457 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
458 } elseif ($followup) {
459 // send comments and likes to owner to relay
460 Logger::log('diaspora followup: ' . $loc);
461 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
462 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
463 // we are the relay - send comments, likes and relayable_retractions to our conversants
464 Logger::log('diaspora relay: ' . $loc);
465 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
466 } elseif ($top_level && !$walltowall) {
467 // currently no workable solution for sending walltowall
468 Logger::log('diaspora status: ' . $loc);
469 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
471 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
475 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
476 // We successfully delivered a message, the contact is alive
477 Model\Contact::unmarkForArchival($contact);
479 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
480 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
483 // The message could not be delivered. We mark the contact as "dead"
484 Model\Contact::markForArchival($contact);
486 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
487 if ($public_message) {
488 Relay::markForArchival($contact);
491 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
492 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
493 // defer message for redelivery
494 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
495 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
497 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
498 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
504 * Deliver content via mail
506 * @param string $cmd Command
507 * @param array $contact Contact record of the receiver
508 * @param array $owner Owner record of the sender
509 * @param array $target_item Item record of the content
510 * @param array $thr_parent Item record of the direct parent in the thread
511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
512 * @throws \ImagickException
514 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
516 if (DI::config()->get('system','dfrn_only')) {
520 $addr = $contact['addr'];
521 if (!strlen($addr)) {
525 if (!in_array($cmd, [self::POST, self::POKE])) {
529 if ($target_item['verb'] != Activity::POST) {
533 if (!empty($thr_parent['object'])) {
534 $data = json_decode($thr_parent['object'], true);
535 if (!empty($data['reply_to'])) {
536 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
537 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
538 } elseif (!empty($data['from'])) {
539 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
540 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
544 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
545 if (!DBA::isResult($local_user)) {
549 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
552 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
553 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
554 $reply_to = $mailacct['reply_to'];
557 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
559 // only expose our real email address to true friends
561 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
563 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
564 $headers .= 'Sender: ' . $local_user['email'] . "\n";
566 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
569 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
570 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
573 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
575 if ($target_item['uri'] !== $target_item['parent-uri']) {
576 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
578 // Export more references on deeper nested threads
579 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
580 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
585 if (empty($target_item['title'])) {
586 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
587 $title = Model\Item::selectFirst(['title'], $condition);
589 if (DBA::isResult($title) && ($title['title'] != '')) {
590 $subject = $title['title'];
592 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
593 $title = Model\Item::selectFirst(['title'], $condition);
595 if (DBA::isResult($title) && ($title['title'] != '')) {
596 $subject = $title['title'];
601 if (strncasecmp($subject, 'RE:', 3)) {
602 $subject = 'Re: ' . $subject;
606 Email::send($addr, $subject, $headers, $target_item);
608 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
610 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);