3 * @copyright Copyright (C) 2010-2021, 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 UPLINK = 'uplink';
50 const REMOVAL = 'removeme';
51 const PROFILEUPDATE = 'profileupdate';
53 public static function execute(string $cmd, int $post_uriid, int $contact_id, int $sender_uid = 0)
55 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]);
59 $public_message = false;
62 if ($cmd == self::MAIL) {
63 $target_item = DBA::selectFirst('mail', [], ['id' => $post_uriid]);
64 if (!DBA::isResult($target_item)) {
67 $uid = $target_item['uid'];
68 } elseif ($cmd == self::SUGGESTION) {
70 $target_item = DI::fsuggest()->selectOneById($post_uriid)->toArray();
71 } catch (FriendSuggestNotFoundException $e) {
72 DI::logger()->info('Cannot find FriendSuggestion', ['id' => $post_uriid]);
75 $uid = $target_item['uid'];
76 } elseif ($cmd == self::RELOCATION) {
80 $item = Model\Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
81 if (!DBA::isResult($item) || empty($item['parent'])) {
82 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
85 $target_id = intval($item['id']);
86 $parent_id = intval($item['parent']);
88 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
89 $params = ['order' => ['id']];
90 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
92 while ($item = Model\Post::fetch($itemdata)) {
93 if ($item['verb'] == Activity::ANNOUNCE) {
97 if ($item['id'] == $parent_id) {
100 if ($item['id'] == $target_id) {
101 $target_item = $item;
105 DBA::close($itemdata);
107 if (empty($target_item)) {
108 Logger::notice('Item ' . $target_id . "wasn't found. Quitting here.");
112 if (empty($parent)) {
113 Logger::notice('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
114 self::setFailedQueue($cmd, $target_item);
118 if (!empty($target_item['contact-uid'])) {
119 $uid = $target_item['contact-uid'];
120 } elseif (!empty($target_item['uid'])) {
121 $uid = $target_item['uid'];
123 Logger::info('Only public users for item ' . $target_id);
124 self::setFailedQueue($cmd, $target_item);
128 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
129 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
130 if (!DBA::isResult($thr_parent)) {
131 // Shouldn't happen. But when this does, we just take the parent as thread parent.
132 // That's totally okay for what we use this variable here.
133 $thr_parent = $parent;
136 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
137 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
138 self::setFailedQueue($cmd, $target_item);
142 // avoid race condition with deleting entries
143 if ($items[0]['deleted']) {
144 foreach ($items as $item) {
145 $item['deleted'] = 1;
149 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
151 // This is IMPORTANT!!!!
153 // We will only send a "notify owner to relay" or followup message if the referenced post
154 // originated on our system by virtue of having our hostname somewhere
155 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
156 // if $parent['wall'] == 1 we will already have the parent message in our array
157 // and we will relay the whole lot.
159 $localhost = DI::baseUrl()->getHostname();
160 if (strpos($localhost, ':')) {
161 $localhost = substr($localhost, 0, strpos($localhost, ':'));
165 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
166 * have been known to cause runaway conditions which affected several servers, along with
167 * permissions issues.
171 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
172 Logger::info('Followup ' . $target_item["guid"]);
173 // local followup to remote post
177 if (empty($parent['allow_cid'])
178 && empty($parent['allow_gid'])
179 && empty($parent['deny_cid'])
180 && empty($parent['deny_gid'])
181 && ($parent["private"] != Model\Item::PRIVATE)) {
182 $public_message = true;
187 Logger::notice('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]);
190 $owner = Model\User::getOwnerDataById($uid);
191 if (!DBA::isResult($owner)) {
192 self::setFailedQueue($cmd, $target_item);
196 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
197 $contact = DBA::selectFirst('contact', [],
198 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
200 if (!DBA::isResult($contact)) {
201 self::setFailedQueue($cmd, $target_item);
205 if (Network::isUrlBlocked($contact['url'])) {
206 self::setFailedQueue($cmd, $target_item);
210 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
212 // Transmit via Diaspora if the thread had started as Diaspora post.
213 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
214 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
215 // Also transmit relayed posts from Diaspora contacts via Diaspora.
216 if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network']] ?? '')) {
217 Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]);
218 $contact['network'] = Protocol::DIASPORA;
221 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
223 switch ($contact['network']) {
225 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
228 case Protocol::DIASPORA:
229 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
233 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
244 * Increased the "failed" counter in the item delivery data
246 * @param string $cmd Command
247 * @param array $item Item array
249 private static function setFailedQueue(string $cmd, array $item)
251 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
255 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
259 * Deliver content via DFRN
261 * @param string $cmd Command
262 * @param array $contact Contact record of the receiver
263 * @param array $owner Owner record of the sender
264 * @param array $items Item record of the content and the parent
265 * @param array $target_item Item record of the content
266 * @param boolean $public_message Is the content public?
267 * @param boolean $top_level Is it a thread starter?
268 * @param boolean $followup Is it an answer to a remote post?
269 * @param int $server_protocol The protocol of the server
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $server_protocol)
275 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
276 if (Diaspora::isReshare($target_item['body'] ?? '') && !empty(FContact::getByURL($contact['addr'], false))) {
277 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
278 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
282 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
284 if ($cmd == self::MAIL) {
285 $item = $target_item;
286 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
287 $atom = DFRN::mail($item, $owner);
288 } elseif ($cmd == self::SUGGESTION) {
289 $item = $target_item;
290 $atom = DFRN::fsuggest($item, $owner);
291 DI::fsuggest()->delete(new FriendSuggests([DI::fsuggest()->selectOneById($item['id'])]));
292 } elseif ($cmd == self::RELOCATION) {
293 $atom = DFRN::relocate($owner, $owner['uid']);
294 } elseif ($followup) {
295 $msgitems = [$target_item];
296 $atom = DFRN::entries($msgitems, $owner);
298 if ($target_item['deleted']) {
299 $msgitems = [$target_item];
302 foreach ($items as $item) {
303 // Only add the parent when we don't delete other items.
304 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
305 $item["entry:comment-allow"] = true;
306 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
311 $atom = DFRN::entries($msgitems, $owner);
314 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
316 $protocol = Model\Post\DeliveryData::DFRN;
318 // We don't have a relationship with contacts on a public post.
319 // Se we transmit with the new method and via Diaspora as a fallback
320 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
321 // Transmit in public if it's a relay post
322 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
324 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
326 // We never spool failed relay deliveries
328 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
330 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
331 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
332 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
334 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
336 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
342 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
343 // Transmit via Diaspora if not possible via Friendica
344 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
348 // DFRN payload over Diaspora transport layer
349 $deliver_status = DFRN::transmit($owner, $contact, $atom);
352 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
354 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
355 // We successfully delivered a message, the contact is alive
356 Model\Contact::unmarkForArchival($contact);
358 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
360 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
361 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
364 // The message could not be delivered. We mark the contact as "dead"
365 Model\Contact::markForArchival($contact);
367 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
368 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
369 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
375 * Deliver content via Diaspora
377 * @param string $cmd Command
378 * @param array $contact Contact record of the receiver
379 * @param array $owner Owner record of the sender
380 * @param array $items Item record of the content and the parent
381 * @param array $target_item Item record of the content
382 * @param boolean $public_message Is the content public?
383 * @param boolean $top_level Is it a thread starter?
384 * @param boolean $followup Is it an answer to a remote post?
385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
386 * @throws \ImagickException
388 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
390 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
391 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
393 if ($public_message) {
394 $loc = 'public batch ' . $contact['batch'];
396 $loc = $contact['addr'];
399 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
401 if (!DI::config()->get('system', 'diaspora_enabled')) {
405 if ($cmd == self::MAIL) {
406 Diaspora::sendMail($target_item, $owner, $contact);
410 if ($cmd == self::SUGGESTION) {
414 if (!$contact['pubkey'] && !$public_message) {
418 if ($cmd == self::RELOCATION) {
419 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
420 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
421 // top-level retraction
422 Logger::notice('diaspora retract: ' . $loc);
423 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
424 } elseif ($followup) {
425 // send comments and likes to owner to relay
426 Logger::notice('diaspora followup: ' . $loc);
427 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
428 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
429 // we are the relay - send comments, likes and relayable_retractions to our conversants
430 Logger::notice('diaspora relay: ' . $loc);
431 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
432 } elseif ($top_level && !$walltowall) {
433 // currently no workable solution for sending walltowall
434 Logger::notice('diaspora status: ' . $loc);
435 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
437 Logger::notice('Unknown mode ' . $cmd . ' for ' . $loc);
441 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
442 // We successfully delivered a message, the contact is alive
443 Model\Contact::unmarkForArchival($contact);
445 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
447 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
448 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
451 // The message could not be delivered. We mark the contact as "dead"
452 Model\Contact::markForArchival($contact);
454 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
455 if ($public_message) {
456 Relay::markForArchival($contact);
459 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
460 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
461 // defer message for redelivery
462 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
463 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
465 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
466 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
472 * Deliver content via mail
474 * @param string $cmd Command
475 * @param array $contact Contact record of the receiver
476 * @param array $owner Owner record of the sender
477 * @param array $target_item Item record of the content
478 * @param array $thr_parent Item record of the direct parent in the thread
479 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
480 * @throws \ImagickException
482 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
484 if (DI::config()->get('system','imap_disabled')) {
488 $addr = $contact['addr'];
489 if (!strlen($addr)) {
493 if (!in_array($cmd, [self::POST, self::POKE])) {
497 if ($target_item['verb'] != Activity::POST) {
501 if (!empty($thr_parent['object'])) {
502 $data = json_decode($thr_parent['object'], true);
503 if (!empty($data['reply_to'])) {
504 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
505 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
506 } elseif (!empty($data['from'])) {
507 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
508 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
512 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
513 if (!DBA::isResult($local_user)) {
517 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
520 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
521 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
522 $reply_to = $mailacct['reply_to'];
525 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
527 // only expose our real email address to true friends
529 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
531 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
532 $headers .= 'Sender: ' . $local_user['email'] . "\n";
534 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
537 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
538 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
541 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
543 if ($target_item['uri'] !== $target_item['parent-uri']) {
544 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
546 // Export more references on deeper nested threads
547 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
548 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
553 if (empty($target_item['title'])) {
554 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
555 $title = Model\Post::selectFirst(['title'], $condition);
557 if (DBA::isResult($title) && ($title['title'] != '')) {
558 $subject = $title['title'];
560 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
561 $title = Model\Post::selectFirst(['title'], $condition);
563 if (DBA::isResult($title) && ($title['title'] != '')) {
564 $subject = $title['title'];
569 if (strncasecmp($subject, 'RE:', 3)) {
570 $subject = 'Re: ' . $subject;
574 Email::send($addr, $subject, $headers, $target_item);
576 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
578 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);