]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Move remaining functions
[friendica.git] / src / Worker / Delivery.php
1 <?php
2 /**
3  * @file src/Worker/Delivery.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\App;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Queue;
14 use Friendica\Model\User;
15 use Friendica\Protocol\Diaspora;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Email;
18 use Friendica\Util\Network;
19 use dba;
20
21 require_once 'include/html2plain.php';
22 require_once 'include/datetime.php';
23 require_once 'include/items.php';
24 require_once 'include/bbcode.php';
25
26 /// @todo This is some ugly code that needs to be split into several methods
27
28 class Delivery {
29         public static function execute($cmd, $item_id, $contact_id) {
30                 global $a;
31
32                 logger('delivery: invoked: '.$cmd.': '.$item_id.' to '.$contact_id, LOGGER_DEBUG);
33
34                 $mail = false;
35                 $fsuggest = false;
36                 $relocate = false;
37                 $top_level = false;
38                 $recipients = [];
39                 $url_recipients = [];
40                 $followup = false;
41
42                 $normal_mode = true;
43
44                 $recipients[] = $contact_id;
45
46                 if ($cmd === 'mail') {
47                         $normal_mode = false;
48                         $mail = true;
49                         $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
50                                         intval($item_id)
51                         );
52                         if (!count($message)) {
53                                 return;
54                         }
55                         $uid = $message[0]['uid'];
56                         $recipients[] = $message[0]['contact-id'];
57                         $item = $message[0];
58                 } elseif ($cmd === 'suggest') {
59                         $normal_mode = false;
60                         $fsuggest = true;
61
62                         $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
63                                 intval($item_id)
64                         );
65                         if (!count($suggest)) {
66                                 return;
67                         }
68                         $uid = $suggest[0]['uid'];
69                         $recipients[] = $suggest[0]['cid'];
70                         $item = $suggest[0];
71                 } elseif ($cmd === 'relocate') {
72                         $normal_mode = false;
73                         $relocate = true;
74                         $uid = $item_id;
75                 } else {
76                         // find ancestors
77                         $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
78                                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
79                                                         WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
80
81                         if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
82                                 return;
83                         }
84
85                         $parent_id = intval($target_item['parent']);
86                         $uid = $target_item['cuid'];
87                         $updated = $target_item['edited'];
88
89                         $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
90                                 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
91                                 intval($parent_id)
92                         );
93
94                         if (!count($items)) {
95                                 return;
96                         }
97
98                         $icontacts = null;
99                         $contacts_arr = [];
100                         foreach ($items as $item) {
101                                 if (!in_array($item['contact-id'],$contacts_arr)) {
102                                         $contacts_arr[] = intval($item['contact-id']);
103                                 }
104                         }
105                         if (count($contacts_arr)) {
106                                 $str_contacts = implode(',',$contacts_arr);
107                                 $icontacts = q("SELECT * FROM `contact`
108                                         WHERE `id` IN ( $str_contacts ) "
109                                 );
110                         }
111                         if ( !($icontacts && count($icontacts))) {
112                                 return;
113                         }
114
115                         // avoid race condition with deleting entries
116
117                         if ($items[0]['deleted']) {
118                                 foreach ($items as $item) {
119                                         $item['deleted'] = 1;
120                                 }
121                         }
122
123                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
124                         // The count then showed more than one entry. The additional check should help.
125                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
126                         if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
127                                 logger('delivery: top level post');
128                                 $top_level = true;
129                         }
130                 }
131
132                 $owner = User::getOwnerDataById($uid);
133                 if (!$owner) {
134                         return;
135                 }
136
137                 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
138
139                 $public_message = true;
140
141                 if (!$mail && !$fsuggest && !$relocate) {
142                         $parent = $items[0];
143
144                         // This is IMPORTANT!!!!
145
146                         // We will only send a "notify owner to relay" or followup message if the referenced post
147                         // originated on our system by virtue of having our hostname somewhere
148                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
149                         // if $parent['wall'] == 1 we will already have the parent message in our array
150                         // and we will relay the whole lot.
151
152                         $localhost = $a->get_hostname();
153                         if (strpos($localhost,':')) {
154                                 $localhost = substr($localhost,0,strpos($localhost,':'));
155                         }
156                         /**
157                          *
158                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
159                          * have been known to cause runaway conditions which affected several servers, along with
160                          * permissions issues.
161                          *
162                          */
163
164                         $relay_to_owner = false;
165
166                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
167                                 $relay_to_owner = true;
168                         }
169
170                         if ($relay_to_owner) {
171                                 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
172                                 // local followup to remote post
173                                 $followup = true;
174                         }
175
176                         if (strlen($parent['allow_cid'])
177                                 || strlen($parent['allow_gid'])
178                                 || strlen($parent['deny_cid'])
179                                 || strlen($parent['deny_gid'])
180                                 || $parent["private"]) {
181                                 $public_message = false; // private recipients, not public
182                         }
183
184                 }
185
186                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
187                         intval($contact_id)
188                 );
189
190                 if (DBM::is_result($r)) {
191                         $contact = $r[0];
192                 }
193                 if ($contact['self']) {
194                         return;
195                 }
196                 $deliver_status = 0;
197
198                 // Transmit via Diaspora if not possible via Friendica
199                 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
200                         $contact['network'] = NETWORK_DIASPORA;
201                 }
202
203                 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
204
205                 switch ($contact['network']) {
206
207                         case NETWORK_DFRN:
208                                 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
209
210                                 if ($mail) {
211                                         $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
212                                         $atom = DFRN::mail($item, $owner);
213                                 } elseif ($fsuggest) {
214                                         $atom = DFRN::fsuggest($item, $owner);
215                                         q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
216                                 } elseif ($relocate) {
217                                         $atom = DFRN::relocate($owner, $uid);
218                                 } elseif ($followup) {
219                                         $msgitems = [];
220                                         foreach ($items as $item) {  // there is only one item
221                                                 if (!$item['parent']) {
222                                                         return;
223                                                 }
224                                                 if ($item['id'] == $item_id) {
225                                                         logger('followup: item: '. print_r($item,true), LOGGER_DATA);
226                                                         $msgitems[] = $item;
227                                                 }
228                                         }
229                                         $atom = DFRN::entries($msgitems,$owner);
230                                 } else {
231                                         $msgitems = [];
232                                         foreach ($items as $item) {
233                                                 if (!$item['parent']) {
234                                                         return;
235                                                 }
236
237                                                 // private emails may be in included in public conversations. Filter them.
238                                                 if ($public_message && $item['private']) {
239                                                         return;
240                                                 }
241
242                                                 $item_contact = self::getItemContact($item,$icontacts);
243                                                 if (!$item_contact) {
244                                                         return;
245                                                 }
246
247                                                 if ($normal_mode) {
248                                                         if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
249                                                                 $item["entry:comment-allow"] = true;
250                                                                 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
251                                                                 $msgitems[] = $item;
252                                                         }
253                                                 } else {
254                                                         $item["entry:comment-allow"] = true;
255                                                         $msgitems[] = $item;
256                                                 }
257                                         }
258                                         $atom = DFRN::entries($msgitems,$owner);
259                                 }
260
261                                 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
262
263                                 logger('notifier: '.$atom, LOGGER_DATA);
264                                 $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
265
266                                 // perform local delivery if we are on the same site
267
268                                 if (link_compare($basepath,System::baseUrl())) {
269                                         $nickname = basename($contact['url']);
270                                         if ($contact['issued-id']) {
271                                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
272                                         } else {
273                                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
274                                         }
275
276                                         $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
277                                                 `contact`.`pubkey` AS `cpubkey`,
278                                                 `contact`.`prvkey` AS `cprvkey`,
279                                                 `contact`.`thumb` AS `thumb`,
280                                                 `contact`.`url` as `url`,
281                                                 `contact`.`name` as `senderName`,
282                                                 `user`.*
283                                                 FROM `contact`
284                                                 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
285                                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
286                                                 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
287                                                 $sql_extra
288                                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
289                                                 dbesc(NETWORK_DFRN),
290                                                 dbesc($nickname)
291                                         );
292
293                                         if ($x && count($x)) {
294                                                 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
295                                                 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
296                                                         q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
297                                                                 intval($x[0]['id'])
298                                                         );
299                                                         $x[0]['writable'] = 1;
300                                                 }
301
302                                                 $ssl_policy = Config::get('system','ssl_policy');
303                                                 Network::fixContactSslPolicy($x[0], $ssl_policy);
304
305                                                 // If we are setup as a soapbox we aren't accepting top level posts from this person
306
307                                                 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
308                                                         break;
309                                                 }
310                                                 logger('mod-delivery: local delivery');
311                                                 DFRN::import($atom, $x[0]);
312                                                 break;
313                                         }
314                                 }
315
316                                 if (!Queue::wasDelayed($contact['id'])) {
317                                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
318                                 } else {
319                                         $deliver_status = (-1);
320                                 }
321
322                                 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
323
324                                 if ($deliver_status < 0) {
325                                         logger('notifier: delivery failed: queuing message');
326                                         Queue::add($contact['id'], NETWORK_DFRN, $atom);
327
328                                         // The message could not be delivered. We mark the contact as "dead"
329                                         Contact::markForArchival($contact);
330                                 } else {
331                                         // We successfully delivered a message, the contact is alive
332                                         Contact::unmarkForArchival($contact);
333                                 }
334
335                                 break;
336
337                         case NETWORK_OSTATUS:
338                                 // Do not send to otatus if we are not configured to send to public networks
339                                 if ($owner['prvnets']) {
340                                         break;
341                                 }
342                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
343                                         break;
344                                 }
345
346                                 // There is currently no code here to distribute anything to OStatus.
347                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
348                                 break;
349
350                         case NETWORK_MAIL:
351
352                                 if (Config::get('system','dfrn_only')) {
353                                         break;
354                                 }
355                                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
356
357                                 $addr = $contact['addr'];
358                                 if (!strlen($addr)) {
359                                         break;
360                                 }
361
362                                 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
363                                         $it = null;
364                                         if ($cmd === 'wall-new') {
365                                                 $it = $items[0];
366                                         } else {
367                                                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
368                                                         intval($item_id)
369                                                 );
370                                                 if (DBM::is_result($r)) {
371                                                         $it = $r[0];
372                                                 }
373                                         }
374                                         if (!$it) {
375                                                 break;
376                                         }
377
378                                         $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
379                                                 intval($uid)
380                                         );
381                                         if (!count($local_user)) {
382                                                 break;
383                                         }
384
385                                         $reply_to = '';
386                                         $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
387                                                 intval($uid)
388                                         );
389                                         if ($r1 && $r1[0]['reply_to']) {
390                                                 $reply_to = $r1[0]['reply_to'];
391                                         }
392
393                                         $subject  = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : L10n::t("\x28no subject\x29")) ;
394
395                                         // only expose our real email address to true friends
396
397                                         if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
398                                                 if ($reply_to) {
399                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
400                                                         $headers .= 'Sender: '.$local_user[0]['email']."\n";
401                                                 } else {
402                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
403                                                 }
404                                         } else {
405                                                 $headers  = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. L10n::t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
406                                         }
407
408                                         //if ($reply_to)
409                                         //      $headers .= 'Reply-to: '.$reply_to . "\n";
410
411                                         $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
412
413                                         //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
414                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
415                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
416
417                                         if ($it['uri'] !== $it['parent-uri']) {
418                                                 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
419
420                                                 // If Threading is enabled, write down the correct parent
421                                                 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
422                                                         $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
423                                                 }
424                                                 $headers .= "\n";
425
426                                                 if (!$it['title']) {
427                                                         $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
428                                                                 dbesc($it['parent-uri']),
429                                                                 intval($uid));
430
431                                                         if (DBM::is_result($r) && ($r[0]['title'] != '')) {
432                                                                 $subject = $r[0]['title'];
433                                                         } else {
434                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
435                                                                         dbesc($it['parent-uri']),
436                                                                         intval($uid));
437
438                                                                 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
439                                                                         $subject = $r[0]['title'];
440                                                                 }
441                                                         }
442                                                 }
443                                                 if (strncasecmp($subject,'RE:',3)) {
444                                                         $subject = 'Re: '.$subject;
445                                                 }
446                                         }
447                                         Email::send($addr, $subject, $headers, $it);
448                                 }
449                                 break;
450
451                         case NETWORK_DIASPORA:
452                                 if ($public_message) {
453                                         $loc = 'public batch '.$contact['batch'];
454                                 } else {
455                                         $loc = $contact['name'];
456                                 }
457
458                                 logger('delivery: diaspora batch deliver: '.$loc);
459
460                                 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
461                                         break;
462                                 }
463                                 if ($mail) {
464                                         Diaspora::sendMail($item,$owner,$contact);
465                                         break;
466                                 }
467
468                                 if (!$normal_mode) {
469                                         break;
470                                 }
471                                 if (!$contact['pubkey'] && !$public_message) {
472                                         break;
473                                 }
474                                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
475                                         // top-level retraction
476                                         logger('diaspora retract: '.$loc);
477                                         Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
478                                         break;
479                                 } elseif ($relocate) {
480                                         Diaspora::sendAccountMigration($owner, $contact, $uid);
481                                         break;
482                                 } elseif ($followup) {
483                                         // send comments and likes to owner to relay
484                                         logger('diaspora followup: '.$loc);
485                                         Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
486                                         break;
487                                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
488                                         // we are the relay - send comments, likes and relayable_retractions to our conversants
489                                         logger('diaspora relay: '.$loc);
490                                         Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
491                                         break;
492                                 } elseif ($top_level && !$walltowall) {
493                                         // currently no workable solution for sending walltowall
494                                         logger('diaspora status: '.$loc);
495                                         Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
496                                         break;
497                                 }
498
499                                 logger('delivery: diaspora unknown mode: '.$contact['name']);
500
501                                 break;
502
503                         default:
504                                 break;
505                 }
506
507                 return;
508         }
509
510         private static function getItemContact($item, $contacts)
511         {
512                 if (!count($contacts) || !is_array($item)) {
513                         return false;
514                 }
515                 foreach ($contacts as $contact) {
516                         if ($contact['id'] == $item['contact-id']) {
517                                 return $contact;
518                         }
519                 }
520                 return false;
521         }
522 }