3 * @copyright Copyright (C) 2010-2021, the Friendica project
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]);
60 $public_message = false;
63 if ($cmd == self::MAIL) {
64 $target_item = DBA::selectFirst('mail', [], ['id' => $post_uriid]);
65 if (!DBA::isResult($target_item)) {
68 $uid = $target_item['uid'];
69 } elseif ($cmd == self::SUGGESTION) {
70 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $post_uriid]);
71 if (!DBA::isResult($target_item)) {
74 $uid = $target_item['uid'];
75 } elseif ($cmd == self::RELOCATION) {
79 $item = Model\Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
80 if (!DBA::isResult($item) || empty($item['parent'])) {
81 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
84 $target_id = intval($item['id']);
85 $parent_id = intval($item['parent']);
87 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
88 $params = ['order' => ['id']];
89 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
91 while ($item = Model\Post::fetch($itemdata)) {
92 if ($item['verb'] == Activity::ANNOUNCE) {
96 if ($item['id'] == $parent_id) {
99 if ($item['id'] == $target_id) {
100 $target_item = $item;
104 DBA::close($itemdata);
106 if (empty($target_item)) {
107 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
111 if (empty($parent)) {
112 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
113 self::setFailedQueue($cmd, $target_item);
117 if (!empty($target_item['contact-uid'])) {
118 $uid = $target_item['contact-uid'];
119 } elseif (!empty($target_item['uid'])) {
120 $uid = $target_item['uid'];
122 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
123 self::setFailedQueue($cmd, $target_item);
127 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
128 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
129 if (!DBA::isResult($thr_parent)) {
130 // Shouldn't happen. But when this does, we just take the parent as thread parent.
131 // That's totally okay for what we use this variable here.
132 $thr_parent = $parent;
135 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
136 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
137 self::setFailedQueue($cmd, $target_item);
141 // avoid race condition with deleting entries
142 if ($items[0]['deleted']) {
143 foreach ($items as $item) {
144 $item['deleted'] = 1;
148 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
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::notice('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $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, archived or pending contacts, and not to ourselves either
196 $contact = DBA::selectFirst('contact', [],
197 ['id' => $contact_id, 'archive' => false, '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 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
211 // Transmit via Diaspora if the thread had started as Diaspora post.
212 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
213 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
214 // Also transmit relayed posts from Diaspora contacts via Diaspora.
215 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network'], $target_item['network']])) {
216 $contact['network'] = Protocol::DIASPORA;
219 // Ensure that local contacts are delivered locally
220 if (Model\Contact::isLocal($contact['url'])) {
221 $contact['network'] = Protocol::DFRN;
224 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
226 switch ($contact['network']) {
228 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
231 case Protocol::DIASPORA:
232 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
236 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
247 * Increased the "failed" counter in the item delivery data
249 * @param string $cmd Command
250 * @param array $item Item array
252 private static function setFailedQueue(string $cmd, array $item)
254 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
258 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
262 * Deliver content via DFRN
264 * @param string $cmd Command
265 * @param array $contact Contact record of the receiver
266 * @param array $owner Owner record of the sender
267 * @param array $items Item record of the content and the parent
268 * @param array $target_item Item record of the content
269 * @param boolean $public_message Is the content public?
270 * @param boolean $top_level Is it a thread starter?
271 * @param boolean $followup Is it an answer to a remote post?
272 * @param int $server_protocol The protocol of the server
273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274 * @throws \ImagickException
276 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $server_protocol)
278 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
279 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
280 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
281 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
285 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
287 if ($cmd == self::MAIL) {
288 $item = $target_item;
289 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
290 $atom = DFRN::mail($item, $owner);
291 } elseif ($cmd == self::SUGGESTION) {
292 $item = $target_item;
293 $atom = DFRN::fsuggest($item, $owner);
294 DBA::delete('fsuggest', ['id' => $item['id']]);
295 } elseif ($cmd == self::RELOCATION) {
296 $atom = DFRN::relocate($owner, $owner['uid']);
297 } elseif ($followup) {
298 $msgitems = [$target_item];
299 $atom = DFRN::entries($msgitems, $owner);
301 if ($target_item['deleted']) {
302 $msgitems = [$target_item];
305 foreach ($items as $item) {
306 // Only add the parent when we don't delete other items.
307 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
308 $item["entry:comment-allow"] = true;
309 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
314 $atom = DFRN::entries($msgitems, $owner);
317 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
319 // perform local delivery if we are on the same site
320 if (Model\Contact::isLocal($contact['url'])) {
321 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
322 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
323 if (!DBA::isResult($target_self)) {
326 $target_uid = $target_self['uid'];
328 // Check if the user has got this contact
329 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
331 // Otherwise there should be a public contact
332 $cid = Model\Contact::getIdForURL($owner['url']);
338 $target_importer = DFRN::getImporter($cid, $target_uid);
339 if (empty($target_importer)) {
340 // This should never happen
344 DFRN::import($atom, $target_importer, Conversation::PARCEL_LOCAL_DFRN, Conversation::PUSH);
346 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
347 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
353 $protocol = Model\Post\DeliveryData::DFRN;
355 // We don't have a relationship with contacts on a public post.
356 // Se we transmit with the new method and via Diaspora as a fallback
357 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
358 // Transmit in public if it's a relay post
359 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
361 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
363 // We never spool failed relay deliveries
365 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
367 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
368 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
369 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
371 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
373 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
379 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
380 // Transmit via Diaspora if not possible via Friendica
381 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
384 } elseif ($cmd != self::RELOCATION) {
385 // DFRN payload over Diaspora transport layer
386 $deliver_status = DFRN::transmit($owner, $contact, $atom);
387 if (($deliver_status < 200) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
389 $deliver_status = DFRN::deliver($owner, $contact, $atom);
390 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
393 $deliver_status = DFRN::deliver($owner, $contact, $atom);
394 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
397 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
399 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
400 // We successfully delivered a message, the contact is alive
401 Model\Contact::unmarkForArchival($contact);
403 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
405 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
406 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
409 // The message could not be delivered. We mark the contact as "dead"
410 Model\Contact::markForArchival($contact);
412 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
413 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
414 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
420 * Deliver content via Diaspora
422 * @param string $cmd Command
423 * @param array $contact Contact record of the receiver
424 * @param array $owner Owner record of the sender
425 * @param array $items Item record of the content and the parent
426 * @param array $target_item Item record of the content
427 * @param boolean $public_message Is the content public?
428 * @param boolean $top_level Is it a thread starter?
429 * @param boolean $followup Is it an answer to a remote post?
430 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
431 * @throws \ImagickException
433 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
435 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
436 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
438 if ($public_message) {
439 $loc = 'public batch ' . $contact['batch'];
441 $loc = $contact['addr'];
444 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
446 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
450 if ($cmd == self::MAIL) {
451 Diaspora::sendMail($target_item, $owner, $contact);
455 if ($cmd == self::SUGGESTION) {
459 if (!$contact['pubkey'] && !$public_message) {
463 if ($cmd == self::RELOCATION) {
464 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
465 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
466 // top-level retraction
467 Logger::log('diaspora retract: ' . $loc);
468 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
469 } elseif ($followup) {
470 // send comments and likes to owner to relay
471 Logger::log('diaspora followup: ' . $loc);
472 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
473 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
474 // we are the relay - send comments, likes and relayable_retractions to our conversants
475 Logger::log('diaspora relay: ' . $loc);
476 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
477 } elseif ($top_level && !$walltowall) {
478 // currently no workable solution for sending walltowall
479 Logger::log('diaspora status: ' . $loc);
480 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
482 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
486 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
487 // We successfully delivered a message, the contact is alive
488 Model\Contact::unmarkForArchival($contact);
490 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
492 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
493 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
496 // The message could not be delivered. We mark the contact as "dead"
497 Model\Contact::markForArchival($contact);
499 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
500 if ($public_message) {
501 Relay::markForArchival($contact);
504 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
505 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
506 // defer message for redelivery
507 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
508 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
510 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
511 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
517 * Deliver content via mail
519 * @param string $cmd Command
520 * @param array $contact Contact record of the receiver
521 * @param array $owner Owner record of the sender
522 * @param array $target_item Item record of the content
523 * @param array $thr_parent Item record of the direct parent in the thread
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 * @throws \ImagickException
527 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
529 if (DI::config()->get('system','dfrn_only')) {
533 $addr = $contact['addr'];
534 if (!strlen($addr)) {
538 if (!in_array($cmd, [self::POST, self::POKE])) {
542 if ($target_item['verb'] != Activity::POST) {
546 if (!empty($thr_parent['object'])) {
547 $data = json_decode($thr_parent['object'], true);
548 if (!empty($data['reply_to'])) {
549 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
550 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
551 } elseif (!empty($data['from'])) {
552 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
553 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
557 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
558 if (!DBA::isResult($local_user)) {
562 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
565 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
566 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
567 $reply_to = $mailacct['reply_to'];
570 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
572 // only expose our real email address to true friends
574 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
576 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
577 $headers .= 'Sender: ' . $local_user['email'] . "\n";
579 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
582 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
583 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
586 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
588 if ($target_item['uri'] !== $target_item['parent-uri']) {
589 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
591 // Export more references on deeper nested threads
592 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
593 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
598 if (empty($target_item['title'])) {
599 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
600 $title = Model\Post::selectFirst(['title'], $condition);
602 if (DBA::isResult($title) && ($title['title'] != '')) {
603 $subject = $title['title'];
605 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
606 $title = Model\Post::selectFirst(['title'], $condition);
608 if (DBA::isResult($title) && ($title['title'] != '')) {
609 $subject = $title['title'];
614 if (strncasecmp($subject, 'RE:', 3)) {
615 $subject = 'Re: ' . $subject;
619 Email::send($addr, $subject, $headers, $target_item);
621 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
623 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);