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