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