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