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