3 * @copyright Copyright (C) 2010-2022, 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\Contact\FriendSuggest\Collection\FriendSuggests;
25 use Friendica\Contact\FriendSuggest\Exception\FriendSuggestNotFoundException;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\FContact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\DFRN;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Protocol\Email;
41 use Friendica\Protocol\Relay;
42 use Friendica\Util\Network;
47 const SUGGESTION = 'suggest';
48 const RELOCATION = 'relocate';
49 const DELETION = 'drop';
50 const POST = 'wall-new';
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) {
71 $target_item = DI::fsuggest()->selectOneById($post_uriid)->toArray();
72 } catch (FriendSuggestNotFoundException $e) {
73 DI::logger()->info('Cannot find FriendSuggestion', ['id' => $post_uriid]);
76 $uid = $target_item['uid'];
77 } elseif ($cmd == self::RELOCATION) {
81 $item = Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
82 if (!DBA::isResult($item) || empty($item['parent'])) {
83 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
86 $target_id = intval($item['id']);
87 $parent_id = intval($item['parent']);
89 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
90 $params = ['order' => ['id']];
91 $itemdata = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
93 while ($item = Post::fetch($itemdata)) {
94 if ($item['verb'] == Activity::ANNOUNCE) {
98 if ($item['id'] == $parent_id) {
101 if ($item['id'] == $target_id) {
102 $target_item = $item;
106 DBA::close($itemdata);
108 if (empty($target_item)) {
109 Logger::warning("No target item data. Quitting here.", ['id' => $target_id]);
113 if (empty($parent)) {
114 Logger::warning('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
115 self::setFailedQueue($cmd, $target_item);
119 if (!empty($target_item['contact-uid'])) {
120 $uid = $target_item['contact-uid'];
121 } elseif (!empty($target_item['uid'])) {
122 $uid = $target_item['uid'];
124 Logger::info('Only public users for item ' . $target_id);
125 self::setFailedQueue($cmd, $target_item);
129 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
130 $thr_parent = Post::selectFirst(['network', 'object'], $condition);
131 if (!DBA::isResult($thr_parent)) {
132 // Shouldn't happen. But when this does, we just take the parent as thread parent.
133 // That's totally okay for what we use this variable here.
134 $thr_parent = $parent;
137 if (!empty($contact_id) && Contact::isArchived($contact_id)) {
138 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
139 self::setFailedQueue($cmd, $target_item);
143 // avoid race condition with deleting entries
144 if ($items[0]['deleted']) {
145 foreach ($items as $item) {
146 $item['deleted'] = 1;
150 $top_level = $target_item['gravity'] == Item::GRAVITY_PARENT;
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::info('Followup ' . $target_item["guid"]);
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'] != Item::PRIVATE)) {
183 $public_message = true;
188 Logger::warning('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]);
191 $owner = 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 $protocol = GServer::getProtocol($contact['gsid'] ?? 0);
213 // Transmit via Diaspora if the thread had started as Diaspora post.
214 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
215 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
216 // Also transmit relayed posts from Diaspora contacts via Diaspora.
217 if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network']] ?? '')) {
218 Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]);
219 $contact['network'] = Protocol::DIASPORA;
222 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
224 switch ($contact['network']) {
226 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
229 case Protocol::DIASPORA:
230 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
234 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
245 * Increased the "failed" counter in the item delivery data
247 * @param string $cmd Command
248 * @param array $item Item array
250 private static function setFailedQueue(string $cmd, array $item)
252 if ($cmd != Delivery::POST) {
256 Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
260 * Deliver content via DFRN
262 * @param string $cmd Command
263 * @param array $contact Contact record of the receiver
264 * @param array $owner Owner record of the sender
265 * @param array $items Item record of the content and the parent
266 * @param array $target_item Item record of the content
267 * @param boolean $public_message Is the content public?
268 * @param boolean $top_level Is it a thread starter?
269 * @param boolean $followup Is it an answer to a remote post?
270 * @param int|null $server_protocol The protocol of the server
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 * @throws \ImagickException
274 private static function deliverDFRN(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup, int $server_protocol = null)
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'] = 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 DI::fsuggest()->delete(new FriendSuggests([DI::fsuggest()->selectOneById($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 $protocol = Post\DeliveryData::DFRN;
319 // We don't have a relationship with contacts on a public post.
320 // Se we transmit with the new method and via Diaspora as a fallback
321 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
322 // Transmit in public if it's a relay post
323 $public_dfrn = ($contact['contact-type'] == Contact::TYPE_RELAY);
325 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
327 // We never spool failed relay deliveries
329 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
331 if ($cmd == Delivery::POST) {
332 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
333 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
335 GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
337 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
343 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Post\DeliveryData::LEGACY_DFRN))) {
344 // Transmit via Diaspora if not possible via Friendica
345 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
349 // DFRN payload over Diaspora transport layer
350 $deliver_status = DFRN::transmit($owner, $contact, $atom);
353 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
355 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
356 // We successfully delivered a message, the contact is alive
357 Contact::unmarkForArchival($contact);
359 GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
361 if ($cmd == Delivery::POST) {
362 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
365 // The message could not be delivered. We mark the contact as "dead"
366 Contact::markForArchival($contact);
368 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
369 if (!Worker::defer() && $cmd == Delivery::POST) {
370 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
376 * Deliver content via Diaspora
378 * @param string $cmd Command
379 * @param array $contact Contact record of the receiver
380 * @param array $owner Owner record of the sender
381 * @param array $items Item record of the content and the parent
382 * @param array $target_item Item record of the content
383 * @param boolean $public_message Is the content public?
384 * @param boolean $top_level Is it a thread starter?
385 * @param boolean $followup Is it an answer to a remote post?
386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
387 * @throws \ImagickException
389 private static function deliverDiaspora(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup)
391 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
392 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
394 if ($public_message) {
395 $loc = 'public batch ' . $contact['batch'];
397 $loc = $contact['addr'];
400 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
402 if (!DI::config()->get('system', 'diaspora_enabled')) {
406 if ($cmd == self::MAIL) {
407 Diaspora::sendMail($target_item, $owner, $contact);
411 if ($cmd == self::SUGGESTION) {
415 if (!$contact['pubkey'] && !$public_message) {
419 if ($cmd == self::RELOCATION) {
420 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
421 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
422 // top-level retraction
423 Logger::notice('diaspora retract: ' . $loc);
424 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
425 } elseif ($followup) {
426 // send comments and likes to owner to relay
427 Logger::notice('diaspora followup: ' . $loc);
428 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
429 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
430 // we are the relay - send comments, likes and relayable_retractions to our conversants
431 Logger::notice('diaspora relay: ' . $loc);
432 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
433 } elseif ($top_level && !$walltowall) {
434 // currently no workable solution for sending walltowall
435 Logger::notice('diaspora status: ' . $loc);
436 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
438 Logger::warning('Unknown mode', ['command' => $cmd, 'target' => $loc]);
442 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
443 // We successfully delivered a message, the contact is alive
444 Contact::unmarkForArchival($contact);
446 GServer::setProtocol($contact['gsid'] ?? 0, Post\DeliveryData::DIASPORA);
448 if ($cmd == Delivery::POST) {
449 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::DIASPORA);
452 // The message could not be delivered. We mark the contact as "dead"
453 Contact::markForArchival($contact);
455 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
456 if ($public_message) {
457 Relay::markForArchival($contact);
460 if (empty($contact['contact-type']) || ($contact['contact-type'] != Contact::TYPE_RELAY)) {
461 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
462 // defer message for redelivery
463 if (!Worker::defer() && $cmd == Delivery::POST) {
464 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
466 } elseif ($cmd == Delivery::POST) {
467 Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
473 * Deliver content via mail
475 * @param string $cmd Command
476 * @param array $contact Contact record of the receiver
477 * @param array $owner Owner record of the sender
478 * @param array $target_item Item record of the content
479 * @param array $thr_parent Item record of the direct parent in the thread
481 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482 * @throws \ImagickException
484 private static function deliverMail(string $cmd, array $contact, array $owner, array $target_item, array $thr_parent)
486 if (DI::config()->get('system', 'imap_disabled')) {
490 $addr = $contact['addr'];
491 if (!strlen($addr)) {
495 if ($cmd != self::POST) {
499 if ($target_item['verb'] != Activity::POST) {
503 if (!empty($thr_parent['object'])) {
504 $data = json_decode($thr_parent['object'], true);
505 if (!empty($data['reply_to'])) {
506 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
507 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
508 } elseif (!empty($data['from'])) {
509 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
510 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
514 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
515 if (!DBA::isResult($local_user)) {
519 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
522 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
523 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
524 $reply_to = $mailacct['reply_to'];
527 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
529 // only expose our real email address to true friends
531 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
533 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
534 $headers .= 'Sender: ' . $local_user['email'] . "\n";
536 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
539 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
540 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
543 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
545 if ($target_item['uri'] !== $target_item['parent-uri']) {
546 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
548 // Export more references on deeper nested threads
549 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
550 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
555 if (empty($target_item['title'])) {
556 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
557 $title = Post::selectFirst(['title'], $condition);
559 if (DBA::isResult($title) && ($title['title'] != '')) {
560 $subject = $title['title'];
562 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
563 $title = Post::selectFirst(['title'], $condition);
565 if (DBA::isResult($title) && ($title['title'] != '')) {
566 $subject = $title['title'];
571 if (strncasecmp($subject, 'RE:', 3)) {
572 $subject = 'Re: ' . $subject;
577 $success = Email::send($addr, $subject, $headers, $target_item);
581 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::MAIL);
582 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);
585 Logger::warning('Delivery of mail has FAILED', ['to' => $addr, 'subject' => $subject, 'guid' => $target_item['guid']]);