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