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