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