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