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