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