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