# tarantella-lib.pl
# Common functions for apache configuration

do '../web-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);
}

# config_icons(context, program)
# Displays up to 17 icons, one for each type of configuration directive, for
# some context (global, virtual, directory or htaccess)
sub config_icons
{
local($m, $func, $e, %etype, $i, $c);
foreach $m (sort { $a cmp $b } (keys %httpd_modules)) {
        $func = $m."_directives";
	foreach $e (&$func($httpd_modules{$m})) {
		if ($e->{$_[0]}) { $etype{$e->{'type'}}++; }
		}
        }
for($i=0; $text{"type_$i"}; $i++) {
	if ($etype{$i} && $access_types{$i}) {
		if ($c%5 == 0) { print "<tr>\n"; }
		print "<td valign=top align=center width=20%>\n";
		&generate_icon("images/type_icon_$i.gif", $text{"type_$i"},
			       $_[1]."type=$i");
		print "</td>\n";
		if ($c%5 == 4) { print "<tr>\n"; }
		$c++;
		}
	}
for($i=2; $i<@_; $i++) {
	if ($c%5 == 0) { print "<tr>\n"; }
	print "<td valign=top align=center width=20%>\n";
	&generate_icon($_[$i]->{'icon'}, $_[$i]->{'name'}, $_[$i]->{'link'});
	print "</td>\n";
	if ($c%5 == 4) { print "<tr>\n"; }
	$c++;
	}
print "</table><p>\n";
}

sub footHere
{
        print "<tr><tr></table></table><hr><p>\n";
        &footer($config{'back_return'},$text{'index'});
        print "<p><p><p>\n";
        do "footer.pl";
}

# restart_button()
# Returns HTML for a link to put in the top-right corner of every page
sub restart_button
{
	$rv = "<a href=\"tta_restart.cgi\">$text{'tta_restart'}</a><br>\n";
	$rv .= "<a href=\"http://localhost/tarantella/help/en-us/admintocs/TOC_index.html\">$text{'tta_help'}</a>\n";
	$rv .= "<a href=\"ldap_restart.cgi\">$text{'ldap_restart'}</a>\n";
        if ( $config{'is_ldapcache'} eq "true" ) {
       	    $rv .= "<a href=\"ldapcache_restart.cgi\">$text{'ldapcache_restart'}</a>\n";
        }
	$rv .= "<a href=\"file:/opt/netscape/ldap/manual/en/slapd/ag/./contents.htm\">$text{'ldap_help'}</a>\n";
return $rv;
}

# list_ous()
# Returns an array of hashtable, each containing info about one ou. Each hash
# will always contain the keys "alias" "name" "ou"
sub list_ous
{
# read the OU list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading OU File List
	$lnum = 0;
	open(FILEOUS, $config{'ou_list'});
	while(<FILEOUS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'obj' => $lin[2], 'ens' => $lin[3], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEOUS);
return @rv;
}

# list_apps()
# Returns an array of hashtable, each containing info about one ou. Each hash
# will always contain the keys "alias" "name" "app"
sub list_apps
{
# read the APP list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading APP File List
	$lnum = 0;
	open(FILEAPPS, $config{'app_list'});
	while(<FILEAPPS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'grpalias' => $lin[2], 
				    'obj' => $lin[3], 'ens' => $lin[4], 
				    'descrip' => $lin[5], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEAPPS);
return @rv;
}

# list_grpapps()
# Returns an array of hashtable, each containing info about one grpapps. Each hash
# will always contain the keys "alias" "name" "grpapps"
sub list_grpapps
{
# read the GRPAPPS list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading GRPAPPS File List
	$lnum = 0;
	open(FILEGRPAPPS, $config{'grpapps_list'});
	while(<FILEGRPAPPS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'obj' => $lin[2], 'ens' => $lin[3], 
				    'descrip' => $lin[4], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEGRPAPPS);
return @rv;
}

