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