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