# list_domains()
# Returns an array of hashtable, each containing info about one ou. Each hash
# will always contain the keys "alias" "name" "domain"
sub list_domains
{
# read the DOMAIN list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading DOMAIN File List
	$lnum = 0;
	open(FILEDOMAINS, $config{'domain_list'});
	while(<FILEDOMAINS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'obj' => $lin[2], 'ens' => $lin[3], 
				    'descrip' => $lin[4], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEDOMAINS);
return @rv;
}

# list_grphosts()
# Returns an array of hashtable, each containing info about one grphosts. Each hash
# will always contain the keys "alias" "name" "grphosts"
sub list_grphosts
{
# read the GRPHOSTS list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading GRPHOSTS File List
	$lnum = 0;
	open(FILEGRPHOSTS, $config{'grphosts_list'});
	while(<FILEGRPHOSTS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'obj' => $lin[2], 'ens' => $lin[3], 
				    'descrip' => $lin[4], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEGRPHOSTS);
return @rv;
}

# list_hosts()
# Returns an array of hashtable, each containing info about one hosts. Each hash
# will always contain the keys "alias" "name" "hosts"
sub list_hosts
{
# read the HOSTS list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading HOSTS File List
	$lnum = 0;
	open(FILEHOSTS, $config{'hosts_list'});
	while(<FILEHOSTS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'grpalias' => $lin[2], 
				    'obj' => $lin[3], 'ens' => $lin[4], 
				    'descrip' => $lin[5], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEHOSTS);
return @rv;
}

# list_hostsuser()
# Returns an array of hashtable, each containing info about one hostsuser. Each hash
# will always contain the keys "alias" "name" "hostsuser"
sub list_hostsuser
{
# read the HOSTSUSER list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading HOSTS File List
	$lnum = 0;
	open(FILEHOSTSUSER, $config{'hostsuser_list'});
	while(<FILEHOSTSUSER>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'username' => $lin[0],'passwd' => $lin[1],
				    'name' => $lin[2],
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEHOSTSUSER);
return @rv;
}

# list_profcache()
# Returns an array of hashtable, each containing info about one hostsuser. Each hash
# will always contain the keys "alias" "name" "hostsuser"
sub list_profcache
{
# read the PROFCACHE list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading PROFCACHE File List
	$lnum = 0;
	open(FILEPROFCACHE, $config{'profcache_list'});
	while(<FILEPROFCACHE>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],'name' => $lin[1],
				    'hostusername' => $lin[2],
				    'hostname' => $lin[3],
				    'grphost' => $lin[4],
				    'username' => $lin[5],
				    'ou' => $lin[6],
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEPROFCACHE);
return @rv;
}

# list_actions()
# Returns an array of hashtable, each containing info about actions. Each hash
# will always contain the keys "alias" "name", etc. 
sub list_actions
{
# read the ACCTIONS list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading ACCTIONS File List
	$lnum = 0;
	open(FILEACCTIONS, $config{'act_list'});
	while(<FILEACCTIONS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],'name' => $lin[1],
				    'target' => $lin[2],
				    'object' => $lin[3],
				    'condition' => $lin[4],
				    'conditionValue' => $lin[5],
				    'action' => $lin[6],
				    'script' => $lin[7],
				    'when' => $lin[8],
				    'how' => $lin[9],
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}

	close(FILEACCTIONS);
return @rv;
}

# list_links()
# Returns an array of hashtable, each containing info about one link. Each hash
# will always contain the keys "alias" "name" "link"
sub list_links
{
# read the Links list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading Links File List
	$lnum = 0;
	open(FILELKS, $config{'tta_links'});
	while(<FILELKS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'obj' => $lin[2], 
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILELKS);
return @rv;
}

