]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Don't transmit to archived inboxes
[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\FContact;
37 use Friendica\Protocol\Relay;
38
39 class Delivery
40 {
41         const MAIL          = 'mail';
42         const SUGGESTION    = 'suggest';
43         const RELOCATION    = 'relocate';
44         const DELETION      = 'drop';
45         const POST          = 'wall-new';
46         const POKE          = 'poke';
47         const UPLINK        = 'uplink';
48         const REMOVAL       = 'removeme';
49         const PROFILEUPDATE = 'profileupdate';
50
51         public static function execute($cmd, $target_id, $contact_id)
52         {
53                 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $target_id, 'contact' => $contact_id]);
54
55                 $top_level = false;
56                 $followup = false;
57                 $public_message = false;
58
59                 $items = [];
60                 if ($cmd == self::MAIL) {
61                         $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
62                         if (!DBA::isResult($target_item)) {
63                                 return;
64                         }
65                         $uid = $target_item['uid'];
66                 } elseif ($cmd == self::SUGGESTION) {
67                         $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
68                         if (!DBA::isResult($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                                 return;
79                         }
80                         $parent_id = intval($item['parent']);
81
82                         $condition = ['id' => [$target_id, $parent_id], 'visible' => true, 'moderated' => false];
83                         $params = ['order' => ['id']];
84                         $itemdata = Model\Item::select([], $condition, $params);
85
86                         while ($item = Model\Item::fetch($itemdata)) {
87                                 if ($item['verb'] == Activity::ANNOUNCE) {
88                                         continue;
89                                 }
90         
91                                 if ($item['id'] == $parent_id) {
92                                         $parent = $item;
93                                 }
94                                 if ($item['id'] == $target_id) {
95                                         $target_item = $item;
96                                 }
97                                 $items[] = $item;
98                         }
99                         DBA::close($itemdata);
100
101                         if (empty($target_item)) {
102                                 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
103                                 return;
104                         }
105
106                         if (empty($parent)) {
107                                 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
108                                 self::setFailedQueue($cmd, $target_item);
109                                 return;
110                         }
111
112                         if (!empty($target_item['contact-uid'])) {
113                                 $uid = $target_item['contact-uid'];
114                         } elseif (!empty($target_item['uid'])) {
115                                 $uid = $target_item['uid'];
116                         } else {
117                                 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
118                                 self::setFailedQueue($cmd, $target_item);
119                                 return;
120                         }
121
122                         $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
123                         $thr_parent = Model\Item::selectFirst(['network', 'object'], $condition);
124                         if (!DBA::isResult($thr_parent)) {
125                                 // Shouldn't happen. But when this does, we just take the parent as thread parent.
126                                 // That's totally okay for what we use this variable here.
127                                 $thr_parent = $parent;
128                         }
129
130                         if (!empty($contact_id) && Model\Contact::isArchived($contact_id)) {
131                                 Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]);
132                                 self::setFailedQueue($cmd, $target_item);
133                                 return;
134                         }
135
136                         // avoid race condition with deleting entries
137                         if ($items[0]['deleted']) {
138                                 foreach ($items as $item) {
139                                         $item['deleted'] = 1;
140                                 }
141                         }
142
143                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
144                         // The count then showed more than one entry. The additional check should help.
145                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
146                         if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
147                                 Logger::log('Top level post');
148                                 $top_level = true;
149                         }
150
151                         // This is IMPORTANT!!!!
152
153                         // We will only send a "notify owner to relay" or followup message if the referenced post
154                         // originated on our system by virtue of having our hostname somewhere
155                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
156                         // if $parent['wall'] == 1 we will already have the parent message in our array
157                         // and we will relay the whole lot.
158
159                         $localhost = DI::baseUrl()->getHostname();
160                         if (strpos($localhost, ':')) {
161                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
162                         }
163                         /**
164                          *
165                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
166                          * have been known to cause runaway conditions which affected several servers, along with
167                          * permissions issues.
168                          *
169                          */
170
171                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
172                                 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
173                                 // local followup to remote post
174                                 $followup = true;
175                         }
176
177                         if (empty($parent['allow_cid'])
178                                 && empty($parent['allow_gid'])
179                                 && empty($parent['deny_cid'])
180                                 && empty($parent['deny_gid'])
181                                 && ($parent["private"] != Model\Item::PRIVATE)) {
182                                 $public_message = true;
183                         }
184                 }
185
186                 if (empty($items)) {
187                         Logger::log('No delivery data for  ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
188                 }
189
190                 $owner = Model\User::getOwnerDataById($uid);
191                 if (!DBA::isResult($owner)) {
192                         self::setFailedQueue($cmd, $target_item);
193                         return;
194                 }
195
196                 // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either
197                 $contact = DBA::selectFirst('contact', [],
198                         ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false]
199                 );
200                 if (!DBA::isResult($contact)) {
201                         self::setFailedQueue($cmd, $target_item);
202                         return;
203                 }
204
205                 if (Network::isUrlBlocked($contact['url'])) {
206                         self::setFailedQueue($cmd, $target_item);
207                         return;
208                 }
209
210                 // Transmit via Diaspora if the thread had started as Diaspora post.
211                 // Also transmit via Diaspora if this is a direct answer to a Diaspora comment.
212                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
213                 if (!empty($parent) && !empty($thr_parent) && in_array(Protocol::DIASPORA, [$parent['network'], $thr_parent['network']])) {
214                         $contact['network'] = Protocol::DIASPORA;
215                 }
216
217                 // Ensure that local contacts are delivered locally
218                 if (Model\Contact::isLocal($contact['url'])) {
219                         $contact['network'] = Protocol::DFRN;
220                 }
221
222                 Logger::notice('Delivering', ['cmd' => $cmd, 'target' => $target_id, 'followup' => $followup, 'network' => $contact['network']]);
223
224                 switch ($contact['network']) {
225                         case Protocol::DFRN:
226                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
227                                 break;
228
229                         case Protocol::DIASPORA:
230                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
231                                 break;
232
233                         case Protocol::MAIL:
234                                 self::deliverMail($cmd, $contact, $owner, $target_item, $thr_parent);
235                                 break;
236
237                         default:
238                                 break;
239                 }
240
241                 return;
242         }
243
244         /**
245          * Increased the "failed" counter in the item delivery data
246          *
247          * @param string $cmd  Command
248          * @param array  $item Item array
249          */
250         private static function setFailedQueue(string $cmd, array $item)
251         {
252                 if (!in_array($cmd, [Delivery::POST, Delivery::POKE])) {
253                         return;
254                 }
255
256                 Model\Post\DeliveryData::incrementQueueFailed($item['uri-id'] ?? $item['id']);
257         }
258
259         /**
260          * Deliver content via DFRN
261          *
262          * @param string  $cmd            Command
263          * @param array   $contact        Contact record of the receiver
264          * @param array   $owner          Owner record of the sender
265          * @param array   $items          Item record of the content and the parent
266          * @param array   $target_item    Item record of the content
267          * @param boolean $public_message Is the content public?
268          * @param boolean $top_level      Is it a thread starter?
269          * @param boolean $followup       Is it an answer to a remote post?
270          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271          * @throws \ImagickException
272          */
273         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
274         {
275                 // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
276                 if (Diaspora::isReshare($target_item['body']) && !empty(FContact::getByURL($contact['addr'], false))) {
277                         Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => ($target_item['guid'] ?? '') ?: $target_item['id']]);
278                         self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
279                         return;
280                 }
281
282                 Logger::info('Deliver ' . (($target_item['guid'] ?? '') ?: $target_item['id']) . ' via DFRN to ' . (($contact['addr'] ?? '') ?: $contact['url']));
283
284                 if ($cmd == self::MAIL) {
285                         $item = $target_item;
286                         $item['body'] = Model\Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
287                         $atom = DFRN::mail($item, $owner);
288                 } elseif ($cmd == self::SUGGESTION) {
289                         $item = $target_item;
290                         $atom = DFRN::fsuggest($item, $owner);
291                         DBA::delete('fsuggest', ['id' => $item['id']]);
292                 } elseif ($cmd == self::RELOCATION) {
293                         $atom = DFRN::relocate($owner, $owner['uid']);
294                 } elseif ($followup) {
295                         $msgitems = [$target_item];
296                         $atom = DFRN::entries($msgitems, $owner);
297                 } else {
298                         $msgitems = [];
299                         foreach ($items as $item) {
300                                 // Only add the parent when we don't delete other items.
301                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
302                                         $item["entry:comment-allow"] = true;
303                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
304                                         $msgitems[] = $item;
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);
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 }