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)) {
61 self::setFailedQueue($cmd, $target_id);
64 $uid = $target_item['uid'];
65 } elseif ($cmd == self::SUGGESTION) {
66 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
67 if (!DBA::isResult($target_item)) {
68 self::setFailedQueue($cmd, $target_id);
71 $uid = $target_item['uid'];
72 } elseif ($cmd == self::RELOCATION) {
76 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
77 if (!DBA::isResult($item) || empty($item['parent'])) {
78 self::setFailedQueue($cmd, $target_id);
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['id'] == $parent_id) {
91 if ($item['id'] == $target_id) {
96 DBA::close($itemdata);
98 if (empty($target_item)) {
99 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
100 self::setFailedQueue($cmd, $target_id);
104 if (empty($parent)) {
105 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
106 self::setFailedQueue($cmd, $target_id);
110 if (!empty($target_item['contact-uid'])) {
111 $uid = $target_item['contact-uid'];
112 } elseif (!empty($target_item['uid'])) {
113 $uid = $target_item['uid'];
115 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
116 self::setFailedQueue($cmd, $target_id);
120 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
121 $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
122 if (!DBA::isResult($thr_parent)) {
123 // Shouldn't happen. But when this does, we just take the parent as thread parent.
124 // That's totally okay for what we use this variable here.
125 $thr_parent = $parent;
128 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
129 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
130 self::setFailedQueue($cmd, $target_id);
134 // avoid race condition with deleting entries
135 if ($items[0]['deleted']) {
136 foreach ($items as $item) {
137 $item['deleted'] = 1;
141 // When commenting too fast after delivery, a post wasn't recognized as top level post.
142 // The count then showed more than one entry. The additional check should help.
143 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
144 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
145 Logger::log('Top level post');
149 // This is IMPORTANT!!!!
151 // We will only send a "notify owner to relay" or followup message if the referenced post
152 // originated on our system by virtue of having our hostname somewhere
153 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
154 // if $parent['wall'] == 1 we will already have the parent message in our array
155 // and we will relay the whole lot.
157 $localhost = DI::baseUrl()->getHostname();
158 if (strpos($localhost, ':')) {
159 $localhost = substr($localhost, 0, strpos($localhost, ':'));
163 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
164 * have been known to cause runaway conditions which affected several servers, along with
165 * permissions issues.
169 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
170 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
171 // local followup to remote post
175 if (empty($parent['allow_cid'])
176 && empty($parent['allow_gid'])
177 && empty($parent['deny_cid'])
178 && empty($parent['deny_gid'])
179 && ($parent["private"] != Model\Item::PRIVATE)) {
180 $public_message = true;
185 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
188 $owner = Model\User::getOwnerDataById($uid);
189 if (!DBA::isResult($owner)) {
190 self::setFailedQueue($cmd, $target_id);
194 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
195 $contact = DBA::selectFirst('contact', [],
196 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
198 if (!DBA::isResult($contact)) {
199 self::setFailedQueue($cmd, $target_id);
203 if (Network::isUrlBlocked($contact['url'])) {
204 self::setFailedQueue($cmd, $target_id);
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 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
212 $contact['network'] = Protocol::DIASPORA;
215 // Ensure that local contacts are delivered locally
216 if (Model\Contact::isLocal($contact['url'])) {
217 $contact['network'] = Protocol::DFRN;
220 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
222 switch ($contact['network']) {
224 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
227 case Protocol::DIASPORA:
228 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
232 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
243 * Increased the "failed" counter in the item delivery data
245 * @param string $cmd Command
246 * @param integer $id Item id
248 private static function setFailedQueue(string $cmd, int $id)
250 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
254 Model\ItemDeliveryData::incrementQueueFailed($id);
258 * Deliver content via DFRN
260 * @param string $cmd Command
261 * @param array $contact Contact record of the receiver
262 * @param array $owner Owner record of the sender
263 * @param array $items Item record of the content and the parent
264 * @param array $target_item Item record of the content
265 * @param boolean $public_message Is the content public?
266 * @param boolean $top_level Is it a thread starter?
267 * @param boolean $followup Is it an answer to a remote post?
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269 * @throws \ImagickException
271 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
273 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
274 if (Diaspora::isReshare($target_item['body']) && !empty(Diaspora::personByHandle($contact['addr'], false))) {
275 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
276 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
280 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
282 if ($cmd == self::MAIL) {
283 $item = $target_item;
284 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
285 $atom = DFRN::mail($item, $owner);
286 } elseif ($cmd == self::SUGGESTION) {
287 $item = $target_item;
288 $atom = DFRN::fsuggest($item, $owner);
289 DBA::delete('fsuggest', ['id' => $item['id']]);
290 } elseif ($cmd == self::RELOCATION) {
291 $atom = DFRN::relocate($owner, $owner['uid']);
292 } elseif ($followup) {
293 $msgitems = [$target_item];
294 $atom = DFRN::entries($msgitems, $owner);
297 foreach ($items as $item) {
298 // Only add the parent when we don't delete other items.
299 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
300 $item["entry:comment-allow"] = true;
301 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
305 $atom = DFRN::entries($msgitems, $owner);
308 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
310 // perform local delivery if we are on the same site
311 if (Model\Contact::isLocal($contact['url'])) {
312 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
313 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
314 if (!DBA::isResult($target_self)) {
317 $target_uid = $target_self['uid'];
319 // Check if the user has got this contact
320 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
322 // Otherwise there should be a public contact
323 $cid = Model\Contact::getIdForURL($owner['url']);
329 $target_importer = DFRN::getImporter($cid, $target_uid);
330 if (empty($target_importer)) {
331 // This should never happen
335 DFRN::import($atom, $target_importer);
337 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
338 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DFRN);
344 $protocol = Model\ItemDeliveryData::DFRN;
346 // We don't have a relationship with contacts on a public post.
347 // Se we transmit with the new method and via Diaspora as a fallback
348 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
349 // Transmit in public if it's a relay post
350 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
352 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
354 // We never spool failed relay deliveries
356 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
358 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
359 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
360 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
362 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
368 if (($deliver_status < 200) || ($deliver_status > 299)) {
369 // Transmit via Diaspora if not possible via Friendica
370 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
373 } elseif ($cmd != self::RELOCATION) {
374 // DFRN payload over Diaspora transport layer
375 $deliver_status = DFRN::transmit($owner, $contact, $atom);
376 if ($deliver_status < 200) {
378 $deliver_status = DFRN::deliver($owner, $contact, $atom);
379 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
382 $deliver_status = DFRN::deliver($owner, $contact, $atom);
383 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
386 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
388 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
389 // We successfully delivered a message, the contact is alive
390 Model\Contact::unmarkForArchival($contact);
392 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
393 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
396 // The message could not be delivered. We mark the contact as "dead"
397 Model\Contact::markForArchival($contact);
399 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
400 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
401 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
407 * Deliver content via Diaspora
409 * @param string $cmd Command
410 * @param array $contact Contact record of the receiver
411 * @param array $owner Owner record of the sender
412 * @param array $items Item record of the content and the parent
413 * @param array $target_item Item record of the content
414 * @param boolean $public_message Is the content public?
415 * @param boolean $top_level Is it a thread starter?
416 * @param boolean $followup Is it an answer to a remote post?
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 * @throws \ImagickException
420 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
422 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
423 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
425 if ($public_message) {
426 $loc = 'public batch ' . $contact['batch'];
428 $loc = $contact['addr'];
431 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
433 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
437 if ($cmd == self::MAIL) {
438 Diaspora::sendMail($target_item, $owner, $contact);
442 if ($cmd == self::SUGGESTION) {
446 if (!$contact['pubkey'] && !$public_message) {
450 if ($cmd == self::RELOCATION) {
451 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
452 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
453 // top-level retraction
454 Logger::log('diaspora retract: ' . $loc);
455 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
456 } elseif ($followup) {
457 // send comments and likes to owner to relay
458 Logger::log('diaspora followup: ' . $loc);
459 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
460 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
461 // we are the relay - send comments, likes and relayable_retractions to our conversants
462 Logger::log('diaspora relay: ' . $loc);
463 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
464 } elseif ($top_level && !$walltowall) {
465 // currently no workable solution for sending walltowall
466 Logger::log('diaspora status: ' . $loc);
467 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
469 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
473 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
474 // We successfully delivered a message, the contact is alive
475 Model\Contact::unmarkForArchival($contact);
477 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
478 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
481 // The message could not be delivered. We mark the contact as "dead"
482 Model\Contact::markForArchival($contact);
484 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
485 if ($public_message) {
486 Diaspora::markRelayForArchival($contact);
489 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
490 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
491 // defer message for redelivery
492 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
493 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
495 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
496 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
502 * Deliver content via mail
504 * @param string $cmd Command
505 * @param array $contact Contact record of the receiver
506 * @param array $owner Owner record of the sender
507 * @param array $target_item Item record of the content
508 * @param array $thr_parent Item record of the direct parent in the thread
509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
510 * @throws \ImagickException
512 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
514 if (DI::config()->get('system','dfrn_only')) {
518 $addr = $contact['addr'];
519 if (!strlen($addr)) {
523 if (!in_array($cmd, [self::POST, self::POKE])) {
527 if ($target_item['verb'] != Activity::POST) {
531 if (!empty($thr_parent['object'])) {
532 $data = json_decode($thr_parent['object'], true);
533 if (!empty($data['reply_to'])) {
534 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
535 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
536 } elseif (!empty($data['from'])) {
537 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
538 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
542 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
543 if (!DBA::isResult($local_user)) {
547 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
550 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
551 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
552 $reply_to = $mailacct['reply_to'];
555 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
557 // only expose our real email address to true friends
559 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
561 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
562 $headers .= 'Sender: ' . $local_user['email'] . "\n";
564 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
567 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
568 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
571 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
573 if ($target_item['uri'] !== $target_item['parent-uri']) {
574 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
576 // Export more references on deeper nested threads
577 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
578 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
583 if (empty($target_item['title'])) {
584 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
585 $title = Model\Item::selectFirst(['title'], $condition);
587 if (DBA::isResult($title) && ($title['title'] != '')) {
588 $subject = $title['title'];
590 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
591 $title = Model\Item::selectFirst(['title'], $condition);
593 if (DBA::isResult($title) && ($title['title'] != '')) {
594 $subject = $title['title'];
599 if (strncasecmp($subject, 'RE:', 3)) {
600 $subject = 'Re: ' . $subject;
604 Email::send($addr, $subject, $headers, $target_item);
606 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::MAIL);
608 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);