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\Model\Item;
39 use Friendica\Protocol\Relay;
44 const SUGGESTION = 'suggest';
45 const RELOCATION = 'relocate';
46 const DELETION = 'drop';
47 const POST = 'wall-new';
49 const UPLINK = 'uplink';
50 const REMOVAL = 'removeme';
51 const PROFILEUPDATE = 'profileupdate';
53 public static function execute($cmd, $target_id, $contact_id)
55 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
59 $public_message = false;
62 if ($cmd == self::MAIL) {
63 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
64 if (!DBA::isResult($target_item)) {
67 $uid = $target_item['uid'];
68 } elseif ($cmd == self::SUGGESTION) {
69 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
70 if (!DBA::isResult($target_item)) {
73 $uid = $target_item['uid'];
74 } elseif ($cmd == self::RELOCATION) {
78 $item = Model\Post::selectFirst(['parent'], ['id' => $target_id]);
79 if (!DBA::isResult($item) || empty($item['parent'])) {
82 $parent_id = intval($item['parent']);
84 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
85 $params = ['order' => ['id']];
86 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
88 while ($item = Model\Post::fetch($itemdata)) {
89 if ($item['verb'] == Activity::ANNOUNCE) {
93 if ($item['id'] == $parent_id) {
96 if ($item['id'] == $target_id) {
101 DBA::close($itemdata);
103 if (empty($target_item)) {
104 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
108 if (empty($parent)) {
109 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
110 self::setFailedQueue($cmd, $target_item);
114 if (!empty($target_item['contact-uid'])) {
115 $uid = $target_item['contact-uid'];
116 } elseif (!empty($target_item['uid'])) {
117 $uid = $target_item['uid'];
119 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
120 self::setFailedQueue($cmd, $target_item);
124 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
125 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
126 if (!DBA::isResult($thr_parent)) {
127 // Shouldn't happen. But when this does, we just take the parent as thread parent.
128 // That's totally okay for what we use this variable here.
129 $thr_parent = $parent;
132 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
133 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
134 self::setFailedQueue($cmd, $target_item);
138 // avoid race condition with deleting entries
139 if ($items[0]['deleted']) {
140 foreach ($items as $item) {
141 $item['deleted'] = 1;
145 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
147 // This is IMPORTANT!!!!
149 // We will only send a "notify owner to relay" or followup message if the referenced post
150 // originated on our system by virtue of having our hostname somewhere
151 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
152 // if $parent['wall'] == 1 we will already have the parent message in our array
153 // and we will relay the whole lot.
155 $localhost = DI::baseUrl()->getHostname();
156 if (strpos($localhost, ':')) {
157 $localhost = substr($localhost, 0, strpos($localhost, ':'));
161 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
162 * have been known to cause runaway conditions which affected several servers, along with
163 * permissions issues.
167 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
168 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
169 // local followup to remote post
173 if (empty($parent['allow_cid'])
174 && empty($parent['allow_gid'])
175 && empty($parent['deny_cid'])
176 && empty($parent['deny_gid'])
177 && ($parent["private"] != Model\Item::PRIVATE)) {
178 $public_message = true;
183 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
186 $owner = Model\User::getOwnerDataById($uid);
187 if (!DBA::isResult($owner)) {
188 self::setFailedQueue($cmd, $target_item);
192 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
193 $contact = DBA::selectFirst('contact', [],
194 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
196 if (!DBA::isResult($contact)) {
197 self::setFailedQueue($cmd, $target_item);
201 if (Network::isUrlBlocked($contact['url'])) {
202 self::setFailedQueue($cmd, $target_item);
206 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
208 // Transmit via Diaspora if the thread had started as Diaspora post.
209 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
210 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
211 // Also transmit relayed posts from Diaspora contacts via Diaspora.
212 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network'], $target_item['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, $protocol);
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 * @param int $server_protocol The protocol of the server
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $server_protocol)
275 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
276 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
277 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
278 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
282 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
284 if ($cmd == self::MAIL) {
285 $item = $target_item;
286 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
287 $atom = DFRN::mail($item, $owner);
288 } elseif ($cmd == self::SUGGESTION) {
289 $item = $target_item;
290 $atom = DFRN::fsuggest($item, $owner);
291 DBA::delete('fsuggest', ['id' => $item['id']]);
292 } elseif ($cmd == self::RELOCATION) {
293 $atom = DFRN::relocate($owner, $owner['uid']);
294 } elseif ($followup) {
295 $msgitems = [$target_item];
296 $atom = DFRN::entries($msgitems, $owner);
298 if ($target_item['deleted']) {
299 $msgitems = [$target_item];
302 foreach ($items as $item) {
303 // Only add the parent when we don't delete other items.
304 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
305 $item["entry:comment-allow"] = true;
306 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
311 $atom = DFRN::entries($msgitems, $owner);
314 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
316 // perform local delivery if we are on the same site
317 if (Model\Contact::isLocal($contact['url'])) {
318 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
319 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
320 if (!DBA::isResult($target_self)) {
323 $target_uid = $target_self['uid'];
325 // Check if the user has got this contact
326 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
328 // Otherwise there should be a public contact
329 $cid = Model\Contact::getIdForURL($owner['url']);
335 $target_importer = DFRN::getImporter($cid, $target_uid);
336 if (empty($target_importer)) {
337 // This should never happen
341 DFRN::import($atom, $target_importer, Conversation::PARCEL_LOCAL_DFRN, Conversation::PUSH);
343 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
344 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
350 $protocol = Model\Post\DeliveryData::DFRN;
352 // We don't have a relationship with contacts on a public post.
353 // Se we transmit with the new method and via Diaspora as a fallback
354 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
355 // Transmit in public if it's a relay post
356 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
358 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
360 // We never spool failed relay deliveries
362 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
364 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
365 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
366 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
368 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
370 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
376 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
377 // Transmit via Diaspora if not possible via Friendica
378 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
381 } elseif ($cmd != self::RELOCATION) {
382 // DFRN payload over Diaspora transport layer
383 $deliver_status = DFRN::transmit($owner, $contact, $atom);
384 if (($deliver_status < 200) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
386 $deliver_status = DFRN::deliver($owner, $contact, $atom);
387 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
390 $deliver_status = DFRN::deliver($owner, $contact, $atom);
391 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
394 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
396 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
397 // We successfully delivered a message, the contact is alive
398 Model\Contact::unmarkForArchival($contact);
400 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
402 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
403 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
406 // The message could not be delivered. We mark the contact as "dead"
407 Model\Contact::markForArchival($contact);
409 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
410 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
411 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
417 * Deliver content via Diaspora
419 * @param string $cmd Command
420 * @param array $contact Contact record of the receiver
421 * @param array $owner Owner record of the sender
422 * @param array $items Item record of the content and the parent
423 * @param array $target_item Item record of the content
424 * @param boolean $public_message Is the content public?
425 * @param boolean $top_level Is it a thread starter?
426 * @param boolean $followup Is it an answer to a remote post?
427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428 * @throws \ImagickException
430 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
432 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
433 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
435 if ($public_message) {
436 $loc = 'public batch ' . $contact['batch'];
438 $loc = $contact['addr'];
441 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
443 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
447 if ($cmd == self::MAIL) {
448 Diaspora::sendMail($target_item, $owner, $contact);
452 if ($cmd == self::SUGGESTION) {
456 if (!$contact['pubkey'] && !$public_message) {
460 if ($cmd == self::RELOCATION) {
461 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
462 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
463 // top-level retraction
464 Logger::log('diaspora retract: ' . $loc);
465 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
466 } elseif ($followup) {
467 // send comments and likes to owner to relay
468 Logger::log('diaspora followup: ' . $loc);
469 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
470 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
471 // we are the relay - send comments, likes and relayable_retractions to our conversants
472 Logger::log('diaspora relay: ' . $loc);
473 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
474 } elseif ($top_level && !$walltowall) {
475 // currently no workable solution for sending walltowall
476 Logger::log('diaspora status: ' . $loc);
477 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
479 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
483 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
484 // We successfully delivered a message, the contact is alive
485 Model\Contact::unmarkForArchival($contact);
487 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
489 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
490 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
493 // The message could not be delivered. We mark the contact as "dead"
494 Model\Contact::markForArchival($contact);
496 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
497 if ($public_message) {
498 Relay::markForArchival($contact);
501 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
502 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
503 // defer message for redelivery
504 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
505 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
507 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
508 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
514 * Deliver content via mail
516 * @param string $cmd Command
517 * @param array $contact Contact record of the receiver
518 * @param array $owner Owner record of the sender
519 * @param array $target_item Item record of the content
520 * @param array $thr_parent Item record of the direct parent in the thread
521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
522 * @throws \ImagickException
524 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
526 if (DI::config()->get('system','dfrn_only')) {
530 $addr = $contact['addr'];
531 if (!strlen($addr)) {
535 if (!in_array($cmd, [self::POST, self::POKE])) {
539 if ($target_item['verb'] != Activity::POST) {
543 if (!empty($thr_parent['object'])) {
544 $data = json_decode($thr_parent['object'], true);
545 if (!empty($data['reply_to'])) {
546 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
547 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
548 } elseif (!empty($data['from'])) {
549 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
550 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
554 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
555 if (!DBA::isResult($local_user)) {
559 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
562 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
563 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
564 $reply_to = $mailacct['reply_to'];
567 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
569 // only expose our real email address to true friends
571 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
573 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
574 $headers .= 'Sender: ' . $local_user['email'] . "\n";
576 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
579 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
580 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
583 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
585 if ($target_item['uri'] !== $target_item['parent-uri']) {
586 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
588 // Export more references on deeper nested threads
589 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
590 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
595 if (empty($target_item['title'])) {
596 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
597 $title = Model\Post::selectFirst(['title'], $condition);
599 if (DBA::isResult($title) && ($title['title'] != '')) {
600 $subject = $title['title'];
602 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
603 $title = Model\Post::selectFirst(['title'], $condition);
605 if (DBA::isResult($title) && ($title['title'] != '')) {
606 $subject = $title['title'];
611 if (strncasecmp($subject, 'RE:', 3)) {
612 $subject = 'Re: ' . $subject;
616 Email::send($addr, $subject, $headers, $target_item);
618 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
620 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);