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';
48 const REMOVAL = 'removeme';
49 const PROFILEUPDATE = 'profileupdate';
51 public static function execute(string $cmd, int $post_uriid, int $contact_id, int $sender_uid = 0)
53 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]);
57 $public_message = false;
60 if ($cmd == self::MAIL) {
61 $target_item = DBA::selectFirst('mail', [], ['id' => $post_uriid]);
62 if (!DBA::isResult($target_item)) {
65 $uid = $target_item['uid'];
66 } elseif ($cmd == self::SUGGESTION) {
68 $target_item = DI::fsuggest()->selectOneById($post_uriid)->toArray();
69 } catch (FriendSuggestNotFoundException $e) {
70 DI::logger()->info('Cannot find FriendSuggestion', ['id' => $post_uriid]);
73 $uid = $target_item['uid'];
74 } elseif ($cmd == self::RELOCATION) {
78 $item = Model\Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
79 if (!DBA::isResult($item) || empty($item['parent'])) {
80 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
83 $target_id = intval($item['id']);
84 $parent_id = intval($item['parent']);
86 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
87 $params = ['order' => ['id']];
88 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
90 while ($item = Model\Post::fetch($itemdata)) {
91 if ($item['verb'] == Activity::ANNOUNCE) {
95 if ($item['id'] == $parent_id) {
98 if ($item['id'] == $target_id) {
103 DBA::close($itemdata);
105 if (empty($target_item)) {
106 Logger::notice('Item ' . $target_id . "wasn't found. Quitting here.");
110 if (empty($parent)) {
111 Logger::notice('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
112 self::setFailedQueue($cmd, $target_item);
116 if (!empty($target_item['contact-uid'])) {
117 $uid = $target_item['contact-uid'];
118 } elseif (!empty($target_item['uid'])) {
119 $uid = $target_item['uid'];
121 Logger::info('Only public users for item ' . $target_id);
122 self::setFailedQueue($cmd, $target_item);
126 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
127 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
128 if (!DBA::isResult($thr_parent)) {
129 // Shouldn't happen. But when this does, we just take the parent as thread parent.
130 // That's totally okay for what we use this variable here.
131 $thr_parent = $parent;
134 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
135 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
136 self::setFailedQueue($cmd, $target_item);
140 // avoid race condition with deleting entries
141 if ($items[0]['deleted']) {
142 foreach ($items as $item) {
143 $item['deleted'] = 1;
147 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
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::info('Followup ' . $target_item["guid"]);
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::notice('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]);
188 $owner = Model\User::getOwnerDataById($uid);
189 if (!DBA::isResult($owner)) {
190 self::setFailedQueue($cmd, $target_item);
194 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
195 $contact = DBA::selectFirst('contact', [],
196 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
198 if (!DBA::isResult($contact)) {
199 self::setFailedQueue($cmd, $target_item);
203 if (Network::isUrlBlocked($contact['url'])) {
204 self::setFailedQueue($cmd, $target_item);
208 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
210 // Transmit via Diaspora if the thread had started as Diaspora post.
211 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
212 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
213 // Also transmit relayed posts from Diaspora contacts via Diaspora.
214 if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network']] ?? '')) {
215 Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]);
216 $contact['network'] = Protocol::DIASPORA;
219 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
221 switch ($contact['network']) {
223 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
226 case Protocol::DIASPORA:
227 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
231 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
242 * Increased the "failed" counter in the item delivery data
244 * @param string $cmd Command
245 * @param array $item Item array
247 private static function setFailedQueue(string $cmd, array $item)
249 if ($cmd != Delivery::POST) {
253 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
257 * Deliver content via DFRN
259 * @param string $cmd Command
260 * @param array $contact Contact record of the receiver
261 * @param array $owner Owner record of the sender
262 * @param array $items Item record of the content and the parent
263 * @param array $target_item Item record of the content
264 * @param boolean $public_message Is the content public?
265 * @param boolean $top_level Is it a thread starter?
266 * @param boolean $followup Is it an answer to a remote post?
267 * @param int|null $server_protocol The protocol of the server
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269 * @throws \ImagickException
271 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)
273 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
274 if (Diaspora::isReshare($target_item['body'] ?? '') && !empty(FContact::getByURL($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 DI::fsuggest()->delete(new FriendSuggests([DI::fsuggest()->selectOneById($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);
296 if ($target_item['deleted']) {
297 $msgitems = [$target_item];
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);
309 $atom = DFRN::entries($msgitems, $owner);
312 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
314 $protocol = Model\Post\DeliveryData::DFRN;
316 // We don't have a relationship with contacts on a public post.
317 // Se we transmit with the new method and via Diaspora as a fallback
318 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
319 // Transmit in public if it's a relay post
320 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
322 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
324 // We never spool failed relay deliveries
326 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
328 if ($cmd == Delivery::POST) {
329 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
330 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
332 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
334 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
340 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
341 // Transmit via Diaspora if not possible via Friendica
342 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
346 // DFRN payload over Diaspora transport layer
347 $deliver_status = DFRN::transmit($owner, $contact, $atom);
350 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
352 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
353 // We successfully delivered a message, the contact is alive
354 Model\Contact::unmarkForArchival($contact);
356 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
358 if ($cmd == Delivery::POST) {
359 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
362 // The message could not be delivered. We mark the contact as "dead"
363 Model\Contact::markForArchival($contact);
365 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
366 if (!Worker::defer() && $cmd == Delivery::POST) {
367 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
373 * Deliver content via Diaspora
375 * @param string $cmd Command
376 * @param array $contact Contact record of the receiver
377 * @param array $owner Owner record of the sender
378 * @param array $items Item record of the content and the parent
379 * @param array $target_item Item record of the content
380 * @param boolean $public_message Is the content public?
381 * @param boolean $top_level Is it a thread starter?
382 * @param boolean $followup Is it an answer to a remote post?
383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
384 * @throws \ImagickException
386 private static function deliverDiaspora(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup)
388 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
389 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
391 if ($public_message) {
392 $loc = 'public batch ' . $contact['batch'];
394 $loc = $contact['addr'];
397 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
399 if (!DI::config()->get('system', 'diaspora_enabled')) {
403 if ($cmd == self::MAIL) {
404 Diaspora::sendMail($target_item, $owner, $contact);
408 if ($cmd == self::SUGGESTION) {
412 if (!$contact['pubkey'] && !$public_message) {
416 if ($cmd == self::RELOCATION) {
417 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
418 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
419 // top-level retraction
420 Logger::notice('diaspora retract: ' . $loc);
421 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
422 } elseif ($followup) {
423 // send comments and likes to owner to relay
424 Logger::notice('diaspora followup: ' . $loc);
425 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
426 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
427 // we are the relay - send comments, likes and relayable_retractions to our conversants
428 Logger::notice('diaspora relay: ' . $loc);
429 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
430 } elseif ($top_level && !$walltowall) {
431 // currently no workable solution for sending walltowall
432 Logger::notice('diaspora status: ' . $loc);
433 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
435 Logger::notice('Unknown mode ' . $cmd . ' for ' . $loc);
439 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
440 // We successfully delivered a message, the contact is alive
441 Model\Contact::unmarkForArchival($contact);
443 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
445 if ($cmd == Delivery::POST) {
446 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
449 // The message could not be delivered. We mark the contact as "dead"
450 Model\Contact::markForArchival($contact);
452 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
453 if ($public_message) {
454 Relay::markForArchival($contact);
457 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
458 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
459 // defer message for redelivery
460 if (!Worker::defer() && $cmd == Delivery::POST) {
461 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
463 } elseif ($cmd == Delivery::POST) {
464 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
470 * Deliver content via mail
472 * @param string $cmd Command
473 * @param array $contact Contact record of the receiver
474 * @param array $owner Owner record of the sender
475 * @param array $target_item Item record of the content
476 * @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 ($cmd != self::POST) {
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;
574 $success = Email::send($addr, $subject, $headers, $target_item);
578 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
579 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);
582 Logger::warning('Delivery of mail has FAILED', ['to' => $addr, 'subject' => $subject, 'guid' => $target_item['guid']]);