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\Database\DBA;
31 use Friendica\Protocol\DFRN;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Protocol\Email;
34 use Friendica\Protocol\Activity;
35 use Friendica\Util\Network;
36 use Friendica\Core\Worker;
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 REMOVAL = 'removeme';
50 const PROFILEUPDATE = 'profileupdate';
52 public static function execute(string $cmd, int $post_uriid, int $contact_id, int $sender_uid = 0)
54 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]);
58 $public_message = false;
61 if ($cmd == self::MAIL) {
62 $target_item = DBA::selectFirst('mail', [], ['id' => $post_uriid]);
63 if (!DBA::isResult($target_item)) {
66 $uid = $target_item['uid'];
67 } elseif ($cmd == self::SUGGESTION) {
69 $target_item = DI::fsuggest()->selectOneById($post_uriid)->toArray();
70 } catch (FriendSuggestNotFoundException $e) {
71 DI::logger()->info('Cannot find FriendSuggestion', ['id' => $post_uriid]);
74 $uid = $target_item['uid'];
75 } elseif ($cmd == self::RELOCATION) {
79 $item = Model\Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
80 if (!DBA::isResult($item) || empty($item['parent'])) {
81 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
84 $target_id = intval($item['id']);
85 $parent_id = intval($item['parent']);
87 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
88 $params = ['order' => ['id']];
89 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
91 while ($item = Model\Post::fetch($itemdata)) {
92 if ($item['verb'] == Activity::ANNOUNCE) {
96 if ($item['id'] == $parent_id) {
99 if ($item['id'] == $target_id) {
100 $target_item = $item;
104 DBA::close($itemdata);
106 if (empty($target_item)) {
107 Logger::notice('Item ' . $target_id . "wasn't found. Quitting here.");
111 if (empty($parent)) {
112 Logger::notice('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
113 self::setFailedQueue($cmd, $target_item);
117 if (!empty($target_item['contact-uid'])) {
118 $uid = $target_item['contact-uid'];
119 } elseif (!empty($target_item['uid'])) {
120 $uid = $target_item['uid'];
122 Logger::info('Only public users for item ' . $target_id);
123 self::setFailedQueue($cmd, $target_item);
127 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
128 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
129 if (!DBA::isResult($thr_parent)) {
130 // Shouldn't happen. But when this does, we just take the parent as thread parent.
131 // That's totally okay for what we use this variable here.
132 $thr_parent = $parent;
135 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
136 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
137 self::setFailedQueue($cmd, $target_item);
141 // avoid race condition with deleting entries
142 if ($items[0]['deleted']) {
143 foreach ($items as $item) {
144 $item['deleted'] = 1;
148 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
150 // This is IMPORTANT!!!!
152 // We will only send a "notify owner to relay" or followup message if the referenced post
153 // originated on our system by virtue of having our hostname somewhere
154 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
155 // if $parent['wall'] == 1 we will already have the parent message in our array
156 // and we will relay the whole lot.
158 $localhost = DI::baseUrl()->getHostname();
159 if (strpos($localhost, ':')) {
160 $localhost = substr($localhost, 0, strpos($localhost, ':'));
164 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
165 * have been known to cause runaway conditions which affected several servers, along with
166 * permissions issues.
170 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
171 Logger::info('Followup ' . $target_item["guid"]);
172 // local followup to remote post
176 if (empty($parent['allow_cid'])
177 && empty($parent['allow_gid'])
178 && empty($parent['deny_cid'])
179 && empty($parent['deny_gid'])
180 && ($parent["private"] != Model\Item::PRIVATE)) {
181 $public_message = true;
186 Logger::notice('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]);
189 $owner = Model\User::getOwnerDataById($uid);
190 if (!DBA::isResult($owner)) {
191 self::setFailedQueue($cmd, $target_item);
195 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
196 $contact = DBA::selectFirst('contact', [],
197 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
199 if (!DBA::isResult($contact)) {
200 self::setFailedQueue($cmd, $target_item);
204 if (Network::isUrlBlocked($contact['url'])) {
205 self::setFailedQueue($cmd, $target_item);
209 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
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 // Also transmit relayed posts from Diaspora contacts via Diaspora.
215 if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network']] ?? '')) {
216 Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]);
217 $contact['network'] = Protocol::DIASPORA;
220 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
222 switch ($contact['network']) {
224 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
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 array $item Item array
248 private static function setFailedQueue(string $cmd, array $item)
250 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
254 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['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 * @param int $server_protocol The protocol of the server
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 * @throws \ImagickException
272 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)
274 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
275 if (Diaspora::isReshare($target_item['body'] ?? '') && !empty(FContact::getByURL($contact['addr'], false))) {
276 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
277 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
281 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
283 if ($cmd == self::MAIL) {
284 $item = $target_item;
285 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
286 $atom = DFRN::mail($item, $owner);
287 } elseif ($cmd == self::SUGGESTION) {
288 $item = $target_item;
289 $atom = DFRN::fsuggest($item, $owner);
290 DI::fsuggest()->delete(new FriendSuggests([DI::fsuggest()->selectOneById($item['id'])]));
291 } elseif ($cmd == self::RELOCATION) {
292 $atom = DFRN::relocate($owner, $owner['uid']);
293 } elseif ($followup) {
294 $msgitems = [$target_item];
295 $atom = DFRN::entries($msgitems, $owner);
297 if ($target_item['deleted']) {
298 $msgitems = [$target_item];
301 foreach ($items as $item) {
302 // Only add the parent when we don't delete other items.
303 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
304 $item["entry:comment-allow"] = true;
305 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
310 $atom = DFRN::entries($msgitems, $owner);
313 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
315 $protocol = Model\Post\DeliveryData::DFRN;
317 // We don't have a relationship with contacts on a public post.
318 // Se we transmit with the new method and via Diaspora as a fallback
319 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
320 // Transmit in public if it's a relay post
321 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
323 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
325 // We never spool failed relay deliveries
327 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
329 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
330 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
331 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
333 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
335 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
341 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
342 // Transmit via Diaspora if not possible via Friendica
343 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
347 // DFRN payload over Diaspora transport layer
348 $deliver_status = DFRN::transmit($owner, $contact, $atom);
351 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
353 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
354 // We successfully delivered a message, the contact is alive
355 Model\Contact::unmarkForArchival($contact);
357 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
359 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
360 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
363 // The message could not be delivered. We mark the contact as "dead"
364 Model\Contact::markForArchival($contact);
366 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
367 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
368 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
374 * Deliver content via Diaspora
376 * @param string $cmd Command
377 * @param array $contact Contact record of the receiver
378 * @param array $owner Owner record of the sender
379 * @param array $items Item record of the content and the parent
380 * @param array $target_item Item record of the content
381 * @param boolean $public_message Is the content public?
382 * @param boolean $top_level Is it a thread starter?
383 * @param boolean $followup Is it an answer to a remote post?
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385 * @throws \ImagickException
387 private static function deliverDiaspora(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup)
389 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
390 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
392 if ($public_message) {
393 $loc = 'public batch ' . $contact['batch'];
395 $loc = $contact['addr'];
398 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
400 if (!DI::config()->get('system', 'diaspora_enabled')) {
404 if ($cmd == self::MAIL) {
405 Diaspora::sendMail($target_item, $owner, $contact);
409 if ($cmd == self::SUGGESTION) {
413 if (!$contact['pubkey'] && !$public_message) {
417 if ($cmd == self::RELOCATION) {
418 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
419 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
420 // top-level retraction
421 Logger::notice('diaspora retract: ' . $loc);
422 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
423 } elseif ($followup) {
424 // send comments and likes to owner to relay
425 Logger::notice('diaspora followup: ' . $loc);
426 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
427 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
428 // we are the relay - send comments, likes and relayable_retractions to our conversants
429 Logger::notice('diaspora relay: ' . $loc);
430 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
431 } elseif ($top_level && !$walltowall) {
432 // currently no workable solution for sending walltowall
433 Logger::notice('diaspora status: ' . $loc);
434 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
436 Logger::notice('Unknown mode ' . $cmd . ' for ' . $loc);
440 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
441 // We successfully delivered a message, the contact is alive
442 Model\Contact::unmarkForArchival($contact);
444 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
446 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
447 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
450 // The message could not be delivered. We mark the contact as "dead"
451 Model\Contact::markForArchival($contact);
453 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
454 if ($public_message) {
455 Relay::markForArchival($contact);
458 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
459 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
460 // defer message for redelivery
461 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
462 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
464 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
465 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
471 * Deliver content via mail
473 * @param string $cmd Command
474 * @param array $contact Contact record of the receiver
475 * @param array $owner Owner record of the sender
476 * @param array $target_item Item record of the content
477 * @param array $thr_parent Item record of the direct parent in the thread
478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
479 * @throws \ImagickException
481 private static function deliverMail(string $cmd, array $contact, array $owner, array $target_item, array $thr_parent)
483 if (DI::config()->get('system','imap_disabled')) {
487 $addr = $contact['addr'];
488 if (!strlen($addr)) {
492 if (!in_array($cmd, [self::POST, self::POKE])) {
496 if ($target_item['verb'] != Activity::POST) {
500 if (!empty($thr_parent['object'])) {
501 $data = json_decode($thr_parent['object'], true);
502 if (!empty($data['reply_to'])) {
503 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
504 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
505 } elseif (!empty($data['from'])) {
506 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
507 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
511 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
512 if (!DBA::isResult($local_user)) {
516 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
519 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
520 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
521 $reply_to = $mailacct['reply_to'];
524 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
526 // only expose our real email address to true friends
528 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
530 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
531 $headers .= 'Sender: ' . $local_user['email'] . "\n";
533 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
536 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
537 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
540 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
542 if ($target_item['uri'] !== $target_item['parent-uri']) {
543 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
545 // Export more references on deeper nested threads
546 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
547 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
552 if (empty($target_item['title'])) {
553 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
554 $title = Model\Post::selectFirst(['title'], $condition);
556 if (DBA::isResult($title) && ($title['title'] != '')) {
557 $subject = $title['title'];
559 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
560 $title = Model\Post::selectFirst(['title'], $condition);
562 if (DBA::isResult($title) && ($title['title'] != '')) {
563 $subject = $title['title'];
568 if (strncasecmp($subject, 'RE:', 3)) {
569 $subject = 'Re: ' . $subject;
573 Email::send($addr, $subject, $headers, $target_item);
575 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
577 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);