# list_webtops()
# Returns an array of hashtable, each containing info about one webtop. Each hash
# will always contain the keys "alias" "name" "link"
sub list_webtops
{
# read the Webtops list file
local(@rv, $_, %idx, $lnum, @lin);
	# start by reading Webtops File List
	$lnum = 0;
	open(FILEWEBTOPS, $config{'tta_webtops'});
	while(<FILEWEBTOPS>) {
		s/\r|\n//g;
		if (/\S/ && !/^[#\+\-]/) {
		        chomp($lin);
			@lin = split(/::/, $_, -1);
			push(@rv, { 'alias' => $lin[0],	'name' => $lin[1],
				    'obj' => $lin[2],
				    'num' => scalar(@rv) });
			$idx{$lin[0]} = $rv[$#rv];
			}
		$lnum++;
		}
	close(FILEWEBTOPS);
return @rv;
}
# show_error([message])
# Display an error message and exit. The variable $whatfailed must be set
# to the name of the operation that failed.
sub show_error
{
	print "<hr>\n";
	print "<h3>",($whatfailed ? "$whatfailed : " : ""),@_,"</h3>\n";
	print "<hr>\n";
}

# load_ttaobj($temp_f)
# Returns an array of hashtable, each containing info about one webtop. Each hash
# will always contain the keys "alias" "name" "link" etc .
sub load_ttaobj
{
# read the obj properties from file
   local(@ttaobj, $_, %idx, $lnum, @lin);
 
	# start by reading from file List

	$lnum = 0;
	open(FILETTAOBJ, $temp_f);
	while(<FILETTAOBJ>) {
		 if (/\S/ && !/^[#\+\-]/ && $lnum gt 0 ) {
		        chomp($lin);
			@lin = split(/: /, $_, -1);
		        $lin[1]=~ s/"//g;
		        $is_space=chop($lin[1]);
                        if ( $is_space eq " " ) { chop($lin[1]); }
			push(@ttaobj, { 'property' => $lin[0],
				    'value' => $lin[1],
				    'num' => scalar(@ttaobj) });
			$idx{$lin[0]} = $ttaobj[$#ttaobj];
			}
		$lnum++;
		}
	close(FILETTAOBJ);
	unlink($temp_f);
    return @ttaobj;
}

# footCacheHere()
# Display a message, close tables and put page foot ... 
# almost ready to exit with good look & feel
sub footCacheHere {
 print "<table width=100% border>\n";
 print "<tr $tb> <td><b>|</b></td> </tr>\n";
 print "<tr></tr><tr><center><b>$text{'ldapcache_disable'}</center></b></tr>\n";
 print "<tr><tr></table></table><hr><p>\n";
 &footer($config{'back_return'},$text{'index'});
 print "<p><p><p>\n";
 do "footer.pl";
}

# htmlCacheapp(msgObj,formObj)
# Display all htmls labels to get input for "ttacacheapp" object 
sub htmlCacheapp 
{
 print "<tr><td valign=top><b>$msgObj</b>&nbsp;</td></tr>\n";
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierlogin'}</b>","f3tierlogin"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_login\" VALUE=\"$tta3tier_login\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierpassword'}</b>","f3tierpassword"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"button\" NAME=\"?\" VALUE=\"?\" onClick=\"showPasswd($formObj);\" >"; 
 print "	<input TYPE=\"password\" NAME=\"tta3tier_password\" VALUE=\"$tta3tier_password\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tiertitle'}</b>","f3tiertitle"),"&nbsp;</td>\n";
print "		<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_title\" VALUE=\"$tta3tier_title\" cols=\"30'\" size=\"30\" ALIGN=left></td></tr>\n"; 
 print "  	<tr><td valign=top>",&hlink("<b>$text{'f_3tierdomain'}</b>","f3tierdomain"),"</td>\n"; 
 print "        <td valign=top><input TYPE=\"text\" NAME=\"tta3tier_domain\" VALUE=\"$tta3tier_domain\" cols=\"12\" size=\"12\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierstringcmd'}</b>","f3tierstringcmd"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_stringcmd\" VALUE=\"$tta3tier_stringcmd\" cols=\"60\" size=\"40\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierappkey1'}</b>","f3tierappkey1"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_appkey1\" VALUE=\"$tta3tier_appkey1\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierappkey2'}</b>","f3tierappkey2"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_appkey2\" VALUE=\"$tta3tier_appkey2\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierappkey3'}</b>","f3tierappkey3"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_appkey3\" VALUE=\"$tta3tier_appkey3\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierappkey4'}</b>","f3tierappkey4"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_appkey4\" VALUE=\"$tta3tier_appkey4\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierappkey5'}</b>","f3tierappkey5"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_appkey5\" VALUE=\"$tta3tier_appkey5\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
 print "	<tr><td valign=top>",&hlink("<b>$text{'f_3tierappkey6'}</b>","f3tierappkey6"),"</td>\n"; 
 print "	<td valign=top><input TYPE=\"text\" NAME=\"tta3tier_appkey6\" VALUE=\"$tta3tier_appkey6\" cols=\"20\" size=\"20\" ALIGN=left></td></tr>\n"; 
}

#script_cache_chek()
#Print javascript lines to check "ttacacheapp" object input fields
#
sub script_cache_chek
{
    print "     if ( emptyField(obj.tta3tier_login) == false ) {\n";
    print "          if ( emptyField(obj.tta3tier_password) == true ) {\n";
    print "                 alert(obj.tta3tier_password.name+\":\"+msg1+\"->\"+obj.tta3tier_password.value+\"<-\");\n";
    print "                 obj.tta3tier_password.focus();\n";
    print "                 return false;\n";
    print "          }\n";
    print "          if ( emptyField(obj.tta3tier_title) == true ) {\n";
    print "                 alert(obj.tta3tier_title.name+\":\"+msg1+\"->\"+obj.tta3tier_title.value+\"<-\");\n";
    print "                 obj.tta3tier_title.focus();\n";
    print "                 return false;\n";
    print "          }\n";
    print "     }\n";
}

# htmlCacheShowPassw(msgObj,formObj)
# Display all htmls labels to get input for "ttacacheapp" object 
sub htmlCacheaShowPassw
{
 print "/******************************************************************\n"; 
 print "   showPasswd(formObj)\n"; 
 print "   Show Password value from form.\n"; 
 print "*******************************************************************/\n"; 
 print "function showPasswd(formObj) {\n"; 
 print "   alert(\"Password es:\"+formObj.tta3tier_password.value+\"\");\n"; 
 print "}\n"; 
}

# htmlCheckAlias
# Out javascript to control aliases, it is need to get @_ with hash object list
sub htmlCheckAlias
{
  local (@obj);         

  print "/******************************************************************\n"; 
  print "   checkAlias_$_[0](Obj)\n"; 
  print "   checkAlias from the array and return false is already exist\n"; 
  print "*******************************************************************/\n"; 
  print "function checkAlias_$_[0](Obj) {\n"; 
  print "   var isalready = false; \n";
  print "   var listAlias = new Array();\n"; 
  @obj=eval("\&list_$_[0]()");
  $nItem=0;
  foreach $item (@obj) {print " listAlias[".$nItem++."] = \"".$item->{'alias'}."\";\n"; }

  print "   \n"; 
  print "   for (var i=0; i < listAlias.length; i++) {\n"; 
  print "       if ( Obj.value == listAlias[i] ) { \n"; 
  print "            isalready = true; \n";
  print "            break;\n"; 
  print "       }\n"; 
  print "   }\n"; 
  print "   if ( isalready == true ) { \n"; 
  print "          alert(Obj.name+\":\"+msg1+\"->\"+Obj.value+\"<-\");\n";
  print "                    Obj.focus();\n";
  print "   }\n"; 
  print "   return isalready;\n"; 
  print "}\n"; 
}

# htmlWinLdapUsers(msgObj,formObj)
# Open Window to show Users
sub htmlWinLdapUsers
{
 print "<input type=button onClick='window.open(\"/tarantella/tta_selusr.cgi?form=winldapusers\", \"selusr\", \"toolbar=no,menubar=no,scrollbar=yes,width=750,height=450\")' value=\"?\">\n";
}

sub load_scriptlist
{
# read the obj properties from file
   local(@script_list, $_, $d, $lnum, $title);
# Get Scripts List
	opendir(DIR, $config{'monitor_scripts_path'});
	foreach $d (readdir(DIR)) {
        	if ( $d =~ /(\.tcl)$/ ) {
              	$file_scr=$config{'monitor_scripts_path'}."/$d";
              	$lnum=0;
              	open(FILESCR, $file_scr);
              	while (<FILESCR>) {
                 	if (/^$config{'mon_title'}/ && $lnum gt 0 ) {
                        	$title=$_;
                        	$title=~s/$config{'mon_title'}//;
                        	push(@script_list, { 'desc' => $title,
                                    	'name' => $d,
                                    	'num' => scalar(@script_list) });
                        	last;
                        	}
                	$lnum++;
              	}
              	close(FILESCR);
        	}
	}
	closedir(DIR);
	@script_list= sort { $a->{'desc'} cmp $b->{'desc'} } @script_list;
  return @script_list;
}

#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->{appkey6} = $in{tta3tier_appkey6};
 
   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 ;
}

# 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 print_tta3tier
{
   local (@tta3tier) = @_;
   print "<tr><p> -------------------------</p<</tr>\n";   
   print "<tr><p>origin=".$tta3tier->{origin}." </p></tr>\n"; 
   print "<tr><p>target=".$tta3tier->{target}." </p></tr>\n";
   print "<tr><p>oudn=".$tta3tier->{oudn}." </p></tr>\n"; 
   print "<tr><p>action=".$tta3tier->{action}." </p></tr>\n"; 
   print "<tr><p>objtype=".$tta3tier->{objetype}." </p></tr>\n";
   print "<tr><p>login=".$tta3tier->{login}." </p></tr>\n";
   print "<tr><p>password=".$tta3tier->{password}." </p></tr>\n";
   print "<tr><p>title=".$tta3tier->{title}." </p></tr>\n";
   print "<tr><p>stringcmd=".$tta3tier->{stringcmd}." </p></tr>\n";
   print "<tr><p>domain=".$tta3tier->{domain}." </p></tr>\n";
   print "<tr><p>appkey1=".$tta3tier->{appkey1}." </p></tr>\n"; 
   print "<tr><p>appkey2=".$tta3tier->{appkey2}." </p></tr>\n"; 
   print "<tr><p>appkey3=".$tta3tier->{appkey3}." </p></tr>\n"; 
   print "<tr><p>appkey4=".$tta3tier->{appkey4}." </p></tr>\n"; 
   print "<tr><p>appkey5=".$tta3tier->{appkey5}." </p></tr>\n"; 
   print "<tr><p>appkey6=".$tta3tier->{appkey6}." </p></tr>\n"; 
}

sub scan_envsess {
         $ens_base=$config{'ens_base'}.$config{'tta_base'};
	 $UserName=~s/$config{'tta_ldapUser'}//;
	 $UserName=~s/,$config{'ldap_base'}//;
	 $UserName=~s/$config{'ens_base'}//;
	 $AppName=~s/$ens_base\///;
	 $AppName=~s/$config{'ens_base'}//;
	 $HostName=~s/...\/_dns\///;
	 $HostName=~s/$ens_base\///;
         if ( $debug eq 2 ) { print DebugLog "\nScanning $UserName ....\n";}
   	 $lnumUser =0 ;
         # First LDAP user  and second TTA user
         $userType="LDAP";
         @linUserName = split(/,/, $UserName);
         if ("$linUserName[0]" eq "$UserName") { 
              $userType="TTA";
              @linUserName = split(/\//, $UserName);
         }
	 $OuName="";
	 foreach $obj (@linUserName) {
              @UserPath= split(/=/,$obj);
              $lnumUser++;
  	      if ( $debug eq 2 ) { print DebugLog "$UserPath[0] -- $UserPath[1] \n"; }
              if ( "$userType" eq "LDAP" ) {
                   if ( $UserPath[0] eq "cn"  &&  $lnumUser eq 1 ) {
		        $NameUser=$UserPath[1];
                        last;
                   } else {
                        if ( "$OuName" ne "" ) { $OuName=",".$OuName; }
		        $OuName="ou=".$UserPath[1].$OuName;
	           }
              } else {
                   $lastOuName=$OuName;
                   if ( "$OuName" ne "" ) { $OuName=",".$OuName; }
		   $OuName="ou=".$UserPath[1].$OuName;
	      }
          }
          if ( "$userType" ne "LDAP" ) { 
                $NameUser=$UserPath[1]; 
                $OuName=$lastOuName;
          }
          if ( "$tta_username" eq "" ) { $tta_username=$NameUser; }
  	  if ( $debug eq 2 ) { print DebugLog "\nScanning $AppName ....\n";}
          $lnumApp = 0;
          @linAppName = split(/\//, $AppName);
          $NameAppGrp="";
	  foreach $obj (@linAppName) {
              @AppPath= split(/=/,$obj);
              if ( $lnumApp lt $#linAppName ) { 
                  if ( "$NameAppGrp" ne "" ) { $NameAppGrp=",".$NameAppGrp; }
	          $NameAppGrp="ou=".$AppPath[1].$NameAppGrp;
              }
              $lnumApp++;
  	      if ( $debug eq 2 ) { print DebugLog "$AppPath[0] -- $AppPath[1] \n"; }
          }
          $NameApp=$AppPath[1];
  	  if ( $debug eq 2 ) { print DebugLog "\nScanning $HostName ....\n";}
          $lnumHost = 0;
          @linHostName = split(/\//, $HostName);
          $NameHostGrp="";
	  foreach $obj (@linHostName) {
              @HostPath= split(/=/,$obj);
              if ( $lnumHost lt $#linHostName ) { 
                  if ( "$NameHostGrp" ne "" ) { $NameHostGrp=",".$NameHostGrp; }
	          $NameHostGrp=$HostPath[0]."=".$HostPath[1].$NameHostGrp;
              }
              $lnumHost++;
  	      if ( $debug eq 2 ) { print DebugLog "$HostPath[0] -- $HostPath[1] \n"; }
          }
          if ( $HostPath[1].length eq 0 ) {
               $NameHost=$HostPath[0];
          } else {
               $NameHost=$HostPath[1];
          }
#          if ( $NameHostGrp.length eq 0 ) {
#               $NameHostGrp=$NameAppGrp;
#               $NameHostGrp=~s/RIMA/servidores/g;
#          }
  	  if ( $debug eq 2 ) { print DebugLog "\n";}
}

# load_tta_emulses($temp_f)
# Returns an array of hashtable, each containing info about one webtop. Each hash
# will always contain the keys "alias" "name" "link" etc .
sub load_tta_emulses
{
# read the obj properties from file
   local(@ttasess, $_, %idx, $lnum, @lin);
 
	# start by reading from file List

	$lnum = 0;
	open(FILETTASESS, $temp_f);
	while(<FILETTASESS>) {
		 if (/\S/ && !/^[#\+\-]/ && $lnum gt 0 ) {
		        chomp($lin);
			@lin = split(/: /, $_, -1);
		        $lin[1]=~ s/"//g;
		        $is_space=chop($lin[1]);
                        if ( $is_space eq " " ) { chop($lin[1]); }
			push(@ttasess, { 'property' => $lin[0],
				    'value' => $lin[1],
				    'num' => scalar(@ttasess) });
			$idx{$lin[0]} = $ttasess[$#ttaobj];
			}
		$lnum++;
		}
	close(FILETTASESS);
    return @ttasess;
}
sub print_emulses
{
 print DebugLog "----------- SCANED PARAMS --------------------\n";
   print DebugLog " Usuario ($userType):       $NameUser\n";
   print DebugLog " Organization:      $OuName\n";
   print DebugLog " Aplicacion:       $NameApp \n";
   print DebugLog " Grupo Aplicacion:    $NameAppGrp \n";
   print DebugLog " Host:          $NameHost \n";
   print DebugLog " Grupo Hosts:       $NameHostGrp \n";
   print DebugLog " Domain:       $NameDomain \n";
   print DebugLog "----------------------------------------------\n";
}

sub outicons_table
# This is to output code for the "Tabs" interface menu 
{
          local ($i) = 0;
          foreach $lnk (@olinks) {
             print "<td valign=top align=center width=$per\%>\n";
             print "<table border bgcolor=#ffffff><tr><td><a href=$lnk>",
                   "<img src=$oicons[$i] alt=\"\" border=0></a>",
                   "</td></tr></table>\n";
             print "<a href=$lnk>$otitles[$i]</a></td>\n";
             $i++;
             if ($pos++ % $cols == $cols - 1) { print "</tr><tr>\n"; }
          }
          while($pos++ % $cols) {
                print "<td width=$per\%></td>\n";
          }
          print "</tr><tr>\n"; 
}

sub outconfig_icons
{
	local($i);
        local ($n) = 0;
	for($i=2; $i<@_; $i++) {
             print "<td valign=top align=center width=$per\%>\n";
             print "<table border bgcolor=#ffffff><tr><td><a href=$_[$i]->{'link'}>",
                   "<img src=$_[$i]->{'icon'} alt=\"\" border=0></a>",
                   "</td></tr></table>\n";
             print "<a href=$_[$i]->{'link'}>$_[$i]->{'name'}</a></td>\n";
             $n++;
             if ($pos++ % $cols == $cols - 1) { print "</tr><tr>\n"; }
        }
        while($pos++ % $cols) {
                print "<td width=$per\%></td>\n";
        }
        print "</tr><tr>\n"; 
}

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;
                  } 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;
                  }
             } 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;
                          }
     		  }
             }
        }
}

