#!/usr/bin/perl
# STTA Rev. 1.3 Copyright (c) 2001-2004 Jesús Pérez Lorenzo  --- license GNU GPL
# stta: (@#) 1.31051043346- [2004_01_29_102036]
# Send the webmin feedback form

require './stta-lib.pl';
do "config_info.pl";
do "ldap-lib.pl";

&init_config();
&load_dataconf();
&ReadParseMime();
&error_setup($text{'feedback_err'});
$access{'feedback'} || &error($text{'feedback_ecannot'});
&load_more_text('feedback');
&foreign_require("proc", "proc-lib.pl");
@procs = &foreign_call("proc", "list_processes");

$findOps="-maxdepth 1 -type f";  # this for find no to scan or report subdirs 
# Construct the email body
$in{'text'} =~ s/\r//g;
$date = localtime(time());
$ver = &get_webmin_version();
&get_miniserv_config(\%miniserv);
if ($in{'name'} && $in{'email'}) {
	$from = "$in{'name'} <$in{'email'}>";
	$email = $in{'email'};
	}
elsif ($in{'email'}) {
	$email = $from = $in{'email'};
	}
else {
	$email = $from = "feedback\@".&get_system_hostname();
	}
local $m = $in{'module'};
local $m="stta";
$m || !$in{'config'} || &error($text{'feedback_emodule'});
&check_os_support($m) && $m !~ /\.\./ || &error($text{'feedback_emodule2'});

        &headerstta($text{'feedback_title'}, "", "feedback" ,undef,1,0,"$text{'headpage_right'}"."$text{'head_logout'}",undef,undef,"$text{head_below}" );

%minfo = &get_module_info($m);
if ($gconfig{'nofeedbackcc'}) {
	@tolist = ( $config{'feedback_to'} ? $config{'feedback_to'} : "");
	}
else {
	@tolist = split(/\s+/, $in{'to'});
	}
@tolist || &error($text{'feedback_enoto'});
foreach $t (@tolist) {
	$headers .= "To: $t\n";
	}
$headers .= "From: $from\n";
$headers .= "Subject: $text{'feedback_title'}\n";
%minfo=&load_minfo();

$alnum=0;
$nameAttach[$alnum] = "mail-text"; $alnum++;
if ( ! $in{dirname} ) {
     $attach[0] = <<EOF;
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
EOF
}
$mod_des=eval("\$minfo{'desc_$current_lang'}");
$attach[0] .= <<EOF;
Name:           $in{'name'}
Email address:  $in{'email'}
Date:           $date
Webmin version: $ver
Browser:        $ENV{'HTTP_USER_AGENT'}
Module:         $in{'module'} ( $mod_des )
EOF
foreach $k (keys %minfo) {
   next if ( $k =~ /desc/ || $k =~ /name/);
$attach[0] .= <<EOF;
$k          : $minfo{$k}
EOF
}
	$uname = `uname -a`;
        $hostname = &get_system_hostname();
        $ver = &get_webmin_version();
        if ($gconfig{'real_os_type'}) {
                if ($gconfig{'os_version'} eq "*") {
                        $ostr = $gconfig{'real_os_type'};
                        }
                else {
                        $ostr = "$gconfig{'real_os_type'} $gconfig{'real_os_version'}";
                        }
                }
        else {
                $ostr = "$gconfig{'os_type'} $gconfig{'os_version'}";
                }
	$attach[0] .= <<EOF;
OS from webmin: $gconfig{'real_os_type'} $gconfig{'real_os_version'}
OS code:        $gconfig{'os_type'} $gconfig{'os_version'}
Uname output:   $uname
EOF

