]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Merge pull request #5877 from annando/issue-5859
[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\Diaspora;
19 use Friendica\Protocol\Email;
20
21 require_once 'include/items.php';
22
23 class Delivery extends BaseObject
24 {
25         const MAIL          = 'mail';
26         const SUGGESTION    = 'suggest';
27         const RELOCATION    = 'relocate';
28         const DELETION      = 'drop';
29         const POST          = 'wall-new';
30         const COMMENT       = 'comment-new';
31         const REMOVAL       = 'removeme';
32         const PROFILEUPDATE = 'profileupdate';
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()->getHostName();
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::DFRN:
170                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
171                                 break;
172
173                         case Protocol::DIASPORA:
174                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
175                                 break;
176
177                         case Protocol::OSTATUS:
178                                 // Do not send to otatus if we are not configured to send to public networks
179                                 if ($owner['prvnets']) {
180                                         break;
181                                 }
182                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
183                                         break;
184                                 }
185
186                                 // There is currently no code here to distribute anything to OStatus.
187                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
188                                 break;
189
190                         case Protocol::MAIL:
191                                 self::deliverMail($cmd, $contact, $owner, $target_item);
192                                 break;
193
194                         default:
195                                 break;
196                 }
197
198                 return;
199         }
200
201         /**
202          * @brief Deliver content via DFRN
203          *
204          * @param string  $cmd            Command
205          * @param array   $contact        Contact record of the receiver
206          * @param array   $owner          Owner record of the sender
207          * @param array   $items          Item record of the content and the parent
208          * @param array   $target_item    Item record of the content
209          * @param boolean $public_message Is the content public?
210          * @param boolean $top_level      Is it a thread starter?
211          * @param boolean $followup       Is it an answer to a remote post?
212          */
213         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
214         {
215                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
216
217                 if ($cmd == self::MAIL) {
218                         $item = $target_item;
219                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
220                         $atom = DFRN::mail($item, $owner);
221                 } elseif ($cmd == self::SUGGESTION) {
222                         $item = $target_item;
223                         $atom = DFRN::fsuggest($item, $owner);
224                         DBA::delete('fsuggest', ['id' => $item['id']]);
225                 } elseif ($cmd == self::RELOCATION) {
226                         $atom = DFRN::relocate($owner, $owner['uid']);
227                 } elseif ($followup) {
228                         $msgitems = [$target_item];
229                         $atom = DFRN::entries($msgitems, $owner);
230                 } else {
231                         $msgitems = [];
232                         foreach ($items as $item) {
233                                 // Only add the parent when we don't delete other items.
234                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
235                                         $item["entry:comment-allow"] = true;
236                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
237                                         $msgitems[] = $item;
238                                 }
239                         }
240                         $atom = DFRN::entries($msgitems, $owner);
241                 }
242
243                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
244
245                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
246
247                 // perform local delivery if we are on the same site
248
249                 if (link_compare($basepath, System::baseUrl())) {
250                         $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
251                         $target_self = DBA::selectFirst('contact', ['uid'], $condition);
252                         if (!DBA::isResult($target_self)) {
253                                 return;
254                         }
255                         $target_uid = $target_self['uid'];
256
257                         // Check if the user has got this contact
258                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
259                         if (!$cid) {
260                                 // Otherwise there should be a public contact
261                                 $cid = Contact::getIdForURL($owner['url']);
262                                 if (!$cid) {
263                                         return;
264                                 }
265                         }
266
267                         $target_importer = DFRN::getImporter($cid, $target_uid);
268                         if (empty($target_importer)) {
269                                 // This should never happen
270                                 return;
271                         }
272
273                         DFRN::import($atom, $target_importer);
274                         return;
275                 }
276
277                 // We don't have a relationship with contacts on a public post.
278                 // Se we transmit with the new method and via Diaspora as a fallback
279                 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
280                         // Transmit in public if it's a relay post
281                         $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
282
283                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
284
285                         // We never spool failed relay deliveries
286                         if ($public_dfrn) {
287                                 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
288                                 return;
289                         }
290
291                         if (($deliver_status < 200) || ($deliver_status > 299)) {
292                                 // Transmit via Diaspora if not possible via Friendica
293                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
294                                 return;
295                         }
296                 } elseif ($cmd != self::RELOCATION) {
297                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
298                 } else {
299                         $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
300                 }
301
302                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
303
304                 if ($deliver_status < 0) {
305                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
306                         Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
307                 }
308
309                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
310                         // We successfully delivered a message, the contact is alive
311                         Contact::unmarkForArchival($contact);
312                 } else {
313                         // The message could not be delivered. We mark the contact as "dead"
314                         Contact::markForArchival($contact);
315
316                         // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
317                         // This is a fallback for systems that don't know the new methods.
318                         self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
319                 }
320         }
321
322         /**
323          * @brief Deliver content via Diaspora
324          *
325          * @param string  $cmd            Command
326          * @param array   $contact        Contact record of the receiver
327          * @param array   $owner          Owner record of the sender
328          * @param array   $items          Item record of the content and the parent
329          * @param array   $target_item    Item record of the content
330          * @param boolean $public_message Is the content public?
331          * @param boolean $top_level      Is it a thread starter?
332          * @param boolean $followup       Is it an answer to a remote post?
333          */
334         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
335         {
336                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
337                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
338
339                 if ($public_message) {
340                         $loc = 'public batch ' . $contact['batch'];
341                 } else {
342                         $loc = $contact['addr'];
343                 }
344
345                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
346
347                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
348                         return;
349                 }
350                 if ($cmd == self::MAIL) {
351                         Diaspora::sendMail($target_item, $owner, $contact);
352                         return;
353                 }
354
355                 if ($cmd == self::SUGGESTION) {
356                         return;
357                 }
358                 if (!$contact['pubkey'] && !$public_message) {
359                         return;
360                 }
361                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
362                         // top-level retraction
363                         logger('diaspora retract: ' . $loc);
364                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
365                         return;
366                 } elseif ($cmd == self::RELOCATION) {
367                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
368                         return;
369                 } elseif ($followup) {
370                         // send comments and likes to owner to relay
371                         logger('diaspora followup: ' . $loc);
372                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
373                         return;
374                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
375                         // we are the relay - send comments, likes and relayable_retractions to our conversants
376                         logger('diaspora relay: ' . $loc);
377                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
378                         return;
379                 } elseif ($top_level && !$walltowall) {
380                         // currently no workable solution for sending walltowall
381                         logger('diaspora status: ' . $loc);
382                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
383                         return;
384                 }
385
386                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
387         }
388
389         /**
390          * @brief Deliver content via mail
391          *
392          * @param string $cmd         Command
393          * @param array  $contact     Contact record of the receiver
394          * @param array  $owner       Owner record of the sender
395          * @param array  $target_item Item record of the content
396          */
397         private static function deliverMail($cmd, $contact, $owner, $target_item)
398         {
399                 if (Config::get('system','dfrn_only')) {
400                         return;
401                 }
402                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
403
404                 $addr = $contact['addr'];
405                 if (!strlen($addr)) {
406                         return;
407                 }
408
409                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
410                         return;
411                 }
412
413                 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
414                 if (!DBA::isResult($local_user)) {
415                         return;
416                 }
417
418                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
419
420                 $reply_to = '';
421                 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
422                 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
423                         $reply_to = $mailacct['reply_to'];
424                 }
425
426                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
427
428                 // only expose our real email address to true friends
429
430                 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
431                         if ($reply_to) {
432                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
433                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
434                         } else {
435                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
436                         }
437                 } else {
438                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
439                 }
440
441                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
442
443                 if ($target_item['uri'] !== $target_item['parent-uri']) {
444                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
445
446                         // If Threading is enabled, write down the correct parent
447                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
448                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
449                         }
450
451                         $headers .= "\n";
452
453                         if (empty($target_item['title'])) {
454                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
455                                 $title = Item::selectFirst(['title'], $condition);
456
457                                 if (DBA::isResult($title) && ($title['title'] != '')) {
458                                         $subject = $title['title'];
459                                 } else {
460                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
461                                         $title = Item::selectFirst(['title'], $condition);
462
463                                         if (DBA::isResult($title) && ($title['title'] != '')) {
464                                                 $subject = $title['title'];
465                                         }
466                                 }
467                         }
468
469                         if (strncasecmp($subject, 'RE:', 3)) {
470                                 $subject = 'Re: ' . $subject;
471                         }
472                 }
473
474                 Email::send($addr, $subject, $headers, $target_item);
475         }
476 }