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 // When commenting too fast after delivery, a post wasn't recognized as top level post.
145 // The count then showed more than one entry. The additional check should help.
146 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
147 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
148 Logger::log('Top level post');
152 // This is IMPORTANT!!!!
154 // We will only send a "notify owner to relay" or followup message if the referenced post
155 // originated on our system by virtue of having our hostname somewhere
156 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
157 // if $parent['wall'] == 1 we will already have the parent message in our array
158 // and we will relay the whole lot.
160 $localhost = DI::baseUrl()->getHostname();
161 if (strpos($localhost, ':')) {
162 $localhost = substr($localhost, 0, strpos($localhost, ':'));
166 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
167 * have been known to cause runaway conditions which affected several servers, along with
168 * permissions issues.
172 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
173 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
174 // local followup to remote post
178 if (empty($parent['allow_cid'])
179 && empty($parent['allow_gid'])
180 && empty($parent['deny_cid'])
181 && empty($parent['deny_gid'])
182 && ($parent["private"] != Model\Item::PRIVATE)) {
183 $public_message = true;
188 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
191 $owner = Model\User::getOwnerDataById($uid);
192 if (!DBA::isResult($owner)) {
193 self::setFailedQueue($cmd, $target_item);
197 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
198 $contact = DBA::selectFirst('contact', [],
199 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
201 if (!DBA::isResult($contact)) {
202 self::setFailedQueue($cmd, $target_item);
206 if (Network::isUrlBlocked($contact['url'])) {
207 self::setFailedQueue($cmd, $target_item);
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 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
215 $contact['network'] = Protocol::DIASPORA;
218 // Ensure that local contacts are delivered locally
219 if (Model\Contact::isLocal($contact['url'])) {
220 $contact['network'] = Protocol::DFRN;
223 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
225 switch ($contact['network']) {
227 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
230 case Protocol::DIASPORA:
231 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
235 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
246 * Increased the "failed" counter in the item delivery data
248 * @param string $cmd Command
249 * @param array $item Item array
251 private static function setFailedQueue(string $cmd, array $item)
253 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
257 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
261 * Deliver content via DFRN
263 * @param string $cmd Command
264 * @param array $contact Contact record of the receiver
265 * @param array $owner Owner record of the sender
266 * @param array $items Item record of the content and the parent
267 * @param array $target_item Item record of the content
268 * @param boolean $public_message Is the content public?
269 * @param boolean $top_level Is it a thread starter?
270 * @param boolean $followup Is it an answer to a remote post?
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 * @throws \ImagickException
274 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
276 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
277 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
278 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
279 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
283 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
285 if ($cmd == self::MAIL) {
286 $item = $target_item;
287 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
288 $atom = DFRN::mail($item, $owner);
289 } elseif ($cmd == self::SUGGESTION) {
290 $item = $target_item;
291 $atom = DFRN::fsuggest($item, $owner);
292 DBA::delete('fsuggest', ['id' => $item['id']]);
293 } elseif ($cmd == self::RELOCATION) {
294 $atom = DFRN::relocate($owner, $owner['uid']);
295 } elseif ($followup) {
296 $msgitems = [$target_item];
297 $atom = DFRN::entries($msgitems, $owner);
299 if ($target_item['deleted']) {
300 $msgitems = [$target_item];
303 foreach ($items as $item) {
304 // Only add the parent when we don't delete other items.
305 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
306 $item["entry:comment-allow"] = true;
307 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
312 $atom = DFRN::entries($msgitems, $owner);
315 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
317 // perform local delivery if we are on the same site
318 if (Model\Contact::isLocal($contact['url'])) {
319 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
320 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
321 if (!DBA::isResult($target_self)) {
324 $target_uid = $target_self['uid'];
326 // Check if the user has got this contact
327 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
329 // Otherwise there should be a public contact
330 $cid = Model\Contact::getIdForURL($owner['url']);
336 $target_importer = DFRN::getImporter($cid, $target_uid);
337 if (empty($target_importer)) {
338 // This should never happen
342 DFRN::import($atom, $target_importer, false, Conversation::PARCEL_LOCAL_DFRN);
344 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
345 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
351 $protocol = Model\Post\DeliveryData::DFRN;
353 // We don't have a relationship with contacts on a public post.
354 // Se we transmit with the new method and via Diaspora as a fallback
355 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
356 // Transmit in public if it's a relay post
357 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
359 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
361 // We never spool failed relay deliveries
363 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
365 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
366 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
367 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
369 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
375 if (($deliver_status < 200) || ($deliver_status > 299)) {
376 // Transmit via Diaspora if not possible via Friendica
377 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
380 } elseif ($cmd != self::RELOCATION) {
381 // DFRN payload over Diaspora transport layer
382 $deliver_status = DFRN::transmit($owner, $contact, $atom);
383 if ($deliver_status < 200) {
385 $deliver_status = DFRN::deliver($owner, $contact, $atom);
386 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
389 $deliver_status = DFRN::deliver($owner, $contact, $atom);
390 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
393 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
395 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
396 // We successfully delivered a message, the contact is alive
397 Model\Contact::unmarkForArchival($contact);
399 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
400 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
403 // The message could not be delivered. We mark the contact as "dead"
404 Model\Contact::markForArchival($contact);
406 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
407 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
408 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
414 * Deliver content via Diaspora
416 * @param string $cmd Command
417 * @param array $contact Contact record of the receiver
418 * @param array $owner Owner record of the sender
419 * @param array $items Item record of the content and the parent
420 * @param array $target_item Item record of the content
421 * @param boolean $public_message Is the content public?
422 * @param boolean $top_level Is it a thread starter?
423 * @param boolean $followup Is it an answer to a remote post?
424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 * @throws \ImagickException
427 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
429 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
430 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
432 if ($public_message) {
433 $loc = 'public batch ' . $contact['batch'];
435 $loc = $contact['addr'];
438 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
440 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
444 if ($cmd == self::MAIL) {
445 Diaspora::sendMail($target_item, $owner, $contact);
449 if ($cmd == self::SUGGESTION) {
453 if (!$contact['pubkey'] && !$public_message) {
457 if ($cmd == self::RELOCATION) {
458 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
459 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
460 // top-level retraction
461 Logger::log('diaspora retract: ' . $loc);
462 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
463 } elseif ($followup) {
464 // send comments and likes to owner to relay
465 Logger::log('diaspora followup: ' . $loc);
466 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
467 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
468 // we are the relay - send comments, likes and relayable_retractions to our conversants
469 Logger::log('diaspora relay: ' . $loc);
470 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
471 } elseif ($top_level && !$walltowall) {
472 // currently no workable solution for sending walltowall
473 Logger::log('diaspora status: ' . $loc);
474 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
476 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
480 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
481 // We successfully delivered a message, the contact is alive
482 Model\Contact::unmarkForArchival($contact);
484 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
485 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
488 // The message could not be delivered. We mark the contact as "dead"
489 Model\Contact::markForArchival($contact);
491 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
492 if ($public_message) {
493 Relay::markForArchival($contact);
496 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
497 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
498 // defer message for redelivery
499 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
500 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
502 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
503 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
509 * Deliver content via mail
511 * @param string $cmd Command
512 * @param array $contact Contact record of the receiver
513 * @param array $owner Owner record of the sender
514 * @param array $target_item Item record of the content
515 * @param array $thr_parent Item record of the direct parent in the thread
516 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517 * @throws \ImagickException
519 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
521 if (DI::config()->get('system','dfrn_only')) {
525 $addr = $contact['addr'];
526 if (!strlen($addr)) {
530 if (!in_array($cmd, [self::POST, self::POKE])) {
534 if ($target_item['verb'] != Activity::POST) {
538 if (!empty($thr_parent['object'])) {
539 $data = json_decode($thr_parent['object'], true);
540 if (!empty($data['reply_to'])) {
541 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
542 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
543 } elseif (!empty($data['from'])) {
544 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
545 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
549 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
550 if (!DBA::isResult($local_user)) {
554 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
557 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
558 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
559 $reply_to = $mailacct['reply_to'];
562 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
564 // only expose our real email address to true friends
566 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
568 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
569 $headers .= 'Sender: ' . $local_user['email'] . "\n";
571 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
574 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
575 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
578 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
580 if ($target_item['uri'] !== $target_item['parent-uri']) {
581 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
583 // Export more references on deeper nested threads
584 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
585 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
590 if (empty($target_item['title'])) {
591 $condition = ['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'];
597 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
598 $title = Model\Item::selectFirst(['title'], $condition);
600 if (DBA::isResult($title) && ($title['title'] != '')) {
601 $subject = $title['title'];
606 if (strncasecmp($subject, 'RE:', 3)) {
607 $subject = 'Re: ' . $subject;
611 Email::send($addr, $subject, $headers, $target_item);
613 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
615 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);