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