# tarantella-lib.pl
# Common functions 

do '../web-lib.pl';
do './lists-lib.pl';
do './html-lib.pl';
do './ttasess-lib.pl';
do './print-lib.pl';
&init_config();
%access = &get_module_acl();

@access_types = $access{'types'} eq '*' ? (0 .. 100)
				        : split(/\s+/, $access{'types'});
map { $access_types{$_}++ } @access_types;
$debug=0;
$no_out=0;

# wsplit(string)
# Splits a string like  foo "foo \"bar\"" bazzz  into an array of words
sub wsplit
{
local($s, @rv); $s = $_[0];
$s =~ s/\\\"/\0/g;
while($s =~ /^"([^"]*)"\s*(.*)$/ || $s =~ /^(\S+)\s*(.*)$/) {
	$w = $1; $s = $2;
	$w =~ s/\0/"/g; push(@rv, $w);
	}
return \@rv;
}

# wjoin(word, word, ...)
sub wjoin
{
local(@rv, $w);
foreach $w (@_) {
	if ($w =~ /^\S+$/) { push(@rv, $w); }
	else { push(@rv, "\"$w\""); }
	}
return join(' ', @rv);
}

# dir_name(struct)
sub dir_name
{
local($dfm, $mat);
$_[0]->{'name'} =~ /^(Directory|Files|Location)(Match)?$/;
$dfm = $1; $mat = $2;
if ($mat) { return "$dfm regexp <tt>$_[0]->{'words'}->[0]</tt>"; }
elsif ($_[0]->{'words'}->[0] eq "~")
	{ return "$dfm regexp <tt>$_[0]->{'words'}->[1]</tt>"; }
else { return "$dfm <tt>$_[0]->{'words'}->[0]</tt>"; }
}

# list_user_file(file, &user,  &pass)
sub list_user_file
{
local($_);
open(USERS, $_[0]);
while(<USERS>) {
	/^(\S+):(\S+)/;
	push(@{$_[1]}, $1); $_[2]->{$1} = $2;
	}
close(USERS);
}

#scan_objdescrip($tta3tier->{objetype}, $dn_t, $tta3tier->{target});
# it tries to get target "objdescrip" from "object list files" depending on type 
#
sub scan_objdescrip 
{
    local ($objetype) = $_[0];
    local ($target) = $_[1];
    local ($origin) = $_[2];
    local ($objdescrip) = "";
    local (@lista,@dn_lin);

    $target=~s/,$config{ldapcache_base}//; 
    if ($objetype eq "" ) { $objtype=$objType; }
    if ($objetype eq "ou" ) {
        @lista= &list_ous();
        $target=~s/,$origin//; 
    } elsif ($objetype eq "host" ) {
        @lista= &list_hosts();
#        $target=~s/ou=/cn=/g; 
    } elsif ($objetype eq "grphosts" ) {
        @lista= &list_grphosts();
#        $target=~s/ou=/cn=/g; 
    } elsif ($objetype eq "app" ) {
        @lista= &list_apps();
    } elsif ($objetype eq "grpapps" ) {
        @lista= &list_grpapps();
    } elsif ($objetype eq "domain" ) {
        @lista= &list_domains();
    }
    foreach $elem (@lista) {
       	if ( $elem->{'obj'} eq $target ) {
             $objdescrip=$elem->{descrip};
             if ( "$objdescrip" eq "" ) { $objdescrip = $elem->{name} };
             last;
         }
    }
#   print "<p>$objetype ..($origin)  --- ($target) -- [$objdescrip]\n";
    return $objdescrip;
}

