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