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);
300 foreach ($items as $item) {
301 // Only add the parent when we don't delete other items.
302 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
303 $item["entry:comment-allow"] = true;
304 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
308 $atom = DFRN::entries($msgitems, $owner);
311 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
313 // perform local delivery if we are on the same site
314 if (Model\Contact::isLocal($contact['url'])) {
315 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
316 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
317 if (!DBA::isResult($target_self)) {
320 $target_uid = $target_self['uid'];
322 // Check if the user has got this contact
323 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
325 // Otherwise there should be a public contact
326 $cid = Model\Contact::getIdForURL($owner['url']);
332 $target_importer = DFRN::getImporter($cid, $target_uid);
333 if (empty($target_importer)) {
334 // This should never happen
338 DFRN::import($atom, $target_importer, false, Conversation::PARCEL_LOCAL_DFRN);
340 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
341 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
347 $protocol = Model\Post\DeliveryData::DFRN;
349 // We don't have a relationship with contacts on a public post.
350 // Se we transmit with the new method and via Diaspora as a fallback
351 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
352 // Transmit in public if it's a relay post
353 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
355 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
357 // We never spool failed relay deliveries
359 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
361 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
362 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
363 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
365 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
371 if (($deliver_status < 200) || ($deliver_status > 299)) {
372 // Transmit via Diaspora if not possible via Friendica
373 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
376 } elseif ($cmd != self::RELOCATION) {
377 // DFRN payload over Diaspora transport layer
378 $deliver_status = DFRN::transmit($owner, $contact, $atom);
379 if ($deliver_status < 200) {
381 $deliver_status = DFRN::deliver($owner, $contact, $atom);
382 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
385 $deliver_status = DFRN::deliver($owner, $contact, $atom);
386 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
389 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
391 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
392 // We successfully delivered a message, the contact is alive
393 Model\Contact::unmarkForArchival($contact);
395 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
396 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
399 // The message could not be delivered. We mark the contact as "dead"
400 Model\Contact::markForArchival($contact);
402 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
403 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
404 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
410 * Deliver content via Diaspora
412 * @param string $cmd Command
413 * @param array $contact Contact record of the receiver
414 * @param array $owner Owner record of the sender
415 * @param array $items Item record of the content and the parent
416 * @param array $target_item Item record of the content
417 * @param boolean $public_message Is the content public?
418 * @param boolean $top_level Is it a thread starter?
419 * @param boolean $followup Is it an answer to a remote post?
420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
421 * @throws \ImagickException
423 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
425 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
426 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
428 if ($public_message) {
429 $loc = 'public batch ' . $contact['batch'];
431 $loc = $contact['addr'];
434 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
436 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
440 if ($cmd == self::MAIL) {
441 Diaspora::sendMail($target_item, $owner, $contact);
445 if ($cmd == self::SUGGESTION) {
449 if (!$contact['pubkey'] && !$public_message) {
453 if ($cmd == self::RELOCATION) {
454 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
455 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
456 // top-level retraction
457 Logger::log('diaspora retract: ' . $loc);
458 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
459 } elseif ($followup) {
460 // send comments and likes to owner to relay
461 Logger::log('diaspora followup: ' . $loc);
462 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
463 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
464 // we are the relay - send comments, likes and relayable_retractions to our conversants
465 Logger::log('diaspora relay: ' . $loc);
466 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
467 } elseif ($top_level && !$walltowall) {
468 // currently no workable solution for sending walltowall
469 Logger::log('diaspora status: ' . $loc);
470 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
472 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
476 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
477 // We successfully delivered a message, the contact is alive
478 Model\Contact::unmarkForArchival($contact);
480 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
481 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
484 // The message could not be delivered. We mark the contact as "dead"
485 Model\Contact::markForArchival($contact);
487 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
488 if ($public_message) {
489 Relay::markForArchival($contact);
492 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
493 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
494 // defer message for redelivery
495 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
496 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
498 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
499 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
505 * Deliver content via mail
507 * @param string $cmd Command
508 * @param array $contact Contact record of the receiver
509 * @param array $owner Owner record of the sender
510 * @param array $target_item Item record of the content
511 * @param array $thr_parent Item record of the direct parent in the thread
512 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
513 * @throws \ImagickException
515 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
517 if (DI::config()->get('system','dfrn_only')) {
521 $addr = $contact['addr'];
522 if (!strlen($addr)) {
526 if (!in_array($cmd, [self::POST, self::POKE])) {
530 if ($target_item['verb'] != Activity::POST) {
534 if (!empty($thr_parent['object'])) {
535 $data = json_decode($thr_parent['object'], true);
536 if (!empty($data['reply_to'])) {
537 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
538 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
539 } elseif (!empty($data['from'])) {
540 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
541 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
545 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
546 if (!DBA::isResult($local_user)) {
550 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
553 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
554 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
555 $reply_to = $mailacct['reply_to'];
558 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
560 // only expose our real email address to true friends
562 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
564 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
565 $headers .= 'Sender: ' . $local_user['email'] . "\n";
567 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
570 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
571 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
574 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
576 if ($target_item['uri'] !== $target_item['parent-uri']) {
577 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
579 // Export more references on deeper nested threads
580 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
581 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
586 if (empty($target_item['title'])) {
587 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
588 $title = Model\Item::selectFirst(['title'], $condition);
590 if (DBA::isResult($title) && ($title['title'] != '')) {
591 $subject = $title['title'];
593 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
594 $title = Model\Item::selectFirst(['title'], $condition);
596 if (DBA::isResult($title) && ($title['title'] != '')) {
597 $subject = $title['title'];
602 if (strncasecmp($subject, 'RE:', 3)) {
603 $subject = 'Re: ' . $subject;
607 Email::send($addr, $subject, $headers, $target_item);
609 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
611 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);