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