3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Logger;
8 use Friendica\Core\Protocol;
9 use Friendica\Database\DBA;
12 use Friendica\Protocol\DFRN;
13 use Friendica\Protocol\Diaspora;
14 use Friendica\Protocol\Email;
15 use Friendica\Protocol\Activity;
16 use Friendica\Util\Strings;
17 use Friendica\Util\Network;
18 use Friendica\Core\Worker;
23 const SUGGESTION = 'suggest';
24 const RELOCATION = 'relocate';
25 const DELETION = 'drop';
26 const POST = 'wall-new';
28 const UPLINK = 'uplink';
29 const REMOVAL = 'removeme';
30 const PROFILEUPDATE = 'profileupdate';
32 public static function execute($cmd, $target_id, $contact_id)
34 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
38 $public_message = false;
41 if ($cmd == self::MAIL) {
42 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
43 if (!DBA::isResult($target_item)) {
44 self::setFailedQueue($cmd, $target_id);
47 $uid = $target_item['uid'];
48 } elseif ($cmd == self::SUGGESTION) {
49 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
50 if (!DBA::isResult($target_item)) {
51 self::setFailedQueue($cmd, $target_id);
54 $uid = $target_item['uid'];
55 } elseif ($cmd == self::RELOCATION) {
59 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
60 if (!DBA::isResult($item) || empty($item['parent'])) {
61 self::setFailedQueue($cmd, $target_id);
64 $parent_id = intval($item['parent']);
66 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
67 $params = ['order' => ['id']];
68 $itemdata = Model\Item::select([], $condition, $params);
70 while ($item = Model\Item::fetch($itemdata)) {
71 if ($item['id'] == $parent_id) {
74 if ($item['id'] == $target_id) {
79 DBA::close($itemdata);
81 if (empty($target_item)) {
82 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
83 self::setFailedQueue($cmd, $target_id);
88 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
89 self::setFailedQueue($cmd, $target_id);
93 if (!empty($target_item['contact-uid'])) {
94 $uid = $target_item['contact-uid'];
95 } elseif (!empty($target_item['uid'])) {
96 $uid = $target_item['uid'];
98 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
99 self::setFailedQueue($cmd, $target_id);
103 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
104 $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
105 if (!DBA::isResult($thr_parent)) {
106 // Shouldn't happen. But when this does, we just take the parent as thread parent.
107 // That's totally okay for what we use this variable here.
108 $thr_parent = $parent;
111 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
112 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
113 self::setFailedQueue($cmd, $target_id);
117 // avoid race condition with deleting entries
118 if ($items[0]['deleted']) {
119 foreach ($items as $item) {
120 $item['deleted'] = 1;
124 // When commenting too fast after delivery, a post wasn't recognized as top level post.
125 // The count then showed more than one entry. The additional check should help.
126 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
127 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
128 Logger::log('Top level post');
132 // This is IMPORTANT!!!!
134 // We will only send a "notify owner to relay" or followup message if the referenced post
135 // originated on our system by virtue of having our hostname somewhere
136 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
137 // if $parent['wall'] == 1 we will already have the parent message in our array
138 // and we will relay the whole lot.
140 $localhost = DI::baseUrl()->getHostname();
141 if (strpos($localhost, ':')) {
142 $localhost = substr($localhost, 0, strpos($localhost, ':'));
146 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
147 * have been known to cause runaway conditions which affected several servers, along with
148 * permissions issues.
152 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
153 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
154 // local followup to remote post
158 if (empty($parent['allow_cid'])
159 && empty($parent['allow_gid'])
160 && empty($parent['deny_cid'])
161 && empty($parent['deny_gid'])
162 && !$parent["private"]) {
163 $public_message = true;
168 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
171 $owner = Model\User::getOwnerDataById($uid);
172 if (!DBA::isResult($owner)) {
173 self::setFailedQueue($cmd, $target_id);
177 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
178 $contact = DBA::selectFirst('contact', [],
179 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
181 if (!DBA::isResult($contact)) {
182 self::setFailedQueue($cmd, $target_id);
186 if (Network::isUrlBlocked($contact['url'])) {
187 self::setFailedQueue($cmd, $target_id);
191 // Transmit via Diaspora if the thread had started as Diaspora post.
192 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
193 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
194 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
195 $contact['network'] = Protocol::DIASPORA;
198 // Ensure that local contacts are delivered locally
199 if (Model\Contact::isLocal($contact['url'])) {
200 $contact['network'] = Protocol::DFRN;
203 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
205 switch ($contact['network']) {
207 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
210 case Protocol::DIASPORA:
211 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
215 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
226 * Increased the "failed" counter in the item delivery data
228 * @param string $cmd Command
229 * @param integer $id Item id
231 private static function setFailedQueue(string $cmd, int $id)
233 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
237 Model\ItemDeliveryData::incrementQueueFailed($id);
241 * Deliver content via DFRN
243 * @param string $cmd Command
244 * @param array $contact Contact record of the receiver
245 * @param array $owner Owner record of the sender
246 * @param array $items Item record of the content and the parent
247 * @param array $target_item Item record of the content
248 * @param boolean $public_message Is the content public?
249 * @param boolean $top_level Is it a thread starter?
250 * @param boolean $followup Is it an answer to a remote post?
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 * @throws \ImagickException
254 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
256 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
257 if (Diaspora::isReshare($target_item['body']) && !empty(Diaspora::personByHandle($contact['addr'], false))) {
258 Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
259 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
263 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
265 if ($cmd == self::MAIL) {
266 $item = $target_item;
267 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
268 $atom = DFRN::mail($item, $owner);
269 } elseif ($cmd == self::SUGGESTION) {
270 $item = $target_item;
271 $atom = DFRN::fsuggest($item, $owner);
272 DBA::delete('fsuggest', ['id' => $item['id']]);
273 } elseif ($cmd == self::RELOCATION) {
274 $atom = DFRN::relocate($owner, $owner['uid']);
275 } elseif ($followup) {
276 $msgitems = [$target_item];
277 $atom = DFRN::entries($msgitems, $owner);
280 foreach ($items as $item) {
281 // Only add the parent when we don't delete other items.
282 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
283 $item["entry:comment-allow"] = true;
284 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
288 $atom = DFRN::entries($msgitems, $owner);
291 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
293 // perform local delivery if we are on the same site
294 if (Model\Contact::isLocal($contact['url'])) {
295 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
296 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
297 if (!DBA::isResult($target_self)) {
300 $target_uid = $target_self['uid'];
302 // Check if the user has got this contact
303 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
305 // Otherwise there should be a public contact
306 $cid = Model\Contact::getIdForURL($owner['url']);
312 $target_importer = DFRN::getImporter($cid, $target_uid);
313 if (empty($target_importer)) {
314 // This should never happen
318 DFRN::import($atom, $target_importer);
320 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
321 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DFRN);
327 $protocol = Model\ItemDeliveryData::DFRN;
329 // We don't have a relationship with contacts on a public post.
330 // Se we transmit with the new method and via Diaspora as a fallback
331 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
332 // Transmit in public if it's a relay post
333 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
335 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
337 // We never spool failed relay deliveries
339 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
341 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
342 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
343 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
345 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
351 if (($deliver_status < 200) || ($deliver_status > 299)) {
352 // Transmit via Diaspora if not possible via Friendica
353 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
356 } elseif ($cmd != self::RELOCATION) {
357 // DFRN payload over Diaspora transport layer
358 $deliver_status = DFRN::transmit($owner, $contact, $atom);
359 if ($deliver_status < 200) {
361 $deliver_status = DFRN::deliver($owner, $contact, $atom);
362 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
365 $deliver_status = DFRN::deliver($owner, $contact, $atom);
366 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
369 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
371 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
372 // We successfully delivered a message, the contact is alive
373 Model\Contact::unmarkForArchival($contact);
375 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
376 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
379 // The message could not be delivered. We mark the contact as "dead"
380 Model\Contact::markForArchival($contact);
382 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
383 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
384 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
390 * Deliver content via Diaspora
392 * @param string $cmd Command
393 * @param array $contact Contact record of the receiver
394 * @param array $owner Owner record of the sender
395 * @param array $items Item record of the content and the parent
396 * @param array $target_item Item record of the content
397 * @param boolean $public_message Is the content public?
398 * @param boolean $top_level Is it a thread starter?
399 * @param boolean $followup Is it an answer to a remote post?
400 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
401 * @throws \ImagickException
403 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
405 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
406 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
408 if ($public_message) {
409 $loc = 'public batch ' . $contact['batch'];
411 $loc = $contact['addr'];
414 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
416 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
420 if ($cmd == self::MAIL) {
421 Diaspora::sendMail($target_item, $owner, $contact);
425 if ($cmd == self::SUGGESTION) {
429 if (!$contact['pubkey'] && !$public_message) {
433 if ($cmd == self::RELOCATION) {
434 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
435 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
436 // top-level retraction
437 Logger::log('diaspora retract: ' . $loc);
438 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
439 } elseif ($followup) {
440 // send comments and likes to owner to relay
441 Logger::log('diaspora followup: ' . $loc);
442 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
443 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
444 // we are the relay - send comments, likes and relayable_retractions to our conversants
445 Logger::log('diaspora relay: ' . $loc);
446 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
447 } elseif ($top_level && !$walltowall) {
448 // currently no workable solution for sending walltowall
449 Logger::log('diaspora status: ' . $loc);
450 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
452 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
456 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
457 // We successfully delivered a message, the contact is alive
458 Model\Contact::unmarkForArchival($contact);
460 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
461 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
464 // The message could not be delivered. We mark the contact as "dead"
465 Model\Contact::markForArchival($contact);
467 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
468 if ($public_message) {
469 Diaspora::markRelayForArchival($contact);
472 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
473 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
474 // defer message for redelivery
475 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
476 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
478 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
479 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
485 * Deliver content via mail
487 * @param string $cmd Command
488 * @param array $contact Contact record of the receiver
489 * @param array $owner Owner record of the sender
490 * @param array $target_item Item record of the content
491 * @param array $thr_parent Item record of the direct parent in the thread
492 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 * @throws \ImagickException
495 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
497 if (DI::config()->get('system','dfrn_only')) {
501 $addr = $contact['addr'];
502 if (!strlen($addr)) {
506 if (!in_array($cmd, [self::POST, self::POKE])) {
510 if ($target_item['verb'] != Activity::POST) {
514 if (!empty($thr_parent['object'])) {
515 $data = json_decode($thr_parent['object'], true);
516 if (!empty($data['reply_to'])) {
517 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
518 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
519 } elseif (!empty($data['from'])) {
520 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
521 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
525 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
526 if (!DBA::isResult($local_user)) {
530 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
533 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
534 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
535 $reply_to = $mailacct['reply_to'];
538 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
540 // only expose our real email address to true friends
542 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
544 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
545 $headers .= 'Sender: ' . $local_user['email'] . "\n";
547 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
550 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . DI::baseUrl()->getHostname() . '>' . "\n";
553 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
555 if ($target_item['uri'] !== $target_item['parent-uri']) {
556 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
558 // Export more references on deeper nested threads
559 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
560 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
565 if (empty($target_item['title'])) {
566 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
567 $title = Model\Item::selectFirst(['title'], $condition);
569 if (DBA::isResult($title) && ($title['title'] != '')) {
570 $subject = $title['title'];
572 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
573 $title = Model\Item::selectFirst(['title'], $condition);
575 if (DBA::isResult($title) && ($title['title'] != '')) {
576 $subject = $title['title'];
581 if (strncasecmp($subject, 'RE:', 3)) {
582 $subject = 'Re: ' . $subject;
586 Email::send($addr, $subject, $headers, $target_item);
588 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::MAIL);
590 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);