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