$attach[0] .= "\n".$in{'text'}."\n";

        if ( $in{dirname} ) {
            if ( ! -d $in{dirname} ) {
                  system("mkdir $in{dirname}");
            } else { 
                  system("rm -r $in{dirname}/* ");
            }
        }
        $temp_d = &tempname();
        if ( ! -d $temp_d ) { system("mkdir $temp_d") }
        if ($in{'cfg'} && !$gconfig{'nofeedbackconfig'}) {
       	      # Check if this user has full rights to the module
	      $access{'feedback'} == 2 || &error($text{'feedback_ecannot2'});
	      local %uacl = &get_module_acl(undef, $m);
	      local %defacl;
	      &read_file("$root_directory/$m/defaultacl", \%defacl);
	      foreach $k (keys %uacl) {
		      if ($defacl{$k} ne $uacl{$k}) { &error($text{'feedback_econfig'}); }
	      }
	      # Attach all the text file from the module's config
		  local $a;
                  if ( ! $in{dirname} ) {
		      $a .= "Content-Type: text/plain; name=\"config\"\n";
		      $a .= "Content-Transfer-Encoding: 7bit\n";
		      $a .= "\n";
                  }
                  &load_dataconf();
		  foreach $k (keys %config) {
			      $a .= "$k=$config{$k}\n";
			      }
                  $nameAttach[$alnum] = "config"; $alnum++;
		  push(@attach, $a);
      
            #	# Find out what config files the module uses
            #	local @files;
            #	if (-r "$root_directory/$m/feedback_files.pl") {
            #		# Ask the module for it's files
            #		&foreign_require($m, "feedback_files.pl");
            #		@files = &foreign_call($m, "feedback_files", $m);
            #		}
            #
            #	# Use all the path in the config
            #	foreach $k (keys %mconfig) {
            #		push(@files, $mconfig{$k}) if ($mconfig{$k} =~ /^\//);
            #		}
            #opendir(DIR, "$config_directory/$m");
            #    foreach $f (readdir(DIR)) { 
            #          next if ( -d $f );
	    #          push(@files, "$config_directory/$m/$f");
            #    }
            #closedir(DIR);
            $str="(cd $config_directory/stta; tar cf $temp_d/stta_etc.tar . ; $config{ziptool} $temp_d/stta_etc.tar 2>/dev/null)";
            &run_cmd();
	    push(@files, "$temp_d/stta_etc.tar.gz");
            $str="(cd $root_directory/stta; ./brandmgr.pl > $temp_d/brandinfo.html )";
            &run_cmd();
	    push(@files, "$temp_d/brandinfo.html");
            $str="(cd $root_directory/stta; tar cf $temp_d/brandinfo.tar .brandinfofile* ; $config{ziptool} $temp_d/brandinfo.tar 2>/dev/null)";
            &run_cmd();
	    push(@files, "$temp_d/brandinfo.tar.gz");
       }
       if ($in{'backups'} && !$gconfig{'nofeedbackconfig'}) {
           $config{output_cgis}=0;
           system("mkdir $temp_d/backups");
           system("mkdir $temp_d/backups/tta");
           system("chmod -R 777 $temp_d");  # ldif I-planet need it
           $str=$config{'tta_backup'}." $temp_d/backups/tta -nodocroot"; # avoid  docroot
           &run_cmd();
           system("mkdir $temp_d/backups/ldap");
           system("chmod -R 777 $temp_d/backups/ldap");  # ldif I-planet need it
           $str=$config{'ldap_backup'}." $temp_d/backups/ldap";
           &run_cmd();
           if ( $config{'is_ldapcache'} eq "true" ) {
                system("mkdir $temp_d/backups/ldapcache");
                system("chmod -R 777 $temp_d/backups/ldapcache");  # ldif I-planet need it
                $str=$config{'ldapcache_backup'}." $temp_d/backups/ldapcache";
                &run_cmd();
           }
           $str="(cd $temp_d; tar cf backups.tar backups; $config{ziptool} backups.tar)";
           &run_cmd();
	   push(@files, "$temp_d/backups.tar.gz");
       }
       if ($in{'dbs'} && !$gconfig{'nofeedbackconfig'}) {
           $config{output_cgis}=0;
           system("mkdir $temp_d/dbs");
           system("chmod -R 777 $temp_d");  # ldif I-planet need it
           $str=$config{'tta_backup'}." $temp_d/dbs ens ";
           &run_cmd();
           $str=$config{'ldap_ldif'}." $temp_d/dbs/ldap.ldif";
           &run_cmd();
           if ( $config{'is_ldapcache'} eq "true" ) {
                $str=$config{'ldapcache_ldif'}." $temp_d/dbs/ldapcache.ldif";
                &run_cmd();
           }
           $str="(cd $temp_d; tar cf dbs.tar dbs; $config{ziptool} dbs.tar)";
           &run_cmd();
	   push(@files, "$temp_d/dbs.tar.gz");
       }
       if ($in{'logs'} && !$gconfig{'nofeedbackconfig'}) {
           $config{output_cgis}=0;
           $n=$in{tailn}+0; 
           system("mkdir $temp_d/logs");
           $str="tail -n $n $webmin_logfile >$temp_d/logs/webmin.log"; 
           &run_cmd();
           $fpath=$config{stta_logdir};
           if ( -d $fpath && $fpath ne "" ) {
                 system("mkdir $temp_d/logs/stta");
	         opendir(DIR, $fpath);
                      foreach $f (readdir(DIR)) {
                          next if ( -d $f );
                          $str="tail -n $n  $fpath/$f  >$temp_d/logs/stta/$f"; 
                          &run_cmd();
                      }
                 closedir(DIR);
           }
           system (" date>$temp_d/test"); 
           local @st = stat("$temp_d/test");
           if (@st) {
                @tm = localtime(@st[9]-$in{timelog}*60);
                $ftest= sprintf "%s%2.2d%2.2d%2.2d",
                        $tm[4]+1,$tm[3],$tm[2],$tm[1];
                system ("touch -m $ftest  $temp_d/test"); 
           }
           # getting webmin diff files 
             $fpath="$var_directory/diffs";
             if ( -d $fpath && $fpath ne "" ) {
               system("mkdir $temp_d/logs/diffs");
               $str="cd $fpath | find . -newer $temp_d/test $findOps | cpio -pdum $temp_d/logs/diffs "; 
               &run_cmd();
             }
           # getting tmp webmin logs files 
             $fpath="/tmp/.webmin";
             if ( -d $fpath && $fpath ne "" ) {
               system("mkdir $temp_d/logs/webmin-tmp");
               $str="cd $fpath; find . -newer $temp_d/test $findOps | cpio -pdum $temp_d/logs/webmin-tmp"; 
               &run_cmd();
             }
           # getting tta logs
             $fpath=$config{ttalog_path};
             if ( -d $fpath && $fpath ne "" ) {
               system("mkdir $temp_d/logs/tta");
               $str="cd $fpath ; find . -newer $temp_d/test $findOps | cpio -pdum $temp_d/logs/tta"; 
               &run_cmd();
             }
           # getting scancache logs
             $fpath=$config{cache_debuglog_dir};
             if ( -d $fpath && $fpath ne "" ) {
               system("mkdir $temp_d/logs/cache");
               $str="cd $fpath; find . -newer $temp_d/test $findOps | cpio -pdum $temp_d/logs/cache "; 
               &run_cmd();
             }
           # getting stta_sess logs
             system("mkdir $temp_d/logs/sttasess");
             system(" cp $config{'countsessout_file'} $config{'totalsessout_file'} $config{'osdataout_file'} $config{'tta_sessout_file'} $temp_d/logs/sttasess "); 
           # 
           $str="(cd $temp_d; tar cf logs.tar logs; $config{ziptool} logs.tar)";
           &run_cmd();
	   push(@files, "$temp_d/logs.tar.gz");
       }
       if ($in{'config'} && !$gconfig{'nofeedbackconfig'}) {
           # opendir(DIR, "$config_directory/$m/dataconf");
           #           next if ( $f =~ /^./ );
           #    foreach $f (readdir(DIR)) { 
	   #         push(@files, "$config_directory/$m/dataconf/$f");
           #     }
           # closedir(DIR);
            $str="(cd $config_directory/stta; tar cf $temp_d/stta_etc.tar . ; $config{ziptool} $temp_d/stta_etc.tar 2>/dev/null)";
            &run_cmd();
	    push(@files, "$root_directory/$m/.brandinfofile");
	    push(@files, "$temp_d/stta_etc.tar.gz");
            $ReportOut=$temp_d."/stta_report.html";
            open (REPORTOUT,">$ReportOut");
                  if ( $ReportOut ) { select(REPORTOUT)}
                  print "<html><body>\n";
                  print "<table width=100% border>\n";
                  print "<tr $tb> <td valig=top><font color='$revtext'><b> $text{'titidx_sttareport'}</b>";
                  print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n";
                  print "Webmin $ver -  $hostname  -  $ostr";
                  print "</td></td> </tr>\n";
                  print "</body></html>\n";
                  &make_STTA_Report();
                  if ( $ReportOut ) { select(REPORTOUT)}
                  print "<table width=100% border>\n";
                  print "<tr $tb> <td valig=top><font color='$revtext'><b> $text{'config_title'}</b>";
                  print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Webmin $ver -  $hostname  -  $ostr</td></td> </tr>\n";
                  print "<tr $cb><td>\n";
                  print "<a name=\"sttaconfig\">\n";
                  &config_form("report");
                  print "</td></tr></table>\n";
                  print "<tr><tr></table></table><p>\n";
                  if ( $ReportOut ) { $| =1; select(STDOUT);}
	          push(@files, "$ReportOut");
       }

	@files = &unique(@files);

	# Attach those config files that are plain text (less than 5%
	# non-ascii characters). Also skip logfiles.
	foreach $f (@files) {
		next if (!$f || -d $f);
		next if ($f =~ /\/var\/log\//);
		local $/ = undef;
		open(FILE, $f) || next;
		local $data = <FILE>;
		close(FILE);
#		local $count = ($data =~ tr/[\000-\176]/[\000-\176]/);
#		if (!length($data) || 100*$count / length($data) > 95) {
			# File is text
			local $a;
			local $sf = &short_name($f);
                        if ( ! $in{dirname} ) {
			      $a .= "Content-Type: text/plain; name=\"$sf\"\n";
			      $a .= "Content-Transfer-Encoding: 7bit\n";
			      $a .= "\n";
                        }
			$a .= $data;
                        $nameAttach[$alnum] = "$sf"; $alnum++;
			push(@attach, $a);
#		}
	}

# Include uploaded attached files
foreach $u ('attach0', 'attach1') {
	if ($in{$u} ne '') {
		local $a;
		local $name = &short_name($in{"${u}_filename"});
		local $type = $in{"${u}_content_type"};
		$type = &guess_type($name) if (!$type);
                if ( ! $in{dirname} ) {
		     $a .= "Content-type: $type; name=\"$name\"\n";
		     $a .= "Content-Transfer-Encoding: base64\n";
		     $a .= "\n\n";
		     $a .= &encode_base64($in{$u});
                } else {  system("cp $in{u} $in{dirname}/$name 2>/dev/null"); }
                $nameAttach[$alnum] = "$name"; $alnum++;
		push(@attach, $a);
		}
	}


if ( $in{'dirname'} ) {
     # pack in dirname
     $i=0;
     foreach $a (@attach) {
        open (FILEMAIL, ">$in{dirname}/$nameAttach[$i]");
   	     print FILEMAIL $a;
        close (FILEMAIL);
        $i++;
     }
     $sent=4;
} else {
     # Build the MIME email
     $bound = "bound".time();
     $mail = $headers;
     $mail .= "Content-Type: multipart/mixed; boundary=\"$bound\"\n";
     $mail .= "MIME-Version: 1.0\n";
     $mail .= "\n";
     $mail .= "This is a multi-part message in MIME format.\n";
     foreach $a (@attach) {
	     $mail .= "\n--".$bound."\n";
	     $mail .= $a;
	     }
     $mail .= "\n--".$bound."--\n";
}
if (!$in{'mailserver_def'} && !$in{'dirname'}) {
	$ok = &send_via_smtp($in{'mailserver'});
	$sent = 3 if ($ok);
	}

if (!$sent) {
	# Try to send the email by calling sendmail -t
	%sconfig = &foreign_config("sendmail");
	$sendmail = $sconfig{'sendmail_path'} ? $sconfig{'sendmail_path'}
					      : &has_command("sendmail");
	if (-x $sendmail && open(MAIL, "| $sendmail -t")) {
		print MAIL $mail;
		if (close(MAIL)) {
			$sent = 2;
			}
		}
	}

if (!$sent) {
	# Try to connect to a local SMTP server
	$ok = &send_via_smtp("localhost");
	$sent = 1 if ($ok);
	}

if ($sent) {
	# Tell the user that it was sent OK
print "<hr>\n";
        print "<table border width=100%>\n";
        print "<tr $tb> <td><b>$text{'feedback_header'}</b></td> </tr>\n";
        print "<tr $cb> <td><table width=100%><tr $cb><td>\n";
        $debug=4;
        if ( -d $temp_d  && $debug lt 4 ) { system("rm -r  $temp_d}") }
	print "<hr><p>\n";
	if ($sent == 3) {
		print &text('feedback_via', join(",", @tolist),
			    "<tt>$in{'mailserver'}</tt>"),"\n";
	} elsif ($sent == 2) {
		print &text('feedback_prog', join(",", @tolist),
			    "<tt>$sendmail</tt>"),"\n";
	} elsif ($sent == 4) {
                if ( $in{'packcmd'} ne ""  ) {
                     $packCmd=$in{'packcmd'};
                     if (  $packCmd =~ /\$HOSTTIME/ ) {
                           @host_name = split(/\./,&get_system_hostname());
                           $host_time=$host_name[0]."_".&out_now_filename();
                           $packCmd =~ s/\$HOSTTIME/$host_time/g;
                     }
                     $str="(cd $in{'dirname'}; ".$packCmd.")";
                     &run_cmd();
                }
		print &text('feedback_dirname', $in{'dirname'}),"   ( $host_time ) \n";
	} else {
		print &text('feedback_via', join(",", @tolist),
			    "<tt>localhost</tt>"),"\n";
		}
        print "<tr></tr><tr></tr></table></table>\n";
	print "<p><hr>\n";
        &footer($config{'back_return'},$text{'index'});
        print "<p><p><p>\n";
        do "footer.pl";


	# Save settings in config
	$feedback{'feedback_name'} = $in{'name'};
	$feedback{'feedback_email'} = $in{'email'};
	$feedback{'feedback_dirname'} = $in{'dirname'};
	$feedback{'feedback_packcmd'} = $in{'packcmd'};
	$feedback{'feedback_mailserver'} =
		$in{'mailserver_def'} ? undef : $in{'mailserver'};
	&write_file("$config_directory/$m/dataconf/feedback", \%feedback);
	}
else {
	# Give up! Tell the user ..
	&error($text{'feedback_esend'});
	}

sub send_via_smtp
{
local $error;
&open_socket($_[0], 25, MAIL, \$error);
return 0 if ($error);
&smtp_command(MAIL) || return 0;
&smtp_command(MAIL, "helo ".&get_system_hostname()."\n") || return 0;
&smtp_command(MAIL, "mail from: $email\n") || return 0;
foreach $t (@tolist) {
	&smtp_command(MAIL, "rcpt to: $t\n") || return 0;
	}
&smtp_command(MAIL, "data\n");
print MAIL $mail;
&smtp_command(MAIL, ".\n");
&smtp_command(MAIL, "quit\n");
close(MAIL);
return 1;
}

# smtp_command(handle, command)
sub smtp_command
{
local ($m, $c) = @_;
print $m $c;
local $r = <$m>;
return $r =~ /^[23]\d+/;
}

sub guess_type
{
local $e;
if (!%mime_types) {
	open(MIME, "$root_directory/mime.types");
	while(<MIME>) {
		s/\r|\n//g;
		s/#.*$//g;
		local @s = split(/\s+/);
		foreach $e (@s[1..$#s]) {
			$mime_types{$e} = $s[0];
			}
		}
	close(MIME);
	}
if ($_[0] =~ /\.([A-z0-9]+)$/ && $mime_types{$1}) {
	return $mime_types{$1};
	}
return "application/octet-stream";
}

sub short_name
{
$_[0] =~ /([^\\\/]+)$/;
return $1;
}

