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\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\Network;
34 use Friendica\Core\Worker;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\FContact;
37 use Friendica\Model\Item;
38 use Friendica\Protocol\Relay;
43 const SUGGESTION = 'suggest';
44 const RELOCATION = 'relocate';
45 const DELETION = 'drop';
46 const POST = 'wall-new';
48 const UPLINK = 'uplink';
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) {
68 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $post_uriid]);
69 if (!DBA::isResult($target_item)) {
72 $uid = $target_item['uid'];
73 } elseif ($cmd == self::RELOCATION) {
77 $item = Model\Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
78 if (!DBA::isResult($item) || empty($item['parent'])) {
79 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
82 $target_id = intval($item['id']);
83 $parent_id = intval($item['parent']);
85 $condition = ['id' => [$target_id, $parent_id], 'visible' => true];
86 $params = ['order' => ['id']];
87 $itemdata = Model\Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
89 while ($item = Model\Post::fetch($itemdata)) {
90 if ($item['verb'] == Activity::ANNOUNCE) {
94 if ($item['id'] == $parent_id) {
97 if ($item['id'] == $target_id) {
102 DBA::close($itemdata);
104 if (empty($target_item)) {
105 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
109 if (empty($parent)) {
110 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
111 self::setFailedQueue($cmd, $target_item);
115 if (!empty($target_item['contact-uid'])) {
116 $uid = $target_item['contact-uid'];
117 } elseif (!empty($target_item['uid'])) {
118 $uid = $target_item['uid'];
120 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
121 self::setFailedQueue($cmd, $target_item);
125 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
126 $thr_parent = Model\Post::selectFirst(['network', 'object'], $condition);
127 if (!DBA::isResult($thr_parent)) {
128 // Shouldn't happen. But when this does, we just take the parent as thread parent.
129 // That's totally okay for what we use this variable here.
130 $thr_parent = $parent;
133 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
134 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
135 self::setFailedQueue($cmd, $target_item);
139 // avoid race condition with deleting entries
140 if ($items[0]['deleted']) {
141 foreach ($items as $item) {
142 $item['deleted'] = 1;
146 $top_level = $target_item['gravity'] == GRAVITY_PARENT;
148 // This is IMPORTANT!!!!
150 // We will only send a "notify owner to relay" or followup message if the referenced post
151 // originated on our system by virtue of having our hostname somewhere
152 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
153 // if $parent['wall'] == 1 we will already have the parent message in our array
154 // and we will relay the whole lot.
156 $localhost = DI::baseUrl()->getHostname();
157 if (strpos($localhost, ':')) {
158 $localhost = substr($localhost, 0, strpos($localhost, ':'));
162 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
163 * have been known to cause runaway conditions which affected several servers, along with
164 * permissions issues.
168 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
169 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
170 // local followup to remote post
174 if (empty($parent['allow_cid'])
175 && empty($parent['allow_gid'])
176 && empty($parent['deny_cid'])
177 && empty($parent['deny_gid'])
178 && ($parent["private"] != Model\Item::PRIVATE)) {
179 $public_message = true;
184 Logger::notice('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]);
187 $owner = Model\User::getOwnerDataById($uid);
188 if (!DBA::isResult($owner)) {
189 self::setFailedQueue($cmd, $target_item);
193 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
194 $contact = DBA::selectFirst('contact', [],
195 ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
197 if (!DBA::isResult($contact)) {
198 self::setFailedQueue($cmd, $target_item);
202 if (Network::isUrlBlocked($contact['url'])) {
203 self::setFailedQueue($cmd, $target_item);
207 $protocol = Model\GServer::getProtocol($contact['gsid'] ?? 0);
209 // Transmit via Diaspora if the thread had started as Diaspora post.
210 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
211 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
212 // Also transmit relayed posts from Diaspora contacts via Diaspora.
213 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network'], $target_item['network']])) {
214 $contact['network'] = Protocol::DIASPORA;
217 Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]);
219 switch ($contact['network']) {
221 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $protocol);
224 case Protocol::DIASPORA:
225 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
229 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
240 * Increased the "failed" counter in the item delivery data
242 * @param string $cmd Command
243 * @param array $item Item array
245 private static function setFailedQueue(string $cmd, array $item)
247 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
251 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
255 * Deliver content via DFRN
257 * @param string $cmd Command
258 * @param array $contact Contact record of the receiver
259 * @param array $owner Owner record of the sender
260 * @param array $items Item record of the content and the parent
261 * @param array $target_item Item record of the content
262 * @param boolean $public_message Is the content public?
263 * @param boolean $top_level Is it a thread starter?
264 * @param boolean $followup Is it an answer to a remote post?
265 * @param int $server_protocol The protocol of the server
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 * @throws \ImagickException
269 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $server_protocol)
271 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
272 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
273 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
274 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
278 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
280 if ($cmd == self::MAIL) {
281 $item = $target_item;
282 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
283 $atom = DFRN::mail($item, $owner);
284 } elseif ($cmd == self::SUGGESTION) {
285 $item = $target_item;
286 $atom = DFRN::fsuggest($item, $owner);
287 DBA::delete('fsuggest', ['id' => $item['id']]);
288 } elseif ($cmd == self::RELOCATION) {
289 $atom = DFRN::relocate($owner, $owner['uid']);
290 } elseif ($followup) {
291 $msgitems = [$target_item];
292 $atom = DFRN::entries($msgitems, $owner);
294 if ($target_item['deleted']) {
295 $msgitems = [$target_item];
298 foreach ($items as $item) {
299 // Only add the parent when we don't delete other items.
300 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
301 $item["entry:comment-allow"] = true;
302 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
307 $atom = DFRN::entries($msgitems, $owner);
310 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
312 $protocol = Model\Post\DeliveryData::DFRN;
314 // We don't have a relationship with contacts on a public post.
315 // Se we transmit with the new method and via Diaspora as a fallback
316 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
317 // Transmit in public if it's a relay post
318 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
320 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
322 // We never spool failed relay deliveries
324 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
326 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
327 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
328 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
330 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
332 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
338 if ((($deliver_status < 200) || ($deliver_status > 299)) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
339 // Transmit via Diaspora if not possible via Friendica
340 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
343 } elseif ($cmd != self::RELOCATION) {
344 // DFRN payload over Diaspora transport layer
345 $deliver_status = DFRN::transmit($owner, $contact, $atom);
346 if (($deliver_status < 200) && (empty($server_protocol) || ($server_protocol == Model\Post\DeliveryData::LEGACY_DFRN))) {
348 $deliver_status = DFRN::deliver($owner, $contact, $atom);
349 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
352 $deliver_status = DFRN::deliver($owner, $contact, $atom);
353 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
356 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
358 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
359 // We successfully delivered a message, the contact is alive
360 Model\Contact::unmarkForArchival($contact);
362 Model\GServer::setProtocol($contact['gsid'] ?? 0, $protocol);
364 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
365 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
368 // The message could not be delivered. We mark the contact as "dead"
369 Model\Contact::markForArchival($contact);
371 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
372 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
373 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
379 * Deliver content via Diaspora
381 * @param string $cmd Command
382 * @param array $contact Contact record of the receiver
383 * @param array $owner Owner record of the sender
384 * @param array $items Item record of the content and the parent
385 * @param array $target_item Item record of the content
386 * @param boolean $public_message Is the content public?
387 * @param boolean $top_level Is it a thread starter?
388 * @param boolean $followup Is it an answer to a remote post?
389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
390 * @throws \ImagickException
392 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
394 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
395 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
397 if ($public_message) {
398 $loc = 'public batch ' . $contact['batch'];
400 $loc = $contact['addr'];
403 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
405 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
409 if ($cmd == self::MAIL) {
410 Diaspora::sendMail($target_item, $owner, $contact);
414 if ($cmd == self::SUGGESTION) {
418 if (!$contact['pubkey'] && !$public_message) {
422 if ($cmd == self::RELOCATION) {
423 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
424 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
425 // top-level retraction
426 Logger::log('diaspora retract: ' . $loc);
427 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
428 } elseif ($followup) {
429 // send comments and likes to owner to relay
430 Logger::log('diaspora followup: ' . $loc);
431 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
432 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
433 // we are the relay - send comments, likes and relayable_retractions to our conversants
434 Logger::log('diaspora relay: ' . $loc);
435 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
436 } elseif ($top_level && !$walltowall) {
437 // currently no workable solution for sending walltowall
438 Logger::log('diaspora status: ' . $loc);
439 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
441 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
445 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
446 // We successfully delivered a message, the contact is alive
447 Model\Contact::unmarkForArchival($contact);
449 Model\GServer::setProtocol($contact['gsid'] ?? 0, Model\Post\DeliveryData::DIASPORA);
451 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
452 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
455 // The message could not be delivered. We mark the contact as "dead"
456 Model\Contact::markForArchival($contact);
458 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
459 if ($public_message) {
460 Relay::markForArchival($contact);
463 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
464 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
465 // defer message for redelivery
466 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
467 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
469 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
470 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
476 * Deliver content via mail
478 * @param string $cmd Command
479 * @param array $contact Contact record of the receiver
480 * @param array $owner Owner record of the sender
481 * @param array $target_item Item record of the content
482 * @param array $thr_parent Item record of the direct parent in the thread
483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
484 * @throws \ImagickException
486 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
488 if (DI::config()->get('system','dfrn_only')) {
492 $addr = $contact['addr'];
493 if (!strlen($addr)) {
497 if (!in_array($cmd, [self::POST, self::POKE])) {
501 if ($target_item['verb'] != Activity::POST) {
505 if (!empty($thr_parent['object'])) {
506 $data = json_decode($thr_parent['object'], true);
507 if (!empty($data['reply_to'])) {
508 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
509 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
510 } elseif (!empty($data['from'])) {
511 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
512 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
516 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
517 if (!DBA::isResult($local_user)) {
521 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
524 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
525 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
526 $reply_to = $mailacct['reply_to'];
529 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
531 // only expose our real email address to true friends
533 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
535 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
536 $headers .= 'Sender: ' . $local_user['email'] . "\n";
538 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
541 $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
542 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
545 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
547 if ($target_item['uri'] !== $target_item['parent-uri']) {
548 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
550 // Export more references on deeper nested threads
551 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
552 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
557 if (empty($target_item['title'])) {
558 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
559 $title = Model\Post::selectFirst(['title'], $condition);
561 if (DBA::isResult($title) && ($title['title'] != '')) {
562 $subject = $title['title'];
564 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
565 $title = Model\Post::selectFirst(['title'], $condition);
567 if (DBA::isResult($title) && ($title['title'] != '')) {
568 $subject = $title['title'];
573 if (strncasecmp($subject, 'RE:', 3)) {
574 $subject = 'Re: ' . $subject;
578 Email::send($addr, $subject, $headers, $target_item);
580 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
582 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);