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