#set_tta3tier(origin,target,dn,action,objtype)
# Set %tta3tier values from Input $in{} and return 
sub set_tta3tier
{
   local (@tta3tier);

   $tta3tier->{origin} = $_[0];
   $tta3tier->{target} = $_[1];
   $tta3tier->{oudn} = $_[2];
   $tta3tier->{action} = $_[3];
   $tta3tier->{objetype} = $_[4];
   $tta3tier->{login} = $in{tta3tier_login};
   $tta3tier->{password} = $in{tta3tier_password};
   $tta3tier->{title} = $in{tta3tier_title};
   $tta3tier->{stringcmd} = $in{tta3tier_stringcmd};
   $tta3tier->{domain} = $in{tta3tier_domain};
   $tta3tier->{appkey1} = $in{tta3tier_appkey1};
   $tta3tier->{appkey2} = $in{tta3tier_appkey2};
   $tta3tier->{appkey3} = $in{tta3tier_appkey3};
   $tta3tier->{appkey4} = $in{tta3tier_appkey4};
   $tta3tier->{appkey5} = $in{tta3tier_appkey5};
   $tta3tier->{maxsess} = $in{tta3tier_maxsess};
   $tta3tier->{ticketstatus} = $in{tta3tier_ticketstatus};
   $tta3tier->{ticketcounter} = $in{tta3tier_ticketcounter};
   $tta3tier->{endticket} = $in{tta3tier_endticket};
 
   return @tta3tier;
}

# run_tta_cmd([type_cmd,ens_obj,temp_f])
# Display an error message and exit. The variable $whatfailed must be set
# to the name of the operation that failed.
sub run_tta_cmd
{
 local ($strout);
 $strout=" $ens_obj  --  $dn";
 $exec_str = "tta"; 
 $cmd_str = $type_cmd; 

 if ( "$type_cmd" eq "emulatorsession" ) {
     $temp_f = &tempname();
     $str=" tta emulatorsession  list >$temp_f";
 }
 if ( "$type_cmd" eq "list" ) {
     $temp_f = &tempname();
     $tempf = &tempname();
     open(TEMPF, ">$tempf");
     print TEMPF "--name $ens_obj\n";
     close(TEMPF);
     $str=" tta object list_contents --file $tempf >$temp_f";
 }
 if ( "$type_cmd" eq "attributes" ) {
     $temp_f = &tempname();
     $tempf = &tempname();
     open(TEMPF, ">$tempf");
     print TEMPF "--name $ens_obj\n";
     close(TEMPF);
     $str=" tta object list_attributes --file $tempf >$temp_f";
 }
 if ( "$type_cmd" eq "delete" ) {
       $temp_f = &tempname();
       open(TEMPF, ">$temp_f");
       print TEMPF "$ens_obj\n";
       close(TEMPF);
       $str=" tta object delete --file $temp_f";
 }
 if ( "$type_cmd" eq "new_person" ) {
       $str=" tta object new_person --file $temp_f";
 }
 if ( "$type_cmd" eq "new_host" ) {
       $str=" tta object new_host --file $temp_f";
 }
 if ( "$type_cmd" eq "new_group" ) {
       $str=" tta object new_group --file $temp_f";
 }
 if ( "$type_cmd" eq "new_container" ) {
       $str=" tta object new_container --file $temp_f";
 }
 if ( "$type_cmd" eq "edit" ) {
       $str=" tta object edit --file $temp_f";
 }
 if ( "$type_cmd" eq "new_orgunit" ) {
       $str=" tta object new_orgunit --file $temp_f";
 }
 if ( "$type_cmd" eq "passcache" ) {
       $str=" tta passcache edit --file $temp_f";
 }
 if ($str) {
    return &run_cmd($str);
 }
 return -1;
}

