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