# list_files($wherepath)
# Returns an array of hashtable, each containing info about one file. Each hash
# will always contain the keys "alias" "name", etc
sub list_files
{
# read the filelist from file
  local ($wherepath); $wherepath = $_[0];   
  local ($temp_f, $elem);    
  local (@rv, $_, %idx, $lnum, @lin);
  local ($f_perm , $f_lsnum, $f_owner, $f_group, $f_size, $f_month);
  local ($f_day, $f_time, $f_name);

  $no_out=1;
  $temp_f = &tempname();
  $str=`(cd $wherepath ; ls -lt $ls_match >$temp_f) 2>/dev/null`;
  &webmin_log("list", $wherepath, $config{run_exec_user}, "$str");
#  if ( $str) {
	$lnum = 0;
	open(FILELIST, $temp_f);
	while(<FILELIST>) {
		s/\r|\n//g;
		@lin = split(/ /, $_, -1);
                $pos=0;
                $ifield=0;
                foreach $elem (@lin) {
                   if ( $elem ne "" ) {
                        if ( $pos eq 0 ) { $f_perm=$elem; }
                        if ( $pos eq 1 ) { $f_lsnum=$elem; }
                        if ( $pos eq 2 ) { $f_owner=$elem; }
                        if ( $pos eq 3 ) { $f_group=$elem; }
                        if ( $pos eq 4 ) { $f_size=$elem; }
                        if ( $pos eq 5 ) { $f_month=$elem; }
                        if ( $pos eq 6 ) { $f_day=$elem; }
                        if ( $pos eq 7 ) { $f_time=$elem; }
                        if ( $pos eq 8 ) { $f_name=$elem; }
                        $pos++;
                   }
                   $ifield++;
                }
                push(@rv,{ 'perm' => $f_perm , 'lsnum' => $f_lsnum,
                                'owner' => $f_owner, 'group' => $f_group,
                                'size' => $f_size, 'month' => $f_month,
                                'day' => $f_day, 'time' => $f_time,
                                'name' => $f_name,
                                'num' => scalar(@rv) });
                $idx{$lin[0]} = $rv[$#rv];
                $lnum++;
	}
	close(FILELIST);
#   }
return @rv;
}
1;  # Return true
