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