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