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;
40 const SUGGESTION = 'suggest';
41 const RELOCATION = 'relocate';
42 const DELETION = 'drop';
43 const POST = 'wall-new';
45 const UPLINK = 'uplink';
46 const REMOVAL = 'removeme';
47 const PROFILEUPDATE = 'profileupdate';
49 public static function execute($cmd, $target_id, $contact_id)
51 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
55 $public_message = false;
58 if ($cmd == self::MAIL) {
59 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
60 if (!DBA::isResult($target_item)) {
63 $uid = $target_item['uid'];
64 } elseif ($cmd == self::SUGGESTION) {
65 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
66 if (!DBA::isResult($target_item)) {
69 $uid = $target_item['uid'];
70 } elseif ($cmd == self::RELOCATION) {
74 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
75 if (!DBA::isResult($item) || empty($item['parent'])) {
78 $parent_id = intval($item['parent']);
80 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
81 $params = ['order' => ['id']];
82 $itemdata = Model\Item::select([], $condition, $params);
84 while ($item = Model\Item::fetch($itemdata)) {
85 if ($item['id'] == $parent_id) {
88 if ($item['id'] == $target_id) {
93 DBA::close($itemdata);
95 if (empty($target_item)) {
96 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
100 if (empty($parent)) {
101 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
102 self::setFailedQueue($cmd, $target_item);
106 if (!empty($target_item['contact-uid'])) {
107 $uid = $target_item['contact-uid'];
108 } elseif (!empty($target_item['uid'])) {
109 $uid = $target_item['uid'];
111 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
112 self::setFailedQueue($cmd, $target_item);
116 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
117 $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
118 if (!DBA::isResult($thr_parent)) {
119 // Shouldn't happen. But when this does, we just take the parent as thread parent.
120 // That's totally okay for what we use this variable here.
121 $thr_parent = $parent;
124 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
125 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
126 self::setFailedQueue($cmd, $target_item);
130 // avoid race condition with deleting entries
131 if ($items[0]['deleted']) {
132 foreach ($items as $item) {
133 $item['deleted'] = 1;
137 // When commenting too fast after delivery, a post wasn't recognized as top level post.
138 // The count then showed more than one entry. The additional check should help.
139 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
140 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
141 Logger::log('Top level post');
145 // This is IMPORTANT!!!!
147 // We will only send a "notify owner to relay" or followup message if the referenced post
148 // originated on our system by virtue of having our hostname somewhere
149 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
150 // if $parent['wall'] == 1 we will already have the parent message in our array
151 // and we will relay the whole lot.
153 $localhost = DI::baseUrl()->getHostname();
154 if (strpos($localhost, ':')) {
155 $localhost = substr($localhost, 0, strpos($localhost, ':'));
159 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
160 * have been known to cause runaway conditions which affected several servers, along with
161 * permissions issues.
165 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
166 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
167 // local followup to remote post
171 if (empty($parent['allow_cid'])
172 && empty($parent['allow_gid'])
173 && empty($parent['deny_cid'])
174 && empty($parent['deny_gid'])
175 && ($parent["private"] != Model\Item::PRIVATE)) {
176 $public_message = true;
181 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
184 $owner = Model\User::getOwnerDataById($uid);
185 if (!DBA::isResult($owner)) {
186 self::setFailedQueue($cmd, $target_item);
190 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
191 $contact = DBA::selectFirst('contact', [],
192 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
194 if (!DBA::isResult($contact)) {
195 self::setFailedQueue($cmd, $target_item);
199 if (Network::isUrlBlocked($contact['url'])) {
200 self::setFailedQueue($cmd, $target_item);
204 // Transmit via Diaspora if the thread had started as Diaspora post.
205 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
206 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
207 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
208 $contact['network'] = Protocol::DIASPORA;
211 // Ensure that local contacts are delivered locally
212 if (Model\Contact::isLocal($contact['url'])) {
213 $contact['network'] = Protocol::DFRN;
216 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
218 switch ($contact['network']) {
220 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
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
244 private static function setFailedQueue(string $cmd, array $item)
246 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
250 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
254 * Deliver content via DFRN
256 * @param string $cmd Command
257 * @param array $contact Contact record of the receiver
258 * @param array $owner Owner record of the sender
259 * @param array $items Item record of the content and the parent
260 * @param array $target_item Item record of the content
261 * @param boolean $public_message Is the content public?
262 * @param boolean $top_level Is it a thread starter?
263 * @param boolean $followup Is it an answer to a remote post?
264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
265 * @throws \ImagickException
267 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
269 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
270 if (Diaspora::isReshare($target_item['body']) && !empty(Diaspora::personByHandle($contact['addr'], false))) {
271 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
272 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
276 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
278 if ($cmd == self::MAIL) {
279 $item = $target_item;
280 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
281 $atom = DFRN::mail($item, $owner);
282 } elseif ($cmd == self::SUGGESTION) {
283 $item = $target_item;
284 $atom = DFRN::fsuggest($item, $owner);
285 DBA::delete('fsuggest', ['id' => $item['id']]);
286 } elseif ($cmd == self::RELOCATION) {
287 $atom = DFRN::relocate($owner, $owner['uid']);
288 } elseif ($followup) {
289 $msgitems = [$target_item];
290 $atom = DFRN::entries($msgitems, $owner);
293 foreach ($items as $item) {
294 // Only add the parent when we don't delete other items.
295 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
296 $item["entry:comment-allow"] = true;
297 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
301 $atom = DFRN::entries($msgitems, $owner);
304 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
306 // perform local delivery if we are on the same site
307 if (Model\Contact::isLocal($contact['url'])) {
308 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
309 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
310 if (!DBA::isResult($target_self)) {
313 $target_uid = $target_self['uid'];
315 // Check if the user has got this contact
316 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
318 // Otherwise there should be a public contact
319 $cid = Model\Contact::getIdForURL($owner['url']);
325 $target_importer = DFRN::getImporter($cid, $target_uid);
326 if (empty($target_importer)) {
327 // This should never happen
331 DFRN::import($atom, $target_importer);
333 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
334 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
340 $protocol = Model\Post\DeliveryData::DFRN;
342 // We don't have a relationship with contacts on a public post.
343 // Se we transmit with the new method and via Diaspora as a fallback
344 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
345 // Transmit in public if it's a relay post
346 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
348 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
350 // We never spool failed relay deliveries
352 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
354 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
355 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
356 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
358 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
364 if (($deliver_status < 200) || ($deliver_status > 299)) {
365 // Transmit via Diaspora if not possible via Friendica
366 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
369 } elseif ($cmd != self::RELOCATION) {
370 // DFRN payload over Diaspora transport layer
371 $deliver_status = DFRN::transmit($owner, $contact, $atom);
372 if ($deliver_status < 200) {
374 $deliver_status = DFRN::deliver($owner, $contact, $atom);
375 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
378 $deliver_status = DFRN::deliver($owner, $contact, $atom);
379 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
382 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
384 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
385 // We successfully delivered a message, the contact is alive
386 Model\Contact::unmarkForArchival($contact);
388 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
389 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
392 // The message could not be delivered. We mark the contact as "dead"
393 Model\Contact::markForArchival($contact);
395 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
396 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
397 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
403 * Deliver content via Diaspora
405 * @param string $cmd Command
406 * @param array $contact Contact record of the receiver
407 * @param array $owner Owner record of the sender
408 * @param array $items Item record of the content and the parent
409 * @param array $target_item Item record of the content
410 * @param boolean $public_message Is the content public?
411 * @param boolean $top_level Is it a thread starter?
412 * @param boolean $followup Is it an answer to a remote post?
413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
414 * @throws \ImagickException
416 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
418 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
419 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
421 if ($public_message) {
422 $loc = 'public batch ' . $contact['batch'];
424 $loc = $contact['addr'];
427 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
429 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
433 if ($cmd == self::MAIL) {
434 Diaspora::sendMail($target_item, $owner, $contact);
438 if ($cmd == self::SUGGESTION) {
442 if (!$contact['pubkey'] && !$public_message) {
446 if ($cmd == self::RELOCATION) {
447 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
448 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
449 // top-level retraction
450 Logger::log('diaspora retract: ' . $loc);
451 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
452 } elseif ($followup) {
453 // send comments and likes to owner to relay
454 Logger::log('diaspora followup: ' . $loc);
455 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
456 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
457 // we are the relay - send comments, likes and relayable_retractions to our conversants
458 Logger::log('diaspora relay: ' . $loc);
459 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
460 } elseif ($top_level && !$walltowall) {
461 // currently no workable solution for sending walltowall
462 Logger::log('diaspora status: ' . $loc);
463 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
465 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
469 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
470 // We successfully delivered a message, the contact is alive
471 Model\Contact::unmarkForArchival($contact);
473 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
474 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
477 // The message could not be delivered. We mark the contact as "dead"
478 Model\Contact::markForArchival($contact);
480 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
481 if ($public_message) {
482 Diaspora::markRelayForArchival($contact);
485 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
486 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
487 // defer message for redelivery
488 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
489 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
491 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
492 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
498 * Deliver content via mail
500 * @param string $cmd Command
501 * @param array $contact Contact record of the receiver
502 * @param array $owner Owner record of the sender
503 * @param array $target_item Item record of the content
504 * @param array $thr_parent Item record of the direct parent in the thread
505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 * @throws \ImagickException
508 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
510 if (DI::config()->get('system','dfrn_only')) {
514 $addr = $contact['addr'];
515 if (!strlen($addr)) {
519 if (!in_array($cmd, [self::POST, self::POKE])) {
523 if ($target_item['verb'] != Activity::POST) {
527 if (!empty($thr_parent['object'])) {
528 $data = json_decode($thr_parent['object'], true);
529 if (!empty($data['reply_to'])) {
530 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
531 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
532 } elseif (!empty($data['from'])) {
533 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
534 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
538 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
539 if (!DBA::isResult($local_user)) {
543 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
546 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
547 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
548 $reply_to = $mailacct['reply_to'];
551 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
553 // only expose our real email address to true friends
555 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
557 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
558 $headers .= 'Sender: ' . $local_user['email'] . "\n";
560 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
563 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
564 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
567 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
569 if ($target_item['uri'] !== $target_item['parent-uri']) {
570 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
572 // Export more references on deeper nested threads
573 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
574 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
579 if (empty($target_item['title'])) {
580 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
581 $title = Model\Item::selectFirst(['title'], $condition);
583 if (DBA::isResult($title) && ($title['title'] != '')) {
584 $subject = $title['title'];
586 $condition = ['parent-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'];
595 if (strncasecmp($subject, 'RE:', 3)) {
596 $subject = 'Re: ' . $subject;
600 Email::send($addr, $subject, $headers, $target_item);
602 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
604 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);