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