# run_cmd([str])
# Display an error message and exit. The variable $whatfailed must be set
# to the name of the operation that failed.
# OUTPUT is going to FILEOUT so can be send it to Webmin Log and Screen if $no_out=false
sub run_cmd
{
  $exec_str = ($exec_str) ? $exec_str : "exec"; 
  $cmd_str = ($cmd_str) ? $cmd_str : "command"; 
 
 if ($str) {
        $| = 1;

        local $temp = &tempname();
        local $outfile = &tempname();
        local $line ="$str\n";

        open(FILEOUT, ">$outfile");
        open(TEMP, ">$temp");
        print TEMP "#!/bin/sh\n";
        print TEMP $env;
	print TEMP "export $export\n" if ($export);
	print TEMP "$str\n";
	close(TEMP);
	chmod(0777, $temp);
        if ( $no_out eq 0 ) { print "<pre>\n"; }
	$got = &foreign_call("proc", "safe_process_exec",
	   		     "su root -c $temp", 0, 0,
                              *FILEOUT, undef, 0);   
	unlink($temp);
        close(FILEOUT);
	open(FILEOUT, $outfile);
	while(<FILEOUT>) {
		s/\r|\n//g;
                if ( $no_out eq 0 ) { print "$_ \n"; }
                $line .= "$_\n"; 
        }
        close(FILEOUT);
	unlink($outfile);
        if ( $temp_f) {
             $line .= "\nfile: $temp_f :::::::::::::::::::::::\n"; 
	     open(TEMPF, $temp_f);
	     while(<TEMPF>) {
		     s/\r|\n//g;
                     $line .= "$_\n"; 
             }
             close(TEMPF);
        }
        if ( $ens_obj ) {
             &additional_log($str, $ens_obj, $line);
        } else { 
             &additional_log($str, undef, $line);
        }
        &webmin_log($exec_str, $cmd_str, $config{run_exec_user}, "$str");
        if (!$got) { 
            if ( $no_out eq 0 ) { print "<i>$text{'run_noout'}</i>\n"; }
            return false;
        } else  {
            if ( $no_out eq 0 ) { print "<pre>\n"; }
        }
  }
  return true;
}

sub scan_dn_cache {
   local (@linUserName, @UserPath);
   local ($UserName) = @_ ;
   local ($lnumUser) = 0;

         @linUserName = split(/,/, $UserName);
	 $OuName="";
	 foreach $obj (@linUserName) {
              @UserPath= split(/=/,$obj);
              $lnumUser++;
              if ( $UserPath[0] eq "cn"  &&  $lnumUser eq 1 ) {
		   $NameUser=$UserPath[1];
                        last;
              } else {
                   if ( "$OuName" ne "" ) { $OuName=$OuName.","; }
		         $OuName=$OuName.$UserPath[0]."=".$UserPath[1];
	      }
          }
}

sub get_acttitles
{
	local ($scr, $item,$nItems);
        local (@l_target, @l_conditions, @l_conditions_tit);
        local (@l_actions, @l_actions_tit);
        local (@l_how, @l_how_tit);
        local (@l_when, @l_when_tit);
        local (@l_target);

	@l_target = split(/,/,$text{'mon_target_value'}, -1);
	foreach $item (@l_target) {
     		if ( $item eq $monTarget ) {
        		$targetext='mon_'.$item.'_sess';
        		$t_monTarget=$text{$targetext};
        			last;
     		}
	}
	@l_conditions = split(/,/,$text{'mon_conditions_value'}, -1);
	@l_conditions_tit = split(/,/,$text{'mon_conditions_desc'}, -1);
        $nItems=0;
	foreach $item (@l_conditions) {
     		if ( $item eq $monCondition ) {
        		$t_monCondition=$l_conditions_tit[$nItems];
        		last;
     		}
                $nItems++;
	}
	@l_actions = split(/,/,$text{'mon_actions_value'}, -1);
	@l_actions_tit = split(/,/,$text{'mon_actions_desc'}, -1);
        $nItems=0;
	foreach $item (@l_actions) {
     		if ( $item eq $monAction ) {
        		$t_monAction=$l_actions_tit[$nItems];
        		last;
     		}
                $nItems++;
	}
	foreach $scr (&load_scriptlist()) { 
     		if ( $scr->{'name'} eq $monScript ) {
        		$t_monScript="<A href=\"file_mod.cgi?fName=".$scr->{'name'}."&perm=all&wkdir=$config{monitor_scripts_path}&fPerm=0700\">".$scr->{'name'}."</A> (".$scr->{'desc'}.")";
        		last;
     		}
	}
	@l_how = split(/,/,$text{'mon_how_value'}, -1);
	@l_how_tit = split(/,/,$text{'mon_how_desc'}, -1);
        $nItems=0;
	foreach $item (@l_how) {
     		if ( $item eq $monHow ) {
          		$t_monHow=$l_how_tit[$nItems];
          		last;
     		}
                $nItems++;
	}
        if ( $monHow eq "auto" && $monWhen ne "" ) {
        	@l_when = split(/,/,$text{'mon_when_value'}, -1);
        	@l_when_tit = split(/,/,$text{'mon_when_desc'}, -1);
                $nItems=0;
        	foreach $item (@l_when) {
     			if ( $item eq $monWhen ) {
          			$t_monWhen=$l_when_tit[$nItems];
          			last;
     			}
		}
                $nItems++;
        } elsif ( $monHow eq "task" ) {   
		@l_when = split(/ /, $monWhen, -1);
                $t_monWhen="$text{'edit_mins'}: $l_when[0]".
                           " $text{'edit_hours'}: $l_when[1]".
                           " $text{'edit_days'}: $l_when[2]".
                           " $text{'edit_months'}: $l_when[3]".
                           " $text{'edit_weekdays'}: $l_when[4]";

        } elsif ( $monHow eq "manual" ) {   
         	$t_monWhen=" - ";
        }
        $t_monObject=$monObject;
        if ( $monObject ne "" ) {
             if ( $monTarget eq "user" ) {
                  $dn = "$monObject,".$config{ldap_base};
                  $ldap_server=1;
                  &connect ();
                  $entry = $conn->browse ($dn);
                  if ($err = $conn->getErrorCode ()) {
                          $t_monObject=$monObject;
                          &additional_log($dn, undef, $err);
                  } else {
                          $dn_ou=$monObject;
                          $dn_ou=~s/cn=$entry->{cn}[0],//;            
                          $organizationname="";
                          foreach $item (&list_ous()) {
                                  if ( $item->{'obj'} eq $dn_ou ) {
                                       $organizationname=$item->{name};
                                       last;
                                  }
                          }
                          $t_monObject=$entry->{cn}[0]."  ".$entry->{sn}[0]." ".$organizationname;
                  }
                  &webmin_log("monitor:read User OU", "browse", "ldap", "$dn");
             } elsif  ( $monTarget eq "ou" ) {
                  foreach $item (&list_ous()) {
     	                  if ( $item->{'alias'} eq $monObject ) {
                               $t_monObject=$item->{'name'};
          		       last;
                          }
     		  }
             } elsif  ( $monTarget eq "host" ) {
                  foreach $item (&list_hosts()) {
     	                  if ( $item->{'alias'} eq $monObject ) {
                               $t_monObject=$item->{'name'};
          		       last;
                          }
     		  }
             } elsif  ( $monTarget eq "grphosts" ) {
                  foreach $item (&list_grphosts()) {
     	                  if ( $item->{'alias'} eq $monObject ) {
                               $t_monObject=$item->{'name'};
          		       last;
                          }
     		  }
             } elsif  ( $monTarget eq "app" ) {
                  foreach $item (&list_apps()) {
     	                  if ( $item->{'alias'} eq $monObject ) {
                               $t_monObject=$item->{'name'};
          		       last;
                          }
     		  }
             } elsif  ( $monTarget eq "grpapps" ) {
                  foreach $item (&list_grpapps()) {
     	                  if ( $item->{'alias'} eq $monObject ) {
                               $t_monObject=$item->{'name'};
          		       last;
                          }
     		  }
             }
        }
}

1;  # Return true
