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