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