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