]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Merge remote-tracking branch 'upstream/develop' into no-term2
[friendica.git] / src / Worker / Delivery.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Worker;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model;
29 use Friendica\Protocol\DFRN;
30 use Friendica\Protocol\Diaspora;
31 use Friendica\Protocol\Email;
32 use Friendica\Protocol\Activity;
33 use Friendica\Util\Strings;
34 use Friendica\Util\Network;
35 use Friendica\Core\Worker;
36
37 class Delivery
38 {
39         const MAIL          = 'mail';
40         const SUGGESTION    = 'suggest';
41         const RELOCATION    = 'relocate';
42         const DELETION      = 'drop';
43         const POST          = 'wall-new';
44         const POKE          = 'poke';
45         const UPLINK        = 'uplink';
46         const REMOVAL       = 'removeme';
47         const PROFILEUPDATE = 'profileupdate';
48
49         public static function execute($cmd, $target_id, $contact_id)
50         {
51                 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
52
53                 $top_level = false;
54                 $followup = false;
55                 $public_message = false;
56
57                 $items = [];
58                 if ($cmd == self::MAIL) {
59                         $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
60                         if (!DBA::isResult($target_item)) {
61                                 self::setFailedQueue($cmd, $target_item);
62                                 return;
63                         }
64                         $uid = $target_item['uid'];
65                 } elseif ($cmd == self::SUGGESTION) {
66                         $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
67                         if (!DBA::isResult($target_item)) {
68                                 self::setFailedQueue($cmd, $target_item);
69                                 return;
70                         }
71                         $uid = $target_item['uid'];
72                 } elseif ($cmd == self::RELOCATION) {
73                         $uid = $target_id;
74                         $target_item = [];
75                 } else {
76                         $item = Model\Item::selectFirst(['parent'], ['id' => $target_id]);
77                         if (!DBA::isResult($item) || empty($item['parent'])) {
78                                 self::setFailedQueue($cmd, $target_item);
79                                 return;
80                         }
81                         $parent_id = intval($item['parent']);
82
83                         $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
84                         $params = ['order' => ['id']];
85                         $itemdata = Model\Item::select([], $condition, $params);
86
87                         while ($item = Model\Item::fetch($itemdata)) {
88                                 if ($item['id'] == $parent_id) {
89                                         $parent = $item;
90                                 }
91                                 if ($item['id'] == $target_id) {
92                                         $target_item = $item;
93                                 }
94                                 $items[] = $item;
95                         }
96                         DBA::close($itemdata);
97
98                         if (empty($target_item)) {
99                                 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
100                                 self::setFailedQueue($cmd, $target_item);
101                                 return;
102                         }
103
104                         if (empty($parent)) {
105                                 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
106                                 self::setFailedQueue($cmd, $target_item);
107                                 return;
108                         }
109
110                         if (!empty($target_item['contact-uid'])) {
111                                 $uid = $target_item['contact-uid'];
112                         } elseif (!empty($target_item['uid'])) {
113                                 $uid = $target_item['uid'];
114                         } else {
115                                 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
116                                 self::setFailedQueue($cmd, $target_item);
117                                 return;
118                         }
119
120                         $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
121                         $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
122                         if (!DBA::isResult($thr_parent)) {
123                                 // Shouldn't happen. But when this does, we just take the parent as thread parent.
124                                 // That's totally okay for what we use this variable here.
125                                 $thr_parent = $parent;
126                         }
127
128                         if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
129                                 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
130                                 self::setFailedQueue($cmd, $target_item);
131                                 return;
132                         }
133
134                         // avoid race condition with deleting entries
135                         if ($items[0]['deleted']) {
136                                 foreach ($items as $item) {
137                                         $item['deleted'] = 1;
138                                 }
139                         }
140
141                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
142                         // The count then showed more than one entry. The additional check should help.
143                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
144                         if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
145                                 Logger::log('Top level post');
146                                 $top_level = true;
147                         }
148
149                         // This is IMPORTANT!!!!
150
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.
156
157                         $localhost = DI::baseUrl()->getHostname();
158                         if (strpos($localhost, ':')) {
159                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
160                         }
161                         /**
162                          *
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.
166                          *
167                          */
168
169                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
170                                 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
171                                 // local followup to remote post
172                                 $followup = true;
173                         }
174
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;
181                         }
182                 }
183
184                 if (empty($items)) {
185                         Logger::log('No delivery data for  ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
186                 }
187
188                 $owner = Model\User::getOwnerDataById($uid);
189                 if (!DBA::isResult($owner)) {
190                         self::setFailedQueue($cmd, $target_item);
191                         return;
192                 }
193
194                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
195                 $contact = DBA::selectFirst('contact', [],
196                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
197                 );
198                 if (!DBA::isResult($contact)) {
199                         self::setFailedQueue($cmd, $target_item);
200                         return;
201                 }
202
203                 if (Network::isUrlBlocked($contact['url'])) {
204                         self::setFailedQueue($cmd, $target_item);
205                         return;
206                 }
207
208                 // Transmit via Diaspora if the thread had started as Diaspora post.
209                 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
210                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
211                 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
212                         $contact['network'] = Protocol::DIASPORA;
213                 }
214
215                 // Ensure that local contacts are delivered locally
216                 if (Model\Contact::isLocal($contact['url'])) {
217                         $contact['network'] = Protocol::DFRN;
218                 }
219
220                 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
221
222                 switch ($contact['network']) {
223                         case Protocol::DFRN:
224                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
225                                 break;
226
227                         case Protocol::DIASPORA:
228                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
229                                 break;
230
231                         case Protocol::MAIL:
232                                 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
233                                 break;
234
235                         default:
236                                 break;
237                 }
238
239                 return;
240         }
241
242         /**
243          * Increased the "failed" counter in the item delivery data
244          *
245          * @param string $cmd  Command
246          * @param array  $item Item array
247          */
248         private static function setFailedQueue(string $cmd, array $item)
249         {
250                 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
251                         return;
252                 }
253
254                 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
255         }
256
257         /**
258          * Deliver content via DFRN
259          *
260          * @param string  $cmd            Command
261          * @param array   $contact        Contact record of the receiver
262          * @param array   $owner          Owner record of the sender
263          * @param array   $items          Item record of the content and the parent
264          * @param array   $target_item    Item record of the content
265          * @param boolean $public_message Is the content public?
266          * @param boolean $top_level      Is it a thread starter?
267          * @param boolean $followup       Is it an answer to a remote post?
268          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269          * @throws \ImagickException
270          */
271         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
272         {
273                 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
274                 if (Diaspora::isReshare($target_item['body']) && !empty(Diaspora::personByHandle($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);
277                         return;
278                 }
279
280                 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
281
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                         DBA::delete('fsuggest', ['id' => $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);
295                 } else {
296                         $msgitems = [];
297                         foreach ($items as $item) {
298                                 // Only add the parent when we don't delete other items.
299                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
300                                         $item["entry:comment-allow"] = true;
301                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
302                                         $msgitems[] = $item;
303                                 }
304                         }
305                         $atom = DFRN::entries($msgitems, $owner);
306                 }
307
308                 Logger::debug('Notifier entry: ' . $contact["url"] . ' ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' entry: ' . $atom);
309
310                 // perform local delivery if we are on the same site
311                 if (Model\Contact::isLocal($contact['url'])) {
312                         $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
313                         $target_self = DBA::selectFirst('contact', ['uid'], $condition);
314                         if (!DBA::isResult($target_self)) {
315                                 return;
316                         }
317                         $target_uid = $target_self['uid'];
318
319                         // Check if the user has got this contact
320                         $cid = Model\Contact::getIdForURL($owner['url'], $target_uid);
321                         if (!$cid) {
322                                 // Otherwise there should be a public contact
323                                 $cid = Model\Contact::getIdForURL($owner['url']);
324                                 if (!$cid) {
325                                         return;
326                                 }
327                         }
328
329                         $target_importer = DFRN::getImporter($cid, $target_uid);
330                         if (empty($target_importer)) {
331                                 // This should never happen
332                                 return;
333                         }
334
335                         DFRN::import($atom, $target_importer);
336
337                         if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
338                                 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DFRN);
339                         }
340
341                         return;
342                 }
343
344                 $protocol = Model\Post\DeliveryData::DFRN;
345
346                 // We don't have a relationship with contacts on a public post.
347                 // Se we transmit with the new method and via Diaspora as a fallback
348                 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
349                         // Transmit in public if it's a relay post
350                         $public_dfrn = ($contact['contact-type'] == Model\Contact::TYPE_RELAY);
351
352                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
353
354                         // We never spool failed relay deliveries
355                         if ($public_dfrn) {
356                                 Logger::info('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
357
358                                 if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
359                                         if (($deliver_status >= 200) && ($deliver_status <= 299)) {
360                                                 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
361                                         } else {
362                                                 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
363                                         }
364                                 }
365                                 return;
366                         }
367
368                         if (($deliver_status < 200) || ($deliver_status > 299)) {
369                                 // Transmit via Diaspora if not possible via Friendica
370                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
371                                 return;
372                         }
373                 } elseif ($cmd != self::RELOCATION) {
374                         // DFRN payload over Diaspora transport layer
375                         $deliver_status = DFRN::transmit($owner, $contact, $atom);
376                         if ($deliver_status < 200) {
377                                 // Legacy DFRN
378                                 $deliver_status = DFRN::deliver($owner, $contact, $atom);
379                                 $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
380                         }
381                 } else {
382                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
383                         $protocol = Model\Post\DeliveryData::LEGACY_DFRN;
384                 }
385
386                 Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id'], 'return' => $deliver_status]);
387
388                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
389                         // We successfully delivered a message, the contact is alive
390                         Model\Contact::unmarkForArchival($contact);
391
392                         if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
393                                 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], $protocol);
394                         }
395                 } else {
396                         // The message could not be delivered. We mark the contact as "dead"
397                         Model\Contact::markForArchival($contact);
398
399                         Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
400                         if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
401                                 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
402                         }
403                 }
404         }
405
406         /**
407          * Deliver content via Diaspora
408          *
409          * @param string  $cmd            Command
410          * @param array   $contact        Contact record of the receiver
411          * @param array   $owner          Owner record of the sender
412          * @param array   $items          Item record of the content and the parent
413          * @param array   $target_item    Item record of the content
414          * @param boolean $public_message Is the content public?
415          * @param boolean $top_level      Is it a thread starter?
416          * @param boolean $followup       Is it an answer to a remote post?
417          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418          * @throws \ImagickException
419          */
420         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
421         {
422                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
423                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
424
425                 if ($public_message) {
426                         $loc = 'public batch ' . $contact['batch'];
427                 } else {
428                         $loc = $contact['addr'];
429                 }
430
431                 Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]);
432
433                 if (DI::config()->get('system', 'dfrn_only') || !DI::config()->get('system', 'diaspora_enabled')) {
434                         return;
435                 }
436
437                 if ($cmd == self::MAIL) {
438                         Diaspora::sendMail($target_item, $owner, $contact);
439                         return;
440                 }
441
442                 if ($cmd == self::SUGGESTION) {
443                         return;
444                 }
445
446                 if (!$contact['pubkey'] && !$public_message) {
447                         return;
448                 }
449
450                 if ($cmd == self::RELOCATION) {
451                         $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
452                 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
453                         // top-level retraction
454                         Logger::log('diaspora retract: ' . $loc);
455                         $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
456                 } elseif ($followup) {
457                         // send comments and likes to owner to relay
458                         Logger::log('diaspora followup: ' . $loc);
459                         $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
460                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
461                         // we are the relay - send comments, likes and relayable_retractions to our conversants
462                         Logger::log('diaspora relay: ' . $loc);
463                         $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
464                 } elseif ($top_level && !$walltowall) {
465                         // currently no workable solution for sending walltowall
466                         Logger::log('diaspora status: ' . $loc);
467                         $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
468                 } else {
469                         Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
470                         return;
471                 }
472
473                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
474                         // We successfully delivered a message, the contact is alive
475                         Model\Contact::unmarkForArchival($contact);
476
477                         if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
478                                 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::DIASPORA);
479                         }
480                 } else {
481                         // The message could not be delivered. We mark the contact as "dead"
482                         Model\Contact::markForArchival($contact);
483
484                         // When it is delivered to the public endpoint, we do mark the relay contact for archival as well
485                         if ($public_message) {
486                                 Diaspora::markRelayForArchival($contact);
487                         }
488
489                         if (empty($contact['contact-type']) || ($contact['contact-type'] != Model\Contact::TYPE_RELAY)) {
490                                 Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
491                                 // defer message for redelivery
492                                 if (!Worker::defer() && in_array($cmd, [Delivery::POST, Delivery::POKE])) {
493                                         Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
494                                 }
495                         } elseif (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
496                                 Model\Post\DeliveryData::incrementQueueFailed($target_item['uri-id']);
497                         }
498                 }
499         }
500
501         /**
502          * Deliver content via mail
503          *
504          * @param string $cmd         Command
505          * @param array  $contact     Contact record of the receiver
506          * @param array  $owner       Owner record of the sender
507          * @param array  $target_item Item record of the content
508          * @param array  $thr_parent  Item record of the direct parent in the thread
509          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
510          * @throws \ImagickException
511          */
512         private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent)
513         {
514                 if (DI::config()->get('system','dfrn_only')) {
515                         return;
516                 }
517
518                 $addr = $contact['addr'];
519                 if (!strlen($addr)) {
520                         return;
521                 }
522
523                 if (!in_array($cmd, [self::POST, self::POKE])) {
524                         return;
525                 }
526
527                 if ($target_item['verb'] != Activity::POST) {
528                         return;
529                 }
530
531                 if (!empty($thr_parent['object'])) {
532                         $data = json_decode($thr_parent['object'], true);
533                         if (!empty($data['reply_to'])) {
534                                 $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host'];
535                                 Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]);
536                         } elseif (!empty($data['from'])) {
537                                 $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host'];
538                                 Logger::info('Use "from" address of the thread parent', ['addr' => $addr]);
539                         }
540                 }
541
542                 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
543                 if (!DBA::isResult($local_user)) {
544                         return;
545                 }
546
547                 Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]);
548
549                 $reply_to = '';
550                 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
551                 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
552                         $reply_to = $mailacct['reply_to'];
553                 }
554
555                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : DI::l10n()->t("\x28no subject\x29"));
556
557                 // only expose our real email address to true friends
558
559                 if (($contact['rel'] == Model\Contact::FRIEND) && !$contact['blocked']) {
560                         if ($reply_to) {
561                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
562                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
563                         } else {
564                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n";
565                         }
566                 } else {
567                         $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHostname());
568                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $sender . '>' . "\n";
569                 }
570
571                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
572
573                 if ($target_item['uri'] !== $target_item['parent-uri']) {
574                         $headers .= 'References: <' . Email::iri2msgid($target_item['parent-uri']) . '>';
575
576                         // Export more references on deeper nested threads
577                         if (($target_item['thr-parent'] != '') && ($target_item['thr-parent'] != $target_item['parent-uri'])) {
578                                 $headers .= ' <' . Email::iri2msgid($target_item['thr-parent']) . '>';
579                         }
580
581                         $headers .= "\n";
582
583                         if (empty($target_item['title'])) {
584                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
585                                 $title = Model\Item::selectFirst(['title'], $condition);
586
587                                 if (DBA::isResult($title) && ($title['title'] != '')) {
588                                         $subject = $title['title'];
589                                 } else {
590                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
591                                         $title = Model\Item::selectFirst(['title'], $condition);
592
593                                         if (DBA::isResult($title) && ($title['title'] != '')) {
594                                                 $subject = $title['title'];
595                                         }
596                                 }
597                         }
598
599                         if (strncasecmp($subject, 'RE:', 3)) {
600                                 $subject = 'Re: ' . $subject;
601                         }
602                 }
603
604                 Email::send($addr, $subject, $headers, $target_item);
605
606                 Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
607
608                 Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);
609         }
610 }