3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Diaspora;
17 use Friendica\Protocol\Email;
18 use Friendica\Protocol\Activity;
19 use Friendica\Util\Strings;
20 use Friendica\Util\Network;
21 use Friendica\Core\Worker;
23 class Delivery extends BaseObject
26 const SUGGESTION = 'suggest';
27 const RELOCATION = 'relocate';
28 const DELETION = 'drop';
29 const POST = 'wall-new';
31 const UPLINK = 'uplink';
32 const REMOVAL = 'removeme';
33 const PROFILEUPDATE = 'profileupdate';
35 public static function execute($cmd, $target_id, $contact_id)
37 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
41 $public_message = false;
44 if ($cmd == self::MAIL) {
45 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
46 if (!DBA::isResult($target_item)) {
47 self::setFailedQueue($cmd, $target_id);
50 $uid = $target_item['uid'];
51 } elseif ($cmd == self::SUGGESTION) {
52 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
53 if (!DBA::isResult($target_item)) {
54 self::setFailedQueue($cmd, $target_id);
57 $uid = $target_item['uid'];
58 } elseif ($cmd == self::RELOCATION) {
62 $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
63 if (!DBA::isResult($item) || empty($item['parent'])) {
64 self::setFailedQueue($cmd, $target_id);
67 $parent_id = intval($item['parent']);
69 $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
70 $params = ['order' => ['id']];
71 $itemdata = Model\Item::select([], $condition, $params);
73 while ($item = Model\Item::fetch($itemdata)) {
74 if ($item['id'] == $parent_id) {
77 if ($item['id'] == $target_id) {
82 DBA::close($itemdata);
84 if (empty($target_item)) {
85 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
86 self::setFailedQueue($cmd, $target_id);
91 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
92 self::setFailedQueue($cmd, $target_id);
96 if (!empty($target_item['contact-uid'])) {
97 $uid = $target_item['contact-uid'];
98 } elseif (!empty($target_item['uid'])) {
99 $uid = $target_item['uid'];
101 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
102 self::setFailedQueue($cmd, $target_id);
106 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
107 $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
108 if (!DBA::isResult($thr_parent)) {
109 // Shouldn't happen. But when this does, we just take the parent as thread parent.
110 // That's totally okay for what we use this variable here.
111 $thr_parent = $parent;
114 if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
115 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
116 self::setFailedQueue($cmd, $target_id);
120 // avoid race condition with deleting entries
121 if ($items[0]['deleted']) {
122 foreach ($items as $item) {
123 $item['deleted'] = 1;
127 // When commenting too fast after delivery, a post wasn't recognized as top level post.
128 // The count then showed more than one entry. The additional check should help.
129 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
130 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
131 Logger::log('Top level post');
135 // This is IMPORTANT!!!!
137 // We will only send a "notify owner to relay" or followup message if the referenced post
138 // originated on our system by virtue of having our hostname somewhere
139 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
140 // if $parent['wall'] == 1 we will already have the parent message in our array
141 // and we will relay the whole lot.
143 $localhost = self::getApp()->getHostName();
144 if (strpos($localhost, ':')) {
145 $localhost = substr($localhost, 0, strpos($localhost, ':'));
149 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
150 * have been known to cause runaway conditions which affected several servers, along with
151 * permissions issues.
155 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
156 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
157 // local followup to remote post
161 if (empty($parent['allow_cid'])
162 && empty($parent['allow_gid'])
163 && empty($parent['deny_cid'])
164 && empty($parent['deny_gid'])
165 && !$parent["private"]) {
166 $public_message = true;
171 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
174 $owner = Model\User::getOwnerDataById($uid);
175 if (!DBA::isResult($owner)) {
176 self::setFailedQueue($cmd, $target_id);
180 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
181 $contact = DBA::selectFirst('contact', [],
182 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
184 if (!DBA::isResult($contact)) {
185 self::setFailedQueue($cmd, $target_id);
189 if (Network::isUrlBlocked($contact['url'])) {
190 self::setFailedQueue($cmd, $target_id);
194 // Transmit via Diaspora if the thread had started as Diaspora post.
195 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
196 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
197 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
198 $contact['network'] = Protocol::DIASPORA;
201 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
203 switch ($contact['network']) {
205 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
208 case Protocol::DIASPORA:
209 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
213 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
224 * Increased the "failed" counter in the item delivery data
226 * @param string $cmd Command
227 * @param integer $id Item id
229 private static function setFailedQueue(string $cmd, int $id)
231 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
235 Model\ItemDeliveryData::incrementQueueFailed($id);
239 * @brief Deliver content via DFRN
241 * @param string $cmd Command
242 * @param array $contact Contact record of the receiver
243 * @param array $owner Owner record of the sender
244 * @param array $items Item record of the content and the parent
245 * @param array $target_item Item record of the content
246 * @param boolean $public_message Is the content public?
247 * @param boolean $top_level Is it a thread starter?
248 * @param boolean $followup Is it an answer to a remote post?
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
255 if (Diaspora::isReshare($target_item['body'])) {
256 // Transmit Diaspora reshares only via Diaspora
257 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
261 if (ActivityPub\Transmitter::::isAnnounce($target_item) && getby) {
265 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
267 if ($cmd == self::MAIL) {
268 $item = $target_item;
269 $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
270 $atom = DFRN::mail($item, $owner);
271 } elseif ($cmd == self::SUGGESTION) {
272 $item = $target_item;
273 $atom = DFRN::fsuggest($item, $owner);
274 DBA::delete('fsuggest', ['id' => $item['id']]);
275 } elseif ($cmd == self::RELOCATION) {
276 $atom = DFRN::relocate($owner, $owner['uid']);
277 } elseif ($followup) {
278 $msgitems = [$target_item];
279 $atom = DFRN::entries($msgitems, $owner);
282 foreach ($items as $item) {
283 // Only add the parent when we don't delete other items.
284 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
285 $item["entry:comment-allow"] = true;
286 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
290 $atom = DFRN::entries($msgitems, $owner);
293 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
295 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
297 // perform local delivery if we are on the same site
299 if (Strings::compareLink($basepath, System::baseUrl())) {
300 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
301 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
302 if (!DBA::isResult($target_self)) {
305 $target_uid = $target_self['uid'];
307 // Check if the user has got this contact
308 $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
310 // Otherwise there should be a public contact
311 $cid = Model\Contact::getIdForURL($owner['url']);
317 $target_importer = DFRN::getImporter($cid, $target_uid);
318 if (empty($target_importer)) {
319 // This should never happen
323 DFRN::import($atom, $target_importer);
325 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
326 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DFRN);
332 $protocol = Model\ItemDeliveryData::DFRN;
334 // We don't have a relationship with contacts on a public post.
335 // Se we transmit with the new method and via Diaspora as a fallback
336 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
337 // Transmit in public if it's a relay post
338 $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
340 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
342 // We never spool failed relay deliveries
344 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
346 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
347 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
348 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
350 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
356 if (($deliver_status < 200) || ($deliver_status > 299)) {
357 // Transmit via Diaspora if not possible via Friendica
358 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
361 } elseif ($cmd != self::RELOCATION) {
362 // DFRN payload over Diaspora transport layer
363 $deliver_status = DFRN::transmit($owner, $contact, $atom);
364 if ($deliver_status < 200) {
366 $deliver_status = DFRN::deliver($owner, $contact, $atom);
367 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
370 $deliver_status = DFRN::deliver($owner, $contact, $atom);
371 $protocol = Model\ItemDeliveryData::LEGACY_DFRN;
374 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
376 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
377 // We successfully delivered a message, the contact is alive
378 Model\Contact::unmarkForArchival($contact);
380 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
381 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], $protocol);
384 // The message could not be delivered. We mark the contact as "dead"
385 Model\Contact::markForArchival($contact);
387 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
388 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
389 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
395 * @brief Deliver content via Diaspora
397 * @param string $cmd Command
398 * @param array $contact Contact record of the receiver
399 * @param array $owner Owner record of the sender
400 * @param array $items Item record of the content and the parent
401 * @param array $target_item Item record of the content
402 * @param boolean $public_message Is the content public?
403 * @param boolean $top_level Is it a thread starter?
404 * @param boolean $followup Is it an answer to a remote post?
405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 * @throws \ImagickException
408 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
410 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
411 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
413 if ($public_message) {
414 $loc = 'public batch ' . $contact['batch'];
416 $loc = $contact['addr'];
419 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
421 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
425 if ($cmd == self::MAIL) {
426 Diaspora::sendMail($target_item, $owner, $contact);
430 if ($cmd == self::SUGGESTION) {
434 if (!$contact['pubkey'] && !$public_message) {
438 if ($cmd == self::RELOCATION) {
439 $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
440 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
441 // top-level retraction
442 Logger::log('diaspora retract: ' . $loc);
443 $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
444 } elseif ($followup) {
445 // send comments and likes to owner to relay
446 Logger::log('diaspora followup: ' . $loc);
447 $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
448 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
449 // we are the relay - send comments, likes and relayable_retractions to our conversants
450 Logger::log('diaspora relay: ' . $loc);
451 $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
452 } elseif ($top_level && !$walltowall) {
453 // currently no workable solution for sending walltowall
454 Logger::log('diaspora status: ' . $loc);
455 $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
457 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
461 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
462 // We successfully delivered a message, the contact is alive
463 Model\Contact::unmarkForArchival($contact);
465 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
466 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::DIASPORA);
469 // The message could not be delivered. We mark the contact as "dead"
470 Model\Contact::markForArchival($contact);
472 // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
473 if ($public_message) {
474 Diaspora::markRelayForArchival($contact);
477 if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
478 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
479 // defer message for redelivery
480 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
481 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
483 } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
484 Model\ItemDeliveryData::incrementQueueFailed($target_item['id']);
490 * @brief Deliver content via mail
492 * @param string $cmd Command
493 * @param array $contact Contact record of the receiver
494 * @param array $owner Owner record of the sender
495 * @param array $target_item Item record of the content
496 * @param array $thr_parent Item record of the direct parent in the thread
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
502 if (Config::get('system','dfrn_only')) {
506 $addr = $contact['addr'];
507 if (!strlen($addr)) {
511 if (!in_array($cmd, [self::POST, self::POKE])) {
515 if ($target_item['verb'] != Activity::POST) {
519 if (!empty($thr_parent['object'])) {
520 $data = json_decode($thr_parent['object'], true);
521 if (!empty($data['reply_to'])) {
522 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
523 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
524 } elseif (!empty($data['from'])) {
525 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
526 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
530 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
531 if (!DBA::isResult($local_user)) {
535 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
538 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
539 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
540 $reply_to = $mailacct['reply_to'];
543 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
545 // only expose our real email address to true friends
547 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
549 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
550 $headers .= 'Sender: ' . $local_user['email'] . "\n";
552 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
555 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
558 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
560 if ($target_item['uri'] !== $target_item['parent-uri']) {
561 $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
563 // Export more references on deeper nested threads
564 if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
565 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
570 if (empty($target_item['title'])) {
571 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
572 $title = Model\Item::selectFirst(['title'], $condition);
574 if (DBA::isResult($title) && ($title['title'] != '')) {
575 $subject = $title['title'];
577 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
578 $title = Model\Item::selectFirst(['title'], $condition);
580 if (DBA::isResult($title) && ($title['title'] != '')) {
581 $subject = $title['title'];
586 if (strncasecmp($subject, 'RE:', 3)) {
587 $subject = 'Re: ' . $subject;
591 Email::send($addr, $subject, $headers, $target_item);
593 Model\ItemDeliveryData::incrementQueueDone($target_item['id'], Model\ItemDeliveryData::MAIL);
595 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);