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