#!/usr/bin/perl
$|=1;

##############################################
##                                          ##
##  PROFILE MANAGER PREMIUM 2.1             ##
##  Build 2004-02-28                        ##
##                                          ##
##  Aytekin Tank                            ##
##  email: aytekin@interlogy.com            ##
##  http://www.interlogy.com/products/pmpre ##
##                                          ##
##  Copyright 1999-2004 Aytekin Tank.       ##
##                                          ##
##############################################


if($ENV{'SERVER_SOFTWARE'} =~ m/IIS/)
{
        if($root eq "" && $ENV{'PATH_TRANSLATED'} ne "")
        {
                my $pt = $ENV{'PATH_TRANSLATED'};
                my @pts = split(/\\/, $pt);
                $pts[-1] = "";
                $root = join "/", @pts;
        }
}
require "${root}lib/pm.lib";
require "${root}lib/payment.lib";
$strip_html = "no";
$iamadmin = 1;
&readit;
$data_dir = "${root}data";
$config_dir = "$data_dir/config";
$bg  = "background=\"images/dot.gif\""; #-disabled

if($input{'adminpass'} ne ""){
        $input{'pass'} = pm_encode($input{'adminpass'});
}
if($input{'password1'} ne ""){
        $input{'pass'} = pm_encode($input{'password1'});
}

if(-e "$data_dir/admin.pass"){
	use CGI;
	my $req = new CGI;
	if($input{'pass'} eq ""){
	   $input{'pass'} = $req->cookie("pmadm");
	}
	$admin_pass_file = "$data_dir/admin.pass";
	if(&admin_pass_check ne "yes"){
		print "Content-type: text/html \n\n";
		fatal_error("You are not authenticated, please login.<br>
			<form action=setup.cgi method=post> 
			<input type=hidden name=action value=$input{'action'}>
			<input type=hidden name=setcookie value=1>
			<table border=0>
			<tr><td>Password: </td><td> <input type=password size=10 name=adminpass> 
			<input type=submit name=submit value=Login></td></tr>
			</table>
		");
	}
	if($input{'setcookie'} == 1){
           my $packed_cookie = $req->cookie(
                                        -NAME           => "pmadm",
                                        -VALUE          => "$input{'pass'}",
                                        -EXPIRES        => "+1d",
                                        -PATH           => "/"
            );
	    print $req->header(-COOKIE => $packed_cookie);
	    $header_set = 1;
	}
}

if($input{'action'} eq ""){ 
	if( !(-e "$data_dir/status.OK") ){
		$input{'action'} = "install";
		if($input{'install_post'} eq "password"){
		   use CGI;
		   my $req = new CGI;
		   my $packed_cookie = $req->cookie(
						-NAME           => "pmadm",
						-VALUE          => "$input{'pass'}",
						-EXPIRES        => "+1h",
						-PATH           => "/"
		    );
		    print $req->header(-COOKIE => $packed_cookie);
		    $header_set = 1;
		}
	}
}

print "Content-type: text/html \n\n" unless $header_set;
&check_pmlib;
&get_configfile_name;
$xmloldcode = "";
parse_config($configfile);
parse_docs("docs.xml");

if($input{'action'} eq "help"){
	&help;
	exit;
}elsif($input{'action'} eq "print"){
	&print_this;
	exit;
}elsif($input{'action'} eq "documentation"){
	&documentation;
	exit;
}elsif($input{'action'} eq "install"){
	&install_header;
	&install;
	&install_footer;
	exit;
}else{
	&header_config;
}

if($input{'action'} eq "modified"){
	show_headline("setup.cgi", "Modifying...");
	&modified_config;
	&modified_message;
} elsif($input{'action'} eq "launch_button"){
	show_headline("setup.cgi", "Launch?");
	&launch_button($input{'continue'});
} elsif($input{'action'} eq "launch"){
	show_headline("setup.cgi", "Launching...");
	launch();
} elsif($input{'action'} eq "modify"){
	show_headline("setup.cgi", "Modify Config");
	&modify_config;
} elsif($input{'action'} eq "modify_listing"){
	show_headline("setup.cgi", "Modify Listing Preferences");
	&modify_config_section("listing");
} elsif($input{'action'} eq "modify_user_tracking"){
	show_headline("setup.cgi", "Modify User Tracking Preferences");
	&modify_config_section("user tracking");
} elsif($input{'action'} eq "modify_static_profile"){
	show_headline("setup.cgi", "Modify Static Profile Preferences");
	&modify_config_section("static profile");
} elsif($input{'action'} eq "modify_protected_directory"){
	show_headline("setup.cgi", "Modify Protected Directory Preferences");
	&modify_config_section("protected directory");
} elsif($input{'action'} eq "modify_random_quote"){
	show_headline("setup.cgi", "Modify Random Quote Preferences");
	&modify_config_section("random quote");
} elsif($input{'action'} eq "modify_advanced"){
	show_headline("setup.cgi", "Modify Advanced Preferences");
	&modify_config_section("advanced");
} elsif($input{'action'} eq "modify_subscriptions"){
	show_headline("setup.cgi", "Modify Subscription Preferences");
	&modify_config_section("subscriptions");
} elsif($input{'action'} eq "dbwiz"){
	&dbwiz();
} elsif($input{'action'} eq "paywiz"){
	show_headline("setup.cgi", "Payment Wizard");
	&paywiz();
} elsif($input{'action'} eq "modify_database"){
	show_headline("setup.cgi", "Modify Database Configuration");
	&modify_config_section("database");
} elsif($input{'action'} eq "modify_email"){
	show_headline("setup.cgi", "Modify Email Preferences");
	&modify_config_section("email");
} elsif($input{'action'} eq "modify_messaging"){
	show_headline("setup.cgi", "Modify Messaging Preferences");
	&modify_config_section("messaging");
} elsif($input{'action'} eq "modify_upload"){
	show_headline("setup.cgi", "Modify Upload Preferences");
	&modify_config_section("upload");
} elsif($input{'action'} eq "modify_files_and_directories"){
	show_headline("setup.cgi", "Modify Files and Directories");
	&modify_config_section("files and directories");
} elsif($input{'action'} eq "modify_templates"){
	show_headline("setup.cgi", "Templates");
	&modify_config_section("templates");
} elsif($input{'action'} eq "template_rules"){
	show_headline("setup.cgi", "Template Rules");
	&template_rules;
} elsif($input{'action'} eq "newtemplate"){
	show_headline("setup.cgi", "Add New Page");
	&newtemplate();
} elsif($input{'action'} eq "addnewtemplate"){
	show_headline("setup.cgi", "Adding New Page...");
	&addnewtemplate();
} elsif($input{'action'} eq "list_all"){
	show_headline("setup.cgi", "All Variables");
	&list_all_variables;
} elsif($input{'action'} eq "list_all_docs"){
	show_headline("setup.cgi", "All Documentation");
	&show_all_docs;
} elsif($input{'action'} eq "forget"){
	show_headline("setup.cgi", "Cancel All Changes");
	&forget_changes;

}else{
	show_headline("setup.cgi", "Setup Main");
	&setup_main;
}


&footer_config;


#----------------------------------------------------------------------------
#- SUBS
#----------------------------------------------------------------------------

sub help
{
        show_doc($input{'topic'});
}

sub print_this 
{
	print "<html><body bgcolor=#fff3d5><font size=1 face=arial>\n";
        print $input{'this'};
	print "</body></html>\n";
}


sub documentation
{
	#- fetch latest tutorials from interlogy site
	eval("use LWP::Simple");
	eval("\$input{'latest_tutorials'} = get(\"http://www.interlogy.com/products/pmpre/latest_tutorials.html\")");			

	#- show all admin panel docs
	$input{'docs'} = &get_all_docs;
	require("$config_dir/pmpre.cfg");
	&tempwiz("documentation");
}

sub addnewtemplate
{
	#- fix the name
	my $name = $input{'tempname'};
	$name =~ s/[^A-Za-z0-9_-]/_/g;

	#- check the type
	my $type = $input{'temptype'};
	if(!($type eq "member_tempz" || $type eq "show_tempz" || 
			$type eq "approved_tempz" || $type eq "admin_tempz")){
		fatal_error("Page type should be one of these: show, member, approved, admin.");
	}

	#- check if the template name already exists
	eval("\%actions =  ( $variable{'tempz'} )");
	if($actions{$name} ne ""){
		fatal_error("This template name already exists.<br>
			Please go back and choose a different name!");
	}

	#- check if the file already exists
	my $newfileloc = "templates/$input{'tempdir'}/t_$name.htm" ;
	my $newfile = $root.$newfileloc;
	if( -e $newfile ){
		fatal_error("This template($newfile) already exists.<br>
			Please go back and choose a different name!");
	}

	#- put body into the file
	open(NF, ">$newfile") or fatal_error("Cannot open $newfile, because: $!
			<br>Make sure your template directories are writable!");
	print NF $input{'tempbody'};
	close NF;

	#- change tempz array
	$input{'variable'} = "tempz";
	$input{'vvalue'} = "$variable{'tempz'}\n\t'$name'\t\t=>\t'$newfileloc', ";
	#print "<textarea cols=100 rows=20>$input{'vvalue'}</textarea>";

	#- change show/member/approved/admin permission arrays
	$input{'variable1'} = $type;
	$input{'vvalue1'} = "$variable{$type}, \"$name\"";

	#- launch
        &modified_config;

	$type =~ s/_tempz//g;
        print "<p><font size=2 face=arial><font color=green>Page has been successfully added!</font><p>
        Once launched, it can be linked such as this: 
	<table border=1 bordercolor=gray cellpadding=10 cellspacing=0 bgcolor=#f2eaea><tr><td>
		<font size=2 face=arial><font color=navy>
                &lt;a href=\"";
        if($type eq "show"){
                print "pm.cgi?action=$type&temp=$name&login=%%login%%&session=%%session%%";
        } else {
                print "pm.cgi?action=$type&temp=$name&session=%%session%%";
        }
        print "\"&gt;$name&lt;/a&gt;</font></font></td></tr></table></font> ";
        launch_button("newtemplate");	


}

sub newtemplate
{
	my $tempdirs = "\n<select name=tempdir>\n<option></option>";
	opendir(HERE,"${root}templates/") or fatal_error("Cannot opendir for new template:$!");
	foreach ( sort grep( -d "${root}templates/$_", readdir(HERE) ) ) {
		if($_ ne "." && $_ ne ".." && $_ ne "html"){
			if($_ eq "member"){
				$tempdirs .= "<option selected>$_</option>";
			}else{
				$tempdirs .= "<option>$_</option>";
			}
		}
	}
	closedir HERE;
	$tempdirs .= "\n</select>\n";
	print "
		<form action=setup.cgi method=post>	
		<input type=hidden name=action value=addnewtemplate>

		<table border=0>
		<tr>
		 <td>Type:</td>
		 <td>
			<select name=temptype>
			<option value=show_tempz>Show: public page</option>
			<option value=member_tempz selected>Member: login required page</option>
			<option value=approved_tempz>Approved: approved member only page</option>
			<option value=admin_tempz>Admin: admin page</option>
			</select>
		 </td>
		</tr>
		 <td>Name:</td>
		 <td><input type=text size=30 name=tempname> (e.g. \"update_news\")</td>
		</tr>
		</tr>
		 <td>Location:</td>
		 <td>$tempdirs</td>
		</tr>
		<tr>
		 <td valign=top>Body:</td>
		 <td valign=top><textarea name=tempbody wrap=soft cols=90 rows=20></textarea></td>
		</tr>
		</table>
		<input type=submit name=submit value=\"Add New Page\">
		</form>
		<p>
	";

}

sub forget_changes
{
	print "All your latest changes are cancelled.";
	unlink("$config_dir/latest.xml");

}


sub dbwiz
{
	show_headline("setup.cgi", "Database Wizard");

	@types = ("Text Field", "Text Area", "Pulldown Menu", "Radio Button",
			"Checkbox", "Upload Picture", "Password Field", "Hidden Field");

	#- check for do
	if($input{'do'} eq "addfieldform"){	
		&dbwiz_addfieldform;
	} elsif($input{'do'} eq "modifyfieldform"){	
		&dbwiz_modifyfieldform;
	} elsif($input{'do'} eq "addfield"){	
		if($input{'populate'} ne ""){
			&dbwiz_addfieldform;
		}else{
			&dbwiz_addmodifyfield("added");
		}
	} elsif($input{'do'} eq "modifyfield"){	
		if($input{'populate'} ne ""){
			&dbwiz_modifyfieldform;
		}else{
			if($input{'submit'} eq "Delete"){
				&dbwiz_delete_warning("deleted");
			}else{
				&dbwiz_addmodifyfield("modified");
			}
		}
	} elsif($input{'do'} eq "deletefield"){	
		&dbwiz_addmodifyfield("deleted");
	} elsif($input{'do'} eq "getcode"){	
		&dbwiz_getcode;	
	} else {
		&dbwiz_add_links;
	}
}

sub dbwiz_getcode
{
	if($input{'page'} eq "register"){
		my $register_code = dbwiz_get_form_code("register");
		my $register_code_html = html_code_showable($register_code);
		show_getcode("Registration Form Preview:", $register_code);
		show_getcode("Registration Form Source Code:", "<textarea cols=90 rows=20 onfocus=\"this.select()\">$register_code_html</textarea>");	
	}elsif($input{'page'} eq "modify"){
		my $modify_code = dbwiz_get_form_code("modify");
		my $modify_code_html = html_code_showable($modify_code);
		show_getcode("Modification Form Preview:", $modify_code);
		show_getcode("Modification Form Source Code:", "<textarea cols=90 rows=20 onfocus=\"this.select()\">$modify_code_html</textarea>");
	}elsif($input{'page'} eq "display"){
		my $display_code = dbwiz_get_display_code("display");
		my $display_code_html = html_code_showable($display_code);
		show_getcode("Profile Template Preview:", with_default_images($display_code), 1);
		show_getcode("Profile Template Source Code:", "<textarea cols=90 rows=20 onfocus=\"this.select()\">$display_code_html</textarea>");
	}

	print "<a href=\"javascript:history.go(-1)\">Go back</a>.";
}

sub with_default_images{
	my ($code) = (@_);
	foreach my $b(keys %base_image){
		my $d = $default{$b};
		$code =~ s/\%\%$b\%\%/$d/m;
	}
	return $code;
}

sub html_code_showable
{
	my ($code) = (@_);
	$newcode = "";
	foreach my $c(split "\n", $code){
		$c =~ s/&/&amp;/g;
		$c =~ s/</&lt;/g;
		$c =~ s/>/&gt;/g;
		$c =~ s/"/&quot;/g;
		$newcode .= "$c\n";
	}
	return $newcode;
}

sub show_getcode
{
	my ($subject, $put, $nocenter) = @_;
	print "
		<p>
		<font size=2 face=arial><b>$subject</b></font><br>
		<table border=0 bgcolor=#f4f6f7 bordercolor=navy width=700 cellspacing=3 cellpadding=4><tr><td>
	";
	print "<center>" if(!$nocenter);
	print $put;
	print "</center>" if(!$nocenter);
	print " <p> </table><p>";
}

sub get_location_sampledir
{
	my $sampledir = $input{'sample_dir'};
        if($ENV{'DOCUMENT_ROOT'} ne ""){
                my $root = $ENV{'DOCUMENT_ROOT'};
		$sampledir =~ s/\Q$root//;
        }else{
		$sampledir = "../";
	}
	return $sampledir;
}


sub get_location_pmcgi
{
        my $pmcgi= "";
        if($ENV{'SCRIPT_NAME'} ne ""){
                my $pt = $ENV{'SCRIPT_NAME'};
                if($pt =~ m/^(.*\/setup\.cgi)$/){
                        $pmcgi = $1;
			$pmcgi =~ s/setup\.cgi/pm\.cgi/;
                }
        }
	if($pmcgi eq ""){
		$pmcgi = "pm.cgi";
	}
	return $pmcgi;
}

sub dbwiz_get_display_code
{
	my ($display_type) = (@_); 
	my $code = "%%TEMPLATE:header%%\n%%TEMPLATE:header_myprofile%% \n\n";
 	$code .= "<p align=left>\n";
 	$code .= "    <table border=0 align=right><tr><td>\n";
	foreach(keys %base_image){
		$code .= "   <img src=%%$_%%><br>\n";
	}
	$code .= "   </td></tr></table>\n";
        my %base_descriptions;
        eval("\%base_descriptions = ($variable{'base_descriptions'});");
	foreach(@base){
		next if($_ eq "register_date");
		next if($_ eq "update_date");
		next if($_ eq "sortable_register_date");
		next if($_ eq "sortable_update_date");
		next if($_ eq "IP");
		next if($_ eq "ID");
		next if($_ eq "password");
		next if($_ eq "mailing");
		next if($_ eq "email");
		next if($base_descriptions{$_}{'type'} eq "hidden");
		next if($base_image{$_} ne "");
		my $label = $_;
		if($base_descriptions{$_}{'label'} ne ""){
			$label = $base_descriptions{$_}{'label'}
		}
		$code .= "$label: %%$_%%\n<br>\n";
	}
	$code .= "</p>\n\n%%TEMPLATE:footer%%\n";
	return $code;

}

sub dbwiz_get_form_code
{
	my ($form_type) = (@_); #- modify or register

	#- get all of the form fields
        my @base;
        eval("\@base = ($variable{'base'});");

	#- get the location of the pm.cgi
	$pmcgi = &get_location_pmcgi;

	#- get the descriptions of the fields	
	my %base_descriptions;
	eval("\%base_descriptions = ($variable{'base_descriptions'});");

	my $code = "\n";
	if($form_type eq "modify"){
		$code .= "<form action=pm.cgi method=post>\n";
		$code .= "<input type=hidden name=action value=modified>\n";
		$code .= "<input type=hidden name=login value=\"%%login%%\">\n";
		$code .= "<input type=hidden name=ID value=\"%%ID%%\">\n";
	}else{
		$code .= "<form action=$pmcgi method=post>\n";
		$code .= "<input type=hidden name=action value=register>\n";
	}
	$code .= "<table border=0>\n";
	$code .= "<tr><td><font color=navy size=2 face=arial><b>";
	if($form_type eq "modify"){
		$code .= "Modify:";
	} else {
		$code .= "Register:";
	}
	$code .= "</b></font><p></td><td></td></tr>\n";
	
	foreach my $field(@base){
		next if($field eq "");
		next if($base_descriptions{$field}{'label'} eq "");
		next if($base_descriptions{$field}{'type'} eq "Upload Picture");
		$code .= "<tr>\n";
		$code .= "	<td>
		<font size=2 face=arial color=navy>
		$base_descriptions{$field}{'label'}
		</font>
	</td>
	<td>
		";
		if($base_descriptions{$field}{'type'} eq "Text Field"){
			$size = 20;
			if($base_descriptions{$field}{'size'}>1){
				$size = $base_descriptions{$field}{'size'};
			}
			if($form_type eq "modify"){
				if($field eq "login"){
					$code .= "<font size=2 face=arial>%%login%%</font>\n";	
				}else{
					$code .= "<input type=text size=$size name=$field value=\"\%\%$field\%\%\">\n";
				}
			} else {
				$code .= "<input type=text size=$size name=$field>\n";
			}
		}elsif($base_descriptions{$field}{'type'} eq "Text Area"){
			$rows = 3;
			if($base_descriptions{$field}{'rows'}>1){
				$rows = $base_descriptions{$field}{'rows'};
			}
			$cols = 60;
			if($base_descriptions{$field}{'cols'}>1){
				$cols = $base_descriptions{$field}{'cols'};
			}
			if($form_type eq "modify"){
				$code .= "<textarea cols=$cols rows=$rows name=$field>\%\%$field\%\%</textarea>\n";
			}else{
				$code .= "<textarea cols=$cols rows=$rows name=$field></textarea>\n";
			}
		}elsif($base_descriptions{$field}{'type'} eq "Pulldown Menu"){
			$code .= "<select name=$field>\n";
			if($form_type eq "modify"){
				$code .= "\t<option>\%\%$field\%\%</option>\n";
			}
			$code .= "\t<option></option>\n";
			if($base_descriptions{$field}{'choices'} ne ""){
				open(F, "<$base_descriptions{$field}{'choices'}") 
					or print "Cannot open $config_dir/$base_descriptions{$field}{'choices'}!";
				while (my $line = <F>){
					$line =~ s/\n//; $line =~ s/\r//; $line =~ s/^ //;
					$code .= "\t<option>$line</option>\n";
				}
				close F;
			}
			$code .= "</select>\n";
		}elsif($base_descriptions{$field}{'type'} eq "Radio Button"){
			if($base_descriptions{$field}{'choices'} ne ""){
				open(F, "<$base_descriptions{$field}{'choices'}") 
					or print "Cannot open $config_dir/$base_descriptions{$field}{'choices'}!";
				while (my $line = <F>){
					$line =~ s/\n//; $line =~ s/\r//; $line =~ s/^ //;
					if($form_type eq "modify"){
						$code .= "<input type=radio name=$field value=\"$line\" \%\%CHECKED:$field:$line\%\%>
							<font size=2 face=arial>$line</font><br>\n";
					}else{
						$code .= "<input type=hidden name=$field value=no>
							<input type=radio name=$field value=\"$line\">
							<font size=2 face=arial>$line</font><br>\n";
					}
				}
				close F;
			}
		}elsif($base_descriptions{$field}{'type'} eq "Checkbox"){
			if($form_type eq "modify"){
				$code .= "<input type=hidden name=$field value=no>\n\t\t<input type=checkbox name=$field value=yes \%\%CHECKED:$field\%\%> \n";
			}else{
				$code .= "<input type=checkbox name=$field value=yes> \n";
			}
		}

		$code .= "	</td>\n";
		$code .= "</tr> \n\n";

	}
	$code .= "</table>\n\n";
	if($form_type eq "modify"){
		$code .= "<input type=submit name=submit value=\" Modify \">\n</form>\n";
	}else{
		$code .= "<input type=submit name=submit value=\" Register \">\n</form>\n";
	}
	return $code;
}

sub dbwiz_delete_warning
{
	#- check the field
	#- if it already does not exist on the database
	#- it is OK.

	print "
		<p><br><font color=black size=2 face=\"arial,verdana\">
		You are about to delete a database field!<br>
		Don't do it unless you know what you are doing!<br>
		If  you have already launched this field, deleting it <font color=red><b> may cause problems on the database</b></font>.
		<br>If this field is not the last field added, this action is not recommended  and might corrupt the database.
		<br>Make sure to backup your database before performing this action.
		</font>
		<p>
		<form action=setup.cgi method=get>
		<input type=hidden name=action value=dbwiz>
		<input type=hidden name=do value=deletefield>
		<input type=hidden name=field_name value=$input{'field_name'}>
		<input type=hidden name=field_label value=\"none\">
		<input type=submit name=submit value=\"Continue\">
		<p>
	";
		

}

sub is_base_field
{
	my ($field) = @_;
	my @mybase;
	eval("\@mybase = ($variable{'base'});");
	foreach(@mybase){
		if($field eq $_){
			return 1;
		}
	}
	return 0;
}

#------------------------------ ADDING
sub dbwiz_addmodifyfield
{
	my ($what) = @_;

	#- do the checks
	$input{'field_name'} =~ s/ /_/g;
	if($input{'field_name'} eq ""){
		fatal_error("Please go back and choose a field name!");
	}
	if($input{'field_label'} eq ""){
		fatal_error("Please go back and choose a field label!");
	}
	if(is_base_field($input{'field_name'}) && $what eq "added"){
		fatal_error("This field is already chosen, please find a different field name.");
	}
	if($input{'field_type'} eq "Text Field" || $input{'field_type'} eq "Password Field"){
		if($input{'field_size'}==0){
			$input{'field_size'} = 20;
		}
	}	
	if($input{'field_type'} eq "Text Area"){
		if($input{'field_cols'}==0){
			$input{'field_cols'} = 40;
		}
		if($input{'field_rows'}==0){
			$input{'field_row'} = 3;
		}
	}	
	
	$input{'field_name'} =~ s/\'/ /g;
	$input{'field_name'} =~ s/\"/ /g;
	my $fn = $input{'field_name'};

	#- change the base fields
	$input{'variable'} = "base";
	my $bvvalue = $variable{'base'};
	$bvvalue =~ s/\,$//;
	if($what eq "added"){
		$input{'vvalue'} = $bvvalue.", '$input{'field_name'}'";
	}elsif($what eq "deleted"){
		eval("\@mybases = ($variable{'base'});");
		if(@mybases>0)
		{
			my $count = 0;
			foreach $f (@mybases){
				if(!($f =~ m/$fn/)){
					$input{'vvalue'} .= "\n" if(($count++)%5==4);
					$input{'vvalue'} .= "$f, ";
				}
			}
		}else{
			$input{'vvalue'} = $bvvalue;
		}
	}else{
		$input{'vvalue'} = $bvvalue;
	}

	$input{'variable1'} = "base_descriptions";
	my $bdvvalue = $variable{'base_descriptions'};
	my $temp = "";
	foreach(split("\n", $bdvvalue)){
		if(!m/\'$fn\' =>/){
			$temp .= "\n$_";	
		}
	}
	$bdvvalue = $temp;
	$bdvvalue =~ s/\n/     /;
	$bdvvalue =~ s/\,$//;
	if($bdvvalue ne "" && $bdvvalue ne "     "){
		$bdvvalue .= ","; 
	}
	if($what ne "deleted")
	{
		$bdvvalue .= "     '$input{'field_name'}' => { ";
		$bdvvalue .= "'label' => '$input{'field_label'}', "; 
		if($input{'field_type'} eq "Text Field" || $input{'field_type'} eq "Password Field"){
			$bdvvalue .= "'size' => '$input{'field_size'}', "; 
		}elsif($input{'field_type'} eq "Text Area"){
			$bdvvalue .= "'cols' => '$input{'field_cols'}', "; 
			$bdvvalue .= "'rows' => '$input{'field_rows'}', "; 
		}elsif($input{'field_type'} eq "Pulldown Menu" || $input{'field_type'} eq "Radio Button"){
			my $choicefile = "$config_dir/choices_$input{'field_name'}.txt";
			open(F, ">$choicefile") or fatal_error("Cannot create $choicefile file: $!<br>\n");
			print F $input{'field_values'};
			close F;
			$bdvvalue .= "'choices' => '$choicefile', ";
		}
		$bdvvalue .= "'type' => '$input{'field_type'}' }";
	}
	$bdvvalue =~ s/     /\n/g;
	$bdvvalue =~ s/\n\n/\n/g;
	$bdvvalue =~ s/\n\n/\n/g;
	$input{'vvalue1'} = $bdvvalue;

        if($what eq "added" && $input{'field_type'} eq "Upload Picture"){
                $input{'variable2'} = "base_image";
                $input{'vvalue2'} = "$variable{'base_image'},\n\"$input{'field_name'}\" =>      \"$input{'field_label'}\"";
        }

	&modified_config;	

	print "<p>Field has been $what successfully!<p>";

	launch_button("dbwiz");

}

#------------------------------- FORMS
sub dbwiz_modifyfieldform
{
	if($input{'field_type'} eq ""){
		my %base_descriptions;
		my $name = $input{'field_name'};
		eval("\%base_descriptions = ($variable{'base_descriptions'});");
		$input{'field_type'} = $base_descriptions{$name}{'type'};
		$input{'field_label'} = $base_descriptions{$name}{'label'};
	}
	if($input{'field_type'} eq "Pulldown Menu" || $input{'field_type'} eq "Radio Button"){
		if( open(F, "<$config_dir/choices_$input{'field_name'}.txt") ){
			while(<F>){
				$input{'field_values'} .= $_; 
			}
			close F;
		}
	}
	dbwiz_fieldform("modifyfield", "Modify Field");
}

sub dbwiz_addfieldform
{
	dbwiz_fieldform("addfield", "Add Field");
}

sub dbwiz_fieldform
{
	my ($nextdo, $button) = @_;
	print " <p>
		<form action=setup.cgi method=post>
		<input type=hidden name=action value=dbwiz>
		<input type=hidden name=field_type value=\"$input{'field_type'}\">
		<input type=hidden name=do value=$nextdo>
		<table border=0>
		<tr><td width=100>
		<b>Field Name:</b>
		</td><td>
	";
	if($nextdo eq "modifyfield"){
		print "$input{'field_name'}";
		print "<input type=hidden name=field_name value=\"$input{'field_name'}\">";

	}else{
		print "<input type=text name=field_name value=\"$input{'field_name'}\" size=20> (e.g. \"first_name\")";
	}
	print "\n </td></tr>\n";
		#if($input{'field_type'} eq ""){
		if($input{'do'} ne "addfieldform")
		{
			print "
				<tr><td>
				<b>Field Type:</b>
				</td><td>
			";
			print "\n\n<select name=field_type>";
			foreach(@types){
				if($input{'field_type'} eq "$_"){
					print " <option selected>$_</option> \n";
				}else{
					print " <option>$_</option> \n";
				}
			}
			print "</select>	\n\n";
			print "
				</td></tr>
			";
		}
		#}
	print "
		<tr><td>
		<b>Field Label:</b>
		</td><td>
		<input type=text name=field_label value=\"$input{'field_label'}\" size=20> (e.g. \"First Name\")
		</td></tr>
	";
	if($input{'field_type'} eq "Text Field" || $input{'field_type'} eq "Password Field"){
		dbwiz_addfieldform_line("field_size", "Text Size", 20);
	}elsif($input{'field_type'} eq "Text Area"){
		dbwiz_addfieldform_line("field_cols", "Column Width", 40);
		dbwiz_addfieldform_line("field_rows", "Number of Rows", 3);
	}elsif($input{'field_type'} eq "Pulldown Menu"  || $input{'field_type'} eq "Radio Button"){
		dbwiz_addfieldform_line("field_values", "List of choices");
	}
	print "\n</table><blockquote><input type=submit name=submit value=\"    $button    \">";
	if($nextdo eq "modifyfield"){
		print "\n<input type=submit name=submit value=\"Delete\">\n\n<p>\n";
	}
	print "</blockquote></form>\n\n<p>\n";

}

#-------- FORMLINE
sub dbwiz_addfieldform_line
{
	my($name, $label, $default) = @_;
	print "
		<tr><td>
		<b>$label:</b>
		</td><td>
	";
	if($name eq "field_size" || $name eq "field_cols" || $name eq "field_rows"){
		print "<input type=text name=$name value=\"$default\" size=3>";
	}
	if($name eq "field_values"){
		my $linesout = $input{'field_values'};
		if($input{'populate'} eq "Countries"){
			open(F, "<$config_dir/choices_pmcountries.txt") or print "Cannot open $config_dir/choices_pmcountries.txt!";
			while (my $line = <F>){
				$line =~ s/\n//; $line =~ s/\r//; $line =~ s/^ //;
				$linesout .= "$line\n";
			}
			close F;
		} elsif($input{'populate'} eq "States"){
			open(F, "<$config_dir/choices_pmstates.txt") or print "Cannot open $config_dir/choices_pmstates.txt!";
			while (my $line = <F>){
				$line =~ s/\n//; $line =~ s/\r//; $line =~ s/^ //;
				$linesout .= "$line\n";
			}
			close F;
		} elsif($input{'populate'} eq "Numbers"){
			if(${input{'number_start'}} > ${input{'number_end'}}){
				for($i=${input{'number_start'}}; $i>=${input{'number_end'}}; $i--){
					$linesout .= "$i\n";
				}
			}else{
				for($i=${input{'number_start'}}; $i<=${input{'number_end'}}; $i++){
					$linesout .= "$i\n";
				}
			}
		}
		print "<textarea name=$name cols=60 rows=20>$linesout</textarea>";
	}
	print " </td> ";
	if($name eq "field_values" && $input{'field_type'} eq "Pulldown Menu"){
		print "
		<td valign=top>
			<input type=submit name=populate value=\"Countries\">
			<br><br>
			<input type=submit name=populate value=\"States\">
			<br><br>
			<input type=submit name=populate value=\"Numbers\"> 
			between 
			<input type=text name=number_start value=\"\" size=4>
			and 
			<input type=text name=number_end value=\"\" size=4> 
			<br><br>
			<input type=submit name=populate value=\"Clear\">
		</td>
		";
	}
	print " </tr> ";
}

sub dbwiz_add_links
{

	print "<p><font size=2 face=arial><b>Step 1: Add/Modify Database Fields.</b></font>";

	#-----------addnew
	print " <p>
		<form action=setup.cgi method=get>
		<input type=hidden name=action value=dbwiz>
		<input type=hidden name=do value=addfieldform>
		<font size=2 face=arial>Add a new </font>
		<select name=field_type>";
	foreach(@types){
		print " <option>$_</option> \n";
	}
	print "</select> <input type=submit name=submit value=Add></form>\n\n<p>\n";

	#-------------modify
	print " <p><font size=2 face=arial>
		<form action=setup.cgi method=get>
		<input type=hidden name=action value=dbwiz>
		<input type=hidden name=do value=modifyfieldform>
		Modify 
		<select name=field_name>
		<option> </option> 
	";
	my @names = ();
	eval("\@names = ($variable{'base'});");
	foreach(@names){
		if(
			$_ ne "ID" &&
			$_ ne "register_date" &&
			$_ ne "update_date" &&
			$_ ne "IP" &&
			$_ ne "password" &&
			$_ ne "sortable_register_date" &&
			$_ ne "sortable_update_date" 
		){
			print " <option>$_</option> \n";
		}
	}
	print "</select> field <input type=submit name=submit value=Modify></form>\n\n<p></font>\n";

	#-------------create form
	#remember the last time, save it in a last_form_base_order.txt
	
	print "<p><br><br><font size=2 face=arial><b>Step 2: Update Templates.</b></font>";
	print " 
		<font face=arial size=2>
		<ul>
		<b>Manual Update</b>
		<ul>
		<li> <a href=setup.cgi?action=dbwiz&do=getcode&page=register>Create sample form for Registration</a>
		<li> <a href=setup.cgi?action=dbwiz&do=getcode&page=modify>Create sample form for Modification Template</a>
		<li> <a href=setup.cgi?action=dbwiz&do=getcode&page=display>Create sample page for Profile Template</a>
		</ul>
		</ul>
		<!-- not implemented
		<ul>
		<br><b>Option 2: Automatic Update</b>
		<br>
		Caution: This will override your current changes on these templates!
		<ul>
			<form action=setup.cgi method=get>
			<input type=hidden name=action value=autoupdate>
			<input type=checkbox name=register value=yes checked>Registration form template<br>
			<input type=checkbox name=modify value=yes checked>Modification form template<br>
			<input type=checkbox name=display value=yes>Profile template<br>
			<input type=checkbox name=static_display value=yes>Static Profile template<br>
			<input type=submit name=submit value=Update>
			</form>
		</ul>
		</ul>
		-->
	";
}

sub setup_main
{
	my $i = 0;
	print "<center><table border=0 width=90% cellpadding=3 cellspacing=3 align=right>";
	foreach $t(sort keys %listtopics){
		next if ($t eq "");
		$i++;
		print "\n<tr>" if($i%2);
		print "\n<td valign=top width=50%>";
		$tunderscore = $t;
		$tunderscore =~ s/ /_/g;
		print "<b><a href=setup.cgi?action=modify_${tunderscore}>".uc($t)." ($listtopics{$t})</a></b><br>";
		foreach $v(@variable_order){
			if($topic{$v} eq $t){
				print "<font size=2 face=\"verdana,arial\">
					<li><a href=setup.cgi?action=modify&variable=$v>$desc{$v}</a>
					</font>";
			}
		}
		print "</td>";
		print "</tr>" unless($i%2);
	}
	print "</table></center>";
}

sub template_rules
{
	print "<font size=2 face=arial>Please Note: Changes will not take effect until you 
		<a href=setup.cgi?action=launch_button&continue=template_rules>launch them</a>!</font>";

	#eval("\%rules = ( $variable{'template_rules'} )");

	if($input{'do'} eq "modify" || $input{'do'} eq "add" || $input{'do'} eq "delete" ){
		#print "<textarea cols=50 rows=20>\n";
		my $action = $input{'rule_action'};
		my $line = " { 'action' => '$input{'rule_action'}', 'field' => '$input{'rule_field'}', 'text' => '$input{'rule_text'}', 'temp'=> '$input{'rule_temp'}' }, ";
		my $c = 0;
		foreach my $l(split("\n", $variable{'template_rules'})){
			if($input{'ruleid'} == $c++ && $input{'do'} ne "delete"){
				$ruleshash .= "$line\n";
			}else{
				$ruleshash .= "$l\n" unless ($input{'do'} eq "delete" && ($input{'ruleid'} eq ($c-1)));
			}
		}
		if($input{'do'} eq "add"){
			$ruleshash .= $line;
		}
	}else{
		$ruleshash = $variable{'template_rules'};
	}

	#print "<textarea cols=50 rows=20>\n";
	#print $ruleshash;
	#print "</textarea>";

	eval("\@rules = ( $ruleshash )");

        $ruleid=0;
        $ruleid = @rules;
        &template_rule_form($ruleid--);
        foreach(reverse @rules){
                &template_rule_form($ruleid--, $_->{'action'}, $_->{'field'}, $_->{'text'}, $_->{'temp'});
        }

	$input{'variable'} = "template_rules";
	$input{'vvalue'} = $ruleshash;
	&modified_config;	

}

sub install_header
{

	print "
		<html>
		 <body bgcolor=#f4f6f7>
		 <center>
		 <table border=0 width=80%>
			 <tr>
			    <td valign=top bgcolor=#F7F9D2>
				 <blockquote>
	";
}

sub install
{

	#- install log
	if( open(IL, "<$data_dir/install.status") ){
		($page) = <IL>;
		close IL;
		if($page eq "100"){
			return;
		}
	}else{
		$page = 0;
		chmod 0777, $data_dir;
		change_install_status($page);
	}	

	if($input{'install_post'} eq "password"){
		if($input{'password1'} ne $input{'password2'}){
                        fatal_error("Passwords don't match! Please go back and enter a new password.");
		}
		if(length($input{'password1'})<3){
                        fatal_error("Password is too short! Please go back and enter a new password.");
		}

		open(AP, ">${data_dir}/admin.pass") or 
                        fatal_error("Cannot create a ${data_dir}/admin.pass
                                <br>Please make sure data directory and everything inside is writable.");
		print AP crypt($input{'password1'}, "pm");
		close AP;

		open(DB, ">${data_dir}/pm.dat");
		print DB "";
		close DB;

		$page = 1;
		change_install_status($page);
	} elsif($input{'install_post'} eq "server_settings"){
		&create_dir($input{'static_path'}) if($input{'create_static'} eq "yes");
		if($input{'create_image'} eq "yes"){
			if( "${root}images/" ne  $input{'image_path'} ){
				&create_dir($input{'image_path'});
				use File::Copy;
				opendir(HERE,"${root}images/") or fatal_error("Cannot open directory:$!");
				foreach (map { m/(.*\.gif|.*\.png)/i } readdir HERE) {
					if( !copy("${root}images/$_", "$input{'image_path'}$_") ){
						 print "
							<b>Warning:</b>
							While trying to copy image files under ${root}images/ directory,
							there has been a problem: $!\n<br>
							To solve the problem, please go to your FTP client make sure
							${root}images/ directory exists and writable! Then reload this page!<p><br><hr><p>\n"
						if( $imagewarning++ < 1);
					}
				}
				closedir HERE;
			}
		}
		&create_htaccess($input{'member_only_path'}) if($input{'create_member_only'} eq "yes");
		&set_server_details_config;
		&modified_config;
		$page = 3;
		change_install_status(3);
	} elsif($input{'install_post'} eq "create_samples"){
		if($input{'create_samples'} eq "yes"){
			#- find the url of the cgi file REQUEST_URI or PATH_INFO
                        my $uripm = "cgi/pm.cgi";
                        my $urisearch = "cgi/search.cgi";
                        my $uriadmin = "cgi/admin.cgi";
			if($ENV{'REQUEST_URI'} ne ""){
				$uripm = $ENV{'REQUEST_URI'};
				$uripm =~ s/setup\.cgi/pm\.cgi/;
				$urisearch = $ENV{'REQUEST_URI'};
				$urisearch =~ s/setup\.cgi/search\.cgi/;
				$uriadmin = $ENV{'REQUEST_URI'};
				$uriadmin =~ s/setup\.cgi/admin\.cgi/;
			}
			my @samplefiles = ("index.html", "search.html", "login.html", "register.html");
			$overwrite = "";
			foreach my $s(@samplefiles){
				my $overwritethis = 0;
				my $newfile = "$input{'sample_dir'}$s";
				if(-e $newfile){
					if($newfile =~ m/index\.html/){
						open(N, "<$newfile");
						while(<N>){
							if(m/OVERWRITE THIS FILE/){
								$overwritethis = 1;
								last;
							}
						}
						close N;
					}
					$overwrite .= "$newfile " unless($overwritethis);
				}
			}
			if($overwrite ne "" && $input{'really'} ne "yes"){
				print "
					Some files already exist, do you want to still overwrite them and create sample files?
					<p>
					If you would like to create samples files on a different directory, go back and change 
					the directory location you have entered. 
					If you would like to overwrite the exising file, click on \"Yes\", otherwise 
					if you would like to continue without creating any sample files, click on \"No\".
					<p>
					<table border=0>
					<tr><td>

					<form>
					<input type=button value=\" Back \" onclick=\"history.go(-1);\">
					</form>

					</td><td>
					<form action=setup.cgi method=post>
					<input type=hidden name=create_samples value=yes>
					<input type=hidden name=really value=yes>
					<input type=hidden name=sample_dir value=\"$input{'sample_dir'}\">
					<input type=hidden name=install_post value=create_samples>
					<input type=submit name=submit value=\" Yes \">
					</form>

					</td><td>
					<form action=setup.cgi method=post>
					<input type=hidden name=create_samples value=no>
					<input type=hidden name=sample_dir value=\"$input{'sample_dir'}\">
					<input type=hidden name=install_post value=create_samples>
					<input type=submit name=submit value=\" No \">
					</form>
					</td></tr>
					</table>
				";
				return;
			}else{
				foreach my $s(@samplefiles)
				{
					my $oldfile = "${root}templates/html/$s";
					my $newfile = "$input{'sample_dir'}$s";
					open(OF, "<$oldfile") or fatal_error("Cannot open $oldfile: $! [1]<br>");
					my @oldcontent = <OF>;
					close OF;
					my $newcontent = join(" ", @oldcontent);
					$newcontent =~ s/pm\.cgi/$uripm/g;
					$newcontent =~ s/search\.cgi/$urisearch/g;
					$newcontent =~ s/admin\.cgi/$uriadmin/g;
					open(NF, ">$newfile") or fatal_error("Cannot open $newfile: $! [2]<br>
							Make sure $input{'sample_dir'} directory is writable
							or go back and define a different directory.");
					print NF $newcontent;
					close NF;	
				}
			}
		}

		$page = 4;
		change_install_status(4);
	}

	if($input{'gopage'} > 0){
		change_install_status($input{'gopage'});
		$page = $input{'gopage'};
	}

	if($page eq "0"){
		if(-e "${data_dir}/admin.pass"){
			$page = 1;
		}else{
			show_headline("setup.cgi", "Installation: Admin Password");
			&install_admin_pass_form;
			return;
		}
	}

	if($page eq "1"){
		show_headline("setup.cgi", "Installation: Checking Files and Permissions");
		&install_check_permissions;
	} elsif($page eq "2"){
		show_headline("setup.cgi", "Installation: Server Details");
		&install_server_details_form;
	} elsif($page eq "-1"){
		show_headline("setup.cgi", "Installation: Disabled");
		&install_database_form;
	} elsif($page eq "3"){
		show_headline("setup.cgi", "Installation: Create Samples");
		&install_samples_form;
	} elsif($page eq "4"){
		show_headline("setup.cgi", "Installation: Launching New Configuration");
		&launch_new_config;	
		open(S, ">${data_dir}/status.OK");
		print S "OK";
		close S;
	} elsif($page eq "5"){
		show_headline("setup.cgi", "Installation: Performing tests");
		&install_complete_form;
	}else{
		show_headline("setup.cgi", "Installation: Undefined");
		print "Undefined page..";
	}
}

sub install_footer
{
	print "
				 </td>
			 </tr>
		 </table>
		 </center> 
		 </body>
	";
}

sub launch_new_config
{
	$_ = 1;
	print "<center><p><font color=gray>Creating the configuration for the first time...</font></p></center>";
	&get_configfile_name;
	$xmlcode = "";
	$xmloldcode = "";
	parse_config($configfile);
	launch();
	my $sampledir = get_location_sampledir();
	print "<center>
			<font color=green>
			Installation is COMPLETE!	
			<br>
			Refresh this page to go to the configuration panel... or
			<br>
			<a href=$sampledir>Go to the sample files created on the last step to test everything!</a>

		</font></p></center>";

}

sub install_complete_form
{
	print "To complete installation...";
}

sub install_database_form
{


}

sub create_dir
{
	my ($dir) = @_;	
	#-- create access directory
	mkdir($dir, 0777);
	unless(-e $dir){
		fatal_error("Cannot create directory: $dir");
	 }

}

sub create_htaccess
{
	my ($dir) = @_;	

	#-- create access directory
	mkdir($dir, 0777);
	unless(-e $dir){
		fatal_error("Cannot create directory: $dir");
	 }

	 #-- create access file
	 open(HT, ">${dir}.htaccess");
	 print HT "AuthUserFile ${dir}.htpassword
AuthGroupFile /dev/null
AuthName \"Only Approved Member Access to this directory\"
AuthType Basic

<Limit GET POST>
require valid-user
</Limit>

Order allow,deny
Satisfy any

#----------------------------------------
# IPs temporarily inserted by approved.cgi
#----------------------------------------
	";
	 close HT;
	 unless(-e "${dir}.htaccess"){
		fatal_error("Cannot create file: ${dir}.htaccess<br>Make sure ${dir} directory is writable!");
	 }
	 chmod(0777, "${dir}.htaccess");

	 #-- create password file
	 unless(-e "${dir}.htpassword"){
		 open(HTP, ">${dir}.htpassword");
		 print HTP "";
		 close HTP;
	 }
	 chmod(0777, "${dir}.htpassword");
	 unless(-e "${dir}.htpassword"){
		fatal_error("Cannot create file: ${dir}.htpassword<br>Make sure ${dir} directory is writable!");
	 }

	 unless(-e "${dir}index.html"){
		 open(HTP, ">${dir}index.html");
		 print HTP "You can see this page or any other file under this directory because you are approved!";
		 close HTP;
	 }
	 chmod(0777, "${dir}index.html");


}

sub set_server_details_config
{
	if($input{'static'} eq "yes"){
		$input{'variable'} = "static_pages";
		$input{'vvalue'} = "yes";	
	}else{
		$input{'variable'} = "static_pages";
		$input{'vvalue'} = "no";	
	}

	$input{'variable1'} = "static_url";
	$input{'vvalue1'} = $input{'static_url'};

	$input{'variable2'} = "static_dir";
	$input{'vvalue2'} = $input{'static_path'};

	$input{'variable3'} = "mail_method";
	$input{'vvalue3'} = $input{'mail_method'};

	$input{'variable4'} = "sendmail";
	$input{'vvalue4'} = $input{'sendmail'};

	$input{'variable5'} = "smtp_server";
	$input{'vvalue5'} = $input{'smtp'};

	$input{'variable6'} = "from";
	$input{'vvalue6'} = $input{'from'};

	$input{'variable7'} = "imageswww";
	$input{'vvalue7'} = $input{'image_url'};

	$input{'variable8'} = "imagesdir";
	$input{'vvalue8'} = $input{'image_path'};

	my $content_pass_www = $input{'member_only_url'};
	$content_pass_www =~ s/http:\/\///i;

	$input{'variable9'} = "content_pass_www";
	$input{'vvalue9'} = $content_pass_www;

	my $content_pass_file = $input{'member_only_path'};
	$input{'variable10'} = "content_pass_file";
	$input{'vvalue10'} = $content_pass_file.".htpassword";

	my $content_htaccess_file = $input{'member_only_path'};
	$input{'variable11'} = "content_htaccess_file";
	$input{'vvalue11'} = $content_pass_file.".htaccess";

}

sub install_samples_form
{
	my $sampledir = "";
	if($ENV{'SCRIPT_FILENAME'} ne ""){
                my $pt = $ENV{'SCRIPT_FILENAME'};
		if($pt =~ m/^(.*)cgi\/setup\.cgi/){
			$sampledir = $1;
		}
	}
	if($sampledir eq "" && $ENV{'PATH_TRANSLATED'} ne ""){
                my $pt = $ENV{'PATH_TRANSLATED'};
		if($pt =~ m/^(.*)cgi\\setup\.cgi/){
			$sampledir = $1;
		}
	}
	if($sampledir eq "")
	{
		if($ENV{'DOCUMENT_ROOT'} ne ""){     
			$sampledir = "$ENV{'DOCUMENT_ROOT'}/";
		}elsif($ENV{'PATH_TRANSLATED'} ne ""){ #- for IIS
			my $pt = $ENV{'PATH_TRANSLATED'};
			my @pt = split(/\\/, $pt);
			$pt[-1] = "";
			$sampledir = join "/", @pt;
		}else{		
			$sampledir = "/your/www/path/";
		}
	}

	print("
		<p>
		Installation will now create new sample HTML files for you.
		The files will include forms and links to some features of 
		Profile Manager Premium. You may integrate them into your site later.
		<br>
		<form action=setup.cgi method=post>
		<input type=checkbox name=create_samples value=yes checked>
		Yes, create these sample HTML pages for me:
		<ul>
		<li><i>index.html</i>
		<li><i>login.html</i>
		<li><i>search.html</i>
		<li><i>register.html</i>
		</ul>
		<br>
		Under this directory:
		<input type=text size=30 name=sample_dir value=\"$sampledir\">
		<p>
		<input type=hidden name=install_post value=create_samples>
		<input type=submit name=submit value=Continue>
		</form>
		<p>

	");

}

sub install_server_details_form
{
	#-- guess static url:
	if($ENV{'HTTP_HOST'} ne ""){   
		$static_url = "http://$ENV{'HTTP_HOST'}/profiles/";
	}elsif($ENV{'SERVER_NAME'} ne ""){     
		$static_url = "http://$ENV{'SERVER_NAME'}/profiles/";
	}elsif($ENV{'SERVER_ADDR'} ne ""){    
		$static_url = "http://$ENV{'SERVER_ADDR'}/profiles/";
	}else{
		$static_url = "http://www.yourdomain.com/profiles/";
	}

	#-- guess static path
	if($ENV{'DOCUMENT_ROOT'} ne ""){     #- for apache
		$static_path = "$ENV{'DOCUMENT_ROOT'}/profiles/";
	}elsif($ENV{'PATH_TRANSLATED'} ne ""){ #- for IIS
		my $pt = $ENV{'PATH_TRANSLATED'};
		my @pt = split(/\\/, $pt);
		if(@pt>3){
			$pt[-3] = "profiles/";
			pop(@pt);
			pop(@pt);
		}else{
			$pt[-1] = "profiles/";
		}
		$static_path = join "/", @pt;
	}else{		#- in case
		$static_path = "/your/www/path/profiles/";
	}

	#- guess email things
	unless($ENV{'SERVER_SOFTWARE'} =~ m/IIS/){
		$sendmail = `which sendmail`;
		if(!($sendmail =~ m/sendmail/)){
			my $ss = `whereis sendmail`;
			if($ss ne ""){
				foreach (split(/ /, $ss)){
					if($_ =~ m/\/sendmail$/){
						$sendmail = $_;
						last;
					}	
				}
			}else{
				@sendmailtest = ("/usr/sbin/sendmail", "/bin/sendmail",
						"/sbin/sendmail",  "/usr/local/bin/sendmail");
				foreach( @sendmailtest ){
					if( -e $_ ){
						$sendmail = $_;
						last;
					}	
				}
			}
		}

	}

	if($ENV{'HTTP_HOST'} ne ""){   
		my $smtph = $ENV{'HTTP_HOST'};
		$smtph =~ s/^www\.//;
		$smtp = "smtp.$smtph";
	}elsif($ENV{'SERVER_NAME'} ne ""){     
		my $smtph = $ENV{'SERVER_NAME'};
		$smtph =~ s/^www\.//;
		$smtp = "smtp.$smtph";
	}else{
		$smtp = "smtp.yourdomain.com";
	}

	if($sendmail ne ""){
		$emailrecommend = "<i><font size=1>Sendmail is recommended for your server.</font></i>";
		$emailradio = "
		<input type=radio name=mail_method value=sendmail checked> Sendmail
		<input type=radio name=mail_method value=SMTP> SMTP
		";
	}else{
		$emailrecommend = "<i><font size=1>SMTP is recommended for your server.</font></i>";
		$emailradio = "
		<input type=radio name=mail_method value=sendmail> Sendmail
		<input type=radio name=mail_method value=SMTP checked> SMTP
		";
	}
	$from = $ENV{'SERVER_ADMIN'};

	#-- guess image url:
	if($ENV{'HTTP_HOST'} ne ""){   
		$image_url = "http://$ENV{'HTTP_HOST'}/images/";
	}elsif($ENV{'SERVER_NAME'} ne ""){     
		$image_url = "http://$ENV{'SERVER_NAME'}/images/";
	}elsif($ENV{'SERVER_ADDR'} ne ""){    
		$image_url = "http://$ENV{'SERVER_ADDR'}/images/";
	}else{
		$image_url = "http://www.yourdomain.com/images/";
	}

	#-- guess image path
	if($ENV{'DOCUMENT_ROOT'} ne ""){     #- for apache
		$image_path = "$ENV{'DOCUMENT_ROOT'}/images/";
	}elsif($ENV{'PATH_TRANSLATED'} ne ""){ #- for IIS
foreach(keys %ENV){
	#print "<li>$_ => $ENV{$_}";
}
		my $pt = $ENV{'PATH_TRANSLATED'};
		my @pt = split(/\\/, $pt);
		if(@pt>3){
			$pt[-3] = "images/";
			pop(@pt);
			pop(@pt);
		}else{
			$pt[-1] = "images/";
		}
		$image_path = join "/", @pt;
	}else{		#- in case
		$image_path = "/your/www/path/images/";
	}

	#-- guess member only url:
	if($ENV{'HTTP_HOST'} ne ""){   
		$member_only_url = "http://$ENV{'HTTP_HOST'}/member-only/";
	}elsif($ENV{'SERVER_NAME'} ne ""){     
		$member_only_url = "http://$ENV{'SERVER_NAME'}/member-only/";
	}elsif($ENV{'SERVER_ADDR'} ne ""){    
		$member_only_url = "http://$ENV{'SERVER_ADDR'}/member-only/";
	}else{
		$member_only_url = "http://www.yourdomain.com/member-only/";
	}

	#-- guess member-only path
	if($ENV{'DOCUMENT_ROOT'} ne ""){     #- for apache
		$member_only_path = "$ENV{'DOCUMENT_ROOT'}/member-only/";
	}elsif($ENV{'PATH_TRANSLATED'} ne ""){ #- for IIS
		my $pt = $ENV{'PATH_TRANSLATED'};
		my @pt = split(/\\/, $pt);
		if(@pt>3){
			$pt[-3] = "member-only/";
			pop(@pt);
			pop(@pt);
		}else{
			$pt[-1] = "member-only/";
		}
		$member_only_path = join "/", @pt;
	}else{		#- in case
		$image_path = "/your/www/path/member-only/";
	}

	print "
	
	<p>
	<!------------------------ start static url ------------------>
	<table border=0 bordercolor=navy cellspacing=0 cellpadding=10 disabled$bg><tr><td>
	<form action=setup.cgi method=post>
	<input type=checkbox name=static value=yes checked> Enable Static Profiles Feature
	<table border=0>
	 <tr>
	  <td>Static Profile Base URL:</td>
	  <td><input type=text size=40 name=static_url value=\"$static_url\"></td>
	 </tr>
	 <tr>
	  <td>Base Path for URL above:</td>
	  <td><input type=text size=40 name=static_path value=\"$static_path\"></td>
	 </tr>
	 <tr>
	  <td></td>
	  <td><input type=checkbox size=40 name=create_static value=yes checked> Create New</td>
	 </tr>
	</table>	
	</td></tr>
	</table>
	<!------------------------ end static url ------------------>
	<p>
	<!------------------------ start email ------------------>
	<table border=0 bordercolor=navy cellspacing=0 cellpadding=10 disabled$bg><tr><td>
	Use email method:  $emailradio 
	 ($emailrecommend)
	<table border=0>
	 <tr>
	  <td>Sendmail Location:</td>
	  <td><input type=text size=40 name=sendmail value=\"$sendmail\"></td>
	 </tr>
	 <tr>
	  <td>SMTP Host Name:</td>
	  <td><input type=text size=40 name=smtp value=\"$smtp\"></td>
	 </tr>
	 <tr>
	  <td>From email address:</td>
	  <td><input type=text size=40 name=from value=\"$from\"></td>
	 </tr>
	</table>	
	</td></tr>
	</table>
	<!------------------------ end email ------------------>
	<p>
	<!------------------------ start upload image ------------------>
	<table border=0 bordercolor=navy cellspacing=0 cellpadding=10 disabled$bg><tr><td>
	<table border=0>
	 <tr>
	  <td>Images Directory URL:</td>
	  <td><input type=text size=40 name=image_url value=\"$image_url\"></td>
	 </tr>
	 <tr>
	  <td>Base Path for URL above:</td>
	  <td><input type=text size=40 name=image_path value=\"$image_path\"></td>
	 </tr>
	 <tr>
	  <td></td>
	  <td><input type=checkbox size=40 name=create_image value=yes checked> Create New</td>
	 </tr>
	</table>	
	</td></tr>
	</table>
	<!------------------------ end upload image ------------------>
	<p>
	<!------------------------ start member-only directory ------------------>
	<table border=0 bordercolor=navy cellspacing=0 cellpadding=10 disabled$bg><tr><td>
	<table border=0>
	 <tr>
	  <td>Member-only Directory URL:</td>
	  <td><input type=text size=40 name=member_only_url value=\"$member_only_url\"></td>
	 </tr>
	 <tr>
	  <td>Base Path for URL above:</td>
	  <td><input type=text size=40 name=member_only_path value=\"$member_only_path\"></td>
	 </tr>
	 <tr>
	  <td></td>
	  <td><input type=checkbox size=40 name=create_member_only value=yes checked> Create New and Set Htaccess</td>
	 </tr>
	</table>	
	</td></tr>
	</table>
	<!------------------------ end member-only directory ------------------>
	<p>

	<input type=hidden name=install_post value=server_settings>
	<input type=submit name=submit value=\"Submit Settings\">
	</form>

	<p><br><br>
	";
}

sub change_install_status{
		my($status) = @_;
		if( open(IL, ">${data_dir}/install.status") ){	
			print IL $status;
			close IL;
		}else{
			fatal_error("Cannot create a file under ${data_dir}
				<br>Please make sure data directory and everything inside is writable.");
		}
}

sub install_check_permissions
{
	$| = 1;	
	@writabledirs = ('data', 'data/backup', 'data/favorites', 'data/blog', 'data/mail');
	@executables = ('pm.cgi', 'admin.cgi', 'upload.cgi', 'search.cgi' , 'login.cgi');

	# check if they exist
	print "\n<p>\nChecking to see if any directory is missing...\n\n";
	$ok = 1;
	foreach(@writabledirs){
		my $d = "${root}$_";
		unless(-e $d){
			print "\n<li><i>$d</i> directory is missing...\n\n";
			mkdir($d, 0777);
			if(-e $d){
				print "\n <font color=green>created</font>\n";
			}else{
				$ok = 0;
				print "\n <font color=red>cannot created</font>\n";
			}
		}
	}
	check_ok($ok);

	print "\n<p>\nChecking to see if any important file is missing...\n\n";
	$ok = 1;
	foreach(@executables){
		my $e = "${root}$_";
		unless(-e $e){
			print "\n<li><font color=red><i>$e</i> file is missing...</font>\n\n";
			$ok = 0;
		}
	}
	check_ok($ok);

	# check permissions on each directory.
	print "\n<p>\nChecking permissions...\n\n";
	$ok = 1;
	foreach(@writabledirs){
		my $d = "${root}$_";
		unless(-w $d){
			print "\n<li><i>$d</i> directory is not writable...\n\n";
			chmod(0777, $d);
			if(-w $d){
				print "\n <font color=green>chmodded</font>\n";
			}else{
				$ok = 0;
				print "\n <font color=red>cannot chmod</font>\n";
			}
		}
	}
	check_ok($ok);

	print "
	<table border=0 disabled$bg>
	<tr><td>

	<form action=setup.cgi method=post>
	<input type=hidden name=action value=install>
	<input type=submit name=submit value=\"Check Again\">
	</form>	

	</td><td>

	<form action=setup.cgi method=post>
	<input type=hidden name=action value=install>
	<input type=hidden name=gopage value=2>
	<input type=submit name=submit value=\"Next Step\">
	</form>	
	</td></tr>
	</table>
	";

}

sub check_ok
{
	if($ok){
		print "\n <br><font color=green>OK!</font>\n";
	}else{
		print "\n <br><font color=red>There are problems above. They 
			should probably be fixed manually before going to the next step.</font>\n";
	}
}


sub install_admin_pass_form
{
	print "
		<blockquote>
		<p>
		<font size=2 face=arial>
		Please enter your administration password now:
		<form action=setup.cgi method=post>
		<table border=0 disabled$bg>
		<tr><td><font size=2 face=arial> Password: </td><td> <input type=password name=password1> </td></tr>
		<tr><td><font size=2 face=arial> Password again:</td><td> <input type=password name=password2> </td></tr>	
		</table>
		<input type=hidden name=install_post value=password>
		<input type=submit name=submit value=\"Create Password\">
		</form>
		<p>
		</blockquote>
	";

}

sub parse_config
{
	my ($file) = @_;
	@variable_order = ();
	%variable = ();
	%type = ();
	%box = ();
	$cur = "none";
	open(F, "<$config_dir/$file") or fatal_error("Cannot open file: $config_dir<b>$file</b>");
	while ($l = <F>){
		$xmloldcode .= $l;
		if($l =~ m/<\/variable>/i){
			chomp($variable{$cur});
			$cur = "none";
		}elsif($l =~ m/<variable name=\"(.*?)\" type=\"(.*?)\" box=\"(.*?)\">/i){
			$cur = $1;
			$variable_order[$o++] = $cur;
			$type{$cur} = $2;
			$box{$cur} = $3;
		}else{
			$variable{$cur} .= $l;
		}

	}
	close F;
}

sub parse_docs
{
	my ($file) = @_;
	%desc;
	%topic;
	%listtopics;
	%doc;
	$cur = "none";
	open(F, "<$config_dir/$file") or fatal_error("Cannot open file: $config_dir<b>$file</b>");
	while ($l = <F>){
		if($l =~ m/<\/description>/i){
			chomp($desc{$cur});
			$descflag = 0;
			$cur = "none";
		}elsif($l =~ m/<\/documentation>/i){
			chomp($doc{$cur});
			$docflag = 0;
			$cur = "none";
		}elsif($l =~ m/<description variable=\"(.*?)\" topic=\"(.*?)\">/i){
			$cur = $1;
			$topic{$cur} = $2;
			$listtopics{$2}++;
			$descflag = 1;
		}elsif($l =~ m/<documentation variable=\"(.*?)\">/i){
			$cur = $1;
			$docflag = 1;
		}else{
			if($descflag){
				$desc{$cur} .= $l;
			} elsif($docflag){
				$doc{$cur} .= $l;
			} 
		}

	}
	close F;

}

sub show_doc
{
	my ($v) = @_;
	if($v eq ""){
		print "Variable not defined!";
		return;
	}
	if($desc{$v} eq ""){
		$desc{$v} = "???";
	}
	if($doc{$v} eq ""){
		$doc{$v} = "No help topic avaliable!";

	}
	print "\n\n\n<br><table border=0 bgcolor=#004080 width=100%><tr><td><font color=white face=Verdana size=2><b><a name=$v>$desc{$v}</a></b></td></tr></table>";
	print "\n<table border=0 bgcolor=#f9e57f width=100%><tr><td><font color=black face=Verdana size=2>$doc{$v}</td></tr></table><br>";
}

sub show_all_docs
{
	print &get_all_docs;
}

sub get_all_docs
{
	my $docs = "";
	$docs .= "\n\n<p>";
	foreach(@variable_order){
		next if ($_ eq "");
		$docs .= "<li><a href=#$_>$desc{$_}</a>";
	}
	$docs .= "\n<p>";
	foreach(@variable_order){
		next if ($_ eq "");
		next if ($_ eq "");
		$docs .= "\n\n\n<br><table border=0 bgcolor=#004080 width=500><tr><td><font 
				color=white face=Verdana size=2><b><a name=$_>$desc{$_} (XML Label: $_)</a></b></td></tr></table>";
		$docs .= "\n<table border=0 bgcolor=#f9e57f width=500><tr><td><font color=black face=Verdana size=2>$doc{$_}
			<br><a href=setup.cgi?action=modify&variable=$_><b>Go -></b></a> <br>
			<font size=1><a href=admin.cgi?action=support&text=$_>Report an unclear description</a> </font>
			</td></tr></table><br>";
	}
	return $docs;
}

sub create_code
{
	$code = "";
	#- create code:
	foreach $v(@variable_order){
		next if($v eq "none");
		#next if($v eq "base_descriptions"); #- this may be enabled on the future versions, it is useless now 
		next if($v eq "");
		$code .= "\n#------------ $v\n";
		if($type{$v} eq "string"){
			if($variable{$v} =~ m/\@/){
				$code .= "\$$v = \'$variable{$v}\';";
			}else{
				#- precalculation
				if($v eq "idle_minutes"){
					$code .= "\$idle_seconds = ".($variable{$v}*60).";";
				} elsif($v eq "timezone"){
					$code .= "\$timezone = ".($variable{$v}*3600).";";
				} else {
					$code .= "\$$v = \"$variable{$v}\";";
				}
			}
		}elsif($type{$v} eq "array"){
			$code .= "\@$v = ($variable{$v});";
		}elsif($type{$v} eq "hash"){
			$code .= "\%$v = ($variable{$v});";
		}elsif($type{$v} eq "hash_hash"){
			$code .= "\%$v = ($variable{$v});";
		}elsif($type{$v} eq "hash_array"){
			$code .= "\%$v = ($variable{$v});";
		}elsif($type{$v} eq "free"){
			$code .= "$variable{$v}";
		}
		$code .= "\n";
	}
	$code =~ s/\r//g;
	$code .= "\n1;\n";
}

sub unnecessary 
{
	print "installing...\n<p>";
	unless( open(LC, ">$config_dir/latest.txt") ){
		print "Make sure your \"$config_dir\" directory exists and writable!";
		exit;
	}
	print LC 1;
	close (LC);

	unless( open(DF, "<$config_dir/default.xml") ){
		print "You are missing the \"$config_dir/default.xml\" file!";
		exit;
	}
	@defaultfile = <DF>;
	close (DF);


	unless( open(LC, ">$config_dir/1.xml") ){
		print "Make sure your \"$config_dir\" directory exists and writable!";
		exit;
	}

}

sub check_pmlib
{
        open (CFG, "<${root}lib/pm.lib") or fatal_error("Cannot find lib/pm.lib file! This file is necessary!\n");
        @cfg = <CFG>;
        close (CFG);
        $cfg = join("", @cfg);
        eval($cfg);
        unless($@ eq ""){
                fatal_error("Errors found on lib/pm.lib. 
			If the error message below does not make any sense 
			Your problem is probably with the way you uploaded the file.
			Make sure your FTP clients uploads this file(.lib files) in ASCII mode.<br><br>\n".$@);
        }
}


sub fatal_error{
	($message) = @_;
	print "
		<center>
		<table border=0 bgcolor=#ddfbff width=600>
		<tr><td><font fave=Verdana size=2 color=red><b>Terminating because of an error:</b><br></font></td></tr>
		<tr><td><font face=Verdana size=2>$message</font></td></tr>
		<tr><td><font fave=Verdana size=2><br><a href=\"javascript:history.go(-1)\">Go back</a></font></td></tr>
		</table>
		</center>
	";
	exit;
}

sub get_configfile_name
{
	if(-e "$config_dir/latest.xml"){
		$configfile = "latest.xml";
	}else{
		my $configxml = "default";
		opendir HERE,"$config_dir" or fatal_error "Cannot open a directory($config_dir) for new configuration:$!";
		foreach (map { m/(.*)\.xml/i } readdir HERE) {
			if($_ > $configxml ){
				$configxml = $_;
			}
			
		}
		closedir HERE;
		$configfile = "$configxml.xml";
	}
	#print "<font color=red>($configfile)</font>";
}

sub get_timestring
{
	return time();
}

sub modified_config
{
	$v = $input{'variable'};
	$variable{$v} = $input{'vvalue'};
	#print "<li>$v=$variable{$v}";
	for($i=0; $i<20; $i++){
		if($input{"variable$i"}){
			my $v = $input{"variable$i"};
			$variable{$v} = $input{"vvalue$i"};
			#print "<li>$v=$variable{$v}";
		}
	}

	#- writeback
	foreach(@variable_order){
		$v = $_;
		$xmlcode .= "<variable name=\"$v\" type=\"$type{$v}\" box=\"$box{$v}\">\n$variable{$v}\n</variable>\n\n";
	}	
	
	create_code();
	if(eval($code) eq ""){
		fatal_error("There was a syntax problem on the text you entered. Please go back, refresh the form, and make the changes again.<p>Debugging information if avaliable:<br><i>$@</i><p>");
	}
	
	open(LATEST, ">$config_dir/latest.xml") or 
			fatal_error("Cannot create $config_dir/latest.xml: $!<br>
			Make sure your $config_dir directory is writable.");
	print LATEST $xmlcode;
	close(LATEST);

	open(LATEST, ">$config_dir/firstlatest.xml")  or
			fatal_error("Cannot create $config_dir/firstlatest.xml: $!<br>
			Make sure your $config_dir directory is writable.");
	print LATEST $xmlcode;
	close(LATEST);


}

sub modified_message
{
	print "<p>Your new changes are accepted. These changes will not affect the existing configuration, 
		until you launch the changes.<p>"; 
	launch_button();
}


sub launch_button{
	my ($continue) = @_;
	if($continue eq ""){
		if($input{'myreferer'} eq ""){
			$continue = "index";
		}else{
			$continue = $input{'myreferer'};
		}
	}
	if(-e "$config_dir/latest.xml"){
		print "
			<table border=0 disabled$bg>
			<tr><td width=100>
				<form action=setup.cgi method=post>
				<input type=hidden name=action value=launch>
				<input type=hidden name=continue value=$continue>
				<input type=submit name=launch value=\"Launch!\">
				</form>
			</td><td>
				<form action=setup.cgi method=post>
				<input type=hidden name=action value=forget>
				<input type=hidden name=continue value=$continue>
				<input type=submit name=submit value=\"Undo All\">
				</form>
			</td><td>
				<form action=setup.cgi method=post>
				<input type=hidden name=action value=$continue>
				<input type=submit name=submit value=\"Continue\">
				</form>
			</td></tr>
			</table>
			<br>
		";
	}
}

sub launch {
	#-- eval it
	create_code();
	#print "<textarea cols=100 rows=40>$code</textarea>\n";
	if(eval($code) eq ""){
		fatal_error("There was a problem on the configuration. Cannot launch because of this problem: <br><i>$@</i>");
	}

	#-- create the pmpre.cfg
	open(CFG, ">$config_dir/pmpre.cfg") or fatal_error("Cannot open $config_dir/pmpre.cfg, because: $!\n");
	print CFG $code;
	close CFG;

	#-- put the latest xml into a new file
	$ts = get_timestring();	
	open(LATEST, ">$config_dir/$ts.xml")  or
                        fatal_error("Cannot create $config_dir/latest.xml: $!<br>
                        Make sure your $config_dir directory is writable.");
	print LATEST $xmloldcode;
	close(LATEST);

	#-- delete latest.xml
	unlink("$config_dir/latest.xml");

	print "
	 <head>
	  <meta HTTP-EQUIV=\"REFRESH\" CONTENT=\"1; URL=setup.cgi?action=$input{'continue'}\">
	 </head>" if ($page ne "4");

	print "
	 <p><center><font color=green>The new configuration is successfully launched!</font></center><p>
	 <br><br><br>
	";
	#Go back to <a href=setup.cgi>main menu</a>
}

sub modify_config_section
{
	my ($mytopic) = @_;
	print "
		<form action=setup.cgi method=post>
		<input type=hidden name=action value=modified>
		<table border=0 bordercolor=navy cellspacing=0 cellpadding=10 disabled$bg>
	";

	my $no = 1;
        foreach $v(@variable_order){
             if($topic{$v} eq $mytopic){
		modify_line($v, $no++, 1);
             }
        }

	print "</table>";
	print "<br>
		<input type=hidden name=myreferer value=$input{'action'}>
		<input type=submit name=submit value=Modify>\n</form>\n";
	print "<p>";
	
}

sub modify_line
{
	my ($v, $no,  $table) = @_;
	print "<tr><td width=30% valign=top>" if($table>0);
	print "<font size=2 fave=\"Arial,Verdana\">$desc{$v} </font>";
	print "</td><td>" if($table>0);
	print "\n<input type=hidden name=variable$no value=\"$v\">";
	if($box{$v} eq "yesno"){
		print "\n<select name=vvalue$no><option>yes</option>";
		if($variable{$v} eq "no"){
			print "<option selected>no</option>";
		}else{
			print "<option>no</option>";
		}
		print "</select>\n";
	} elsif($box{$v} =~ m/^\d+$/){
		$values{$v} =~ s/\"/\&quot\;/g;
		print "<input type=text size=$box{$v} name=vvalue$no value=\"$variable{$v}\">";
	} elsif($box{$v} =~ m/^(\d+)\-(\d+)$/){
		my $rows = $1;
		my $cols = $2;
		print "<textarea name=vvalue$no rows=$rows cols=$cols>$variable{$v}</textarea>";
	}else{
		print "<textarea name=vvalue$no rows=10 cols=60>$variable{$v}</textarea>";
	}
	print "</td><td width=10% valign=top align=right>" if($table>0);

	#- hack to prevent images broken:
	eval("require \"$config_dir/pmpre.cfg\""); $imageswww = "images/" if($imageswww eq "");

	print "<a href=\"javascript:getHelp('$v')\"><img src=${imageswww}question1.gif border=0></a>";
	print "</td></tr>\n\n";
}

sub modify_config
{
	$v = $input{'variable'};
	print "\n<form action=setup.cgi method=post>
		<input type=hidden name=action value=modified>
		<input type=hidden name=variable value=$v>
	";
	print "<table>";
	modify_line($v, 1, 1);
	print "</table>";
	print "<br><input type=submit name=submit value=Modify>\n</form>\n";
	print "<p>";
	show_doc($v);
	print "<p>";
}

sub header_config
{
	if($tempz{'adminheader'} eq ""){
		$tempz{'adminheader'} = "templates/admin/ta_header.htm";
	}
	if($tempz{'adminheader_pref'} eq ""){
		$tempz{'adminheader_pref'} = "templates/admin/ta_header_preferences.htm";
	}
	if($tempz{'adminheader_db'} eq ""){
		$tempz{'adminheader_db'} = "templates/admin/ta_header_database.htm";
	}
	if($tempz{'adminheader_temp'} eq ""){
		$tempz{'adminheader_temp'} = "templates/admin/ta_header_templates.htm";
	}
	if($tempz{'adminheader_payment'} eq ""){
		$tempz{'adminheader_payment'} = "templates/admin/ta_header_payment.htm";
	}
	eval("require \"$config_dir/pmpre.cfg\""); $imageswww = "images/" if($imageswww eq "");
	tempwiz("adminheader");
	if(
		$input{'action'} eq "newtemplate" || 
		$input{'action'} eq "addnewtemplate" || 
		$input{'action'} eq "template_rules"){
		tempwiz("adminheader_temp");
	}elsif ( $input{'action'} eq "dbwiz" ){
		tempwiz("adminheader_db");
	}elsif( $input{'action'} eq "paywiz" ){
		tempwiz("adminheader_payment");
	}elsif ( $input{'action'} eq "dbwiz" ){
		tempwiz("adminheader_db");
	}elsif ( $input{'action'} eq "launch" || $input{'action'} eq "launch_button"){
		if(
			$input{'continue'} eq "newtemplate" || 
			$input{'continue'} eq "addnewtemplate" || 
			$input{'continue'} eq "template_rules"){
			tempwiz("adminheader_temp");
		}elsif ( $input{'continue'} eq "dbwiz" ){
			tempwiz("adminheader_db");
		}elsif( $input{'continue'} eq "paywiz" ){
			tempwiz("adminheader_payment");
		}elsif ( $input{'continue'} eq "dbwiz" ){
			tempwiz("adminheader_db");
		}elsif ( $input{'continue'} eq "launch" ){
			tempwiz("adminheader_db");
		}else{
			tempwiz("adminheader_pref");
		}

	}else{
		tempwiz("adminheader_pref");
	}

	print  "
		<html>
		 <head><title>Setup Panel $input{'$action'}</title>

		<style type=\"text/css\">
		<!--
adminbody {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 13px;
color: #000080;
background: #B0C4DE;
border: 2px solid #4682B4;
padding: 5px;
width: 800px;
}
		 -->
		 </style>
		";
	$css_old = "
		 <style type=\"text/css\">
		 <!--
		      A:link {text-decoration: none; font-size:x-small; color:navy;}
		      A:visited {text-decoration: none; font-size:x-small; color:navy;}
		      body{
			color: transparent;
			font-family: Verdana;
			font-size: x-small;
			text-decoration: none
		      }
		      td { 
			font-size: 11pt;   
			font-family: verdana,arial,helveticai,sans-serif;       
			text-decoration : none
		      }
		      h3{
				font-family: verdana, arial, helvetica, sans-serif;
				font-size: 15px;
				color: #ffffff;
				font-weight: 700;
				background-color: #3399cc;
				border: 1px solid #000000;
				border-left-width: 10px;
				margin-left: 5%;
				padding: 5px;
				padding-left: 5px;
				margin-top: 5px;
				margin-bottom: 3px;
				-moz-box-sizing: border-box;
				box-sizing: border-box;
			}
		 -->
		 </style>
		";

		print "
		<script>
		function getHelp(topic){
			var baseLoc = \"\";
			var helpLoc = baseLoc + \"setup.cgi?action=help&topic=\" + topic;
			window.open(helpLoc,'viewHelp','width=300,height=240,left=100,top=150,status=no,toolbar=no,menubar=no,resizable=no,scrollbars=yes');
			}
		</script>
		 </head>
		 <body bgcolor=\"white\" disabled$bg link=\"#FF0000\" vlink=\"#FF0000\" alink=\"#FF0000\">
	";

}


sub footer_config
{
	my $old = "
		 <p>
		<font size=1 color=black face=\"Arial\">
		Configuration Quick Bar: 
		<a href=setup.cgi><font size=1 color=black face=Verdana>Main</font></a> | 
		<a href=setup.cgi?action=list_all><font size=1 color=black face=Verdana>Index</font></a> | 
		<a href=setup.cgi?action=template_rules><font size=1 color=black face=Verdana>Template Rules</font></a> | 
		<a href=setup.cgi?action=dbwiz><font size=1 color=black face=Verdana>Database Wizard</font></a> | 
		<a href=setup.cgi?action=list_all_docs><font size=1 color=black face=Verdana>Documentation</font></a>
		</font>
		 </center>
		 </body>
		 </html>
	";
	if($tempz{'adminfooter'} eq ""){
		$tempz{'adminfooter'} = "templates/admin/ta_footer.htm";
	}
	tempwiz("adminfooter");

}

sub list_all_variables
{
	foreach(@variable_order){
		push(@all, "$desc{$_}###<li><a href=setup.cgi?action=modify&variable=$_>$desc{$_} </a>");
	}
	@all = sort(@all);
	foreach(@all){
		my ($junk, $out) = split("###", $_);
		print $out;
	}
}

sub show_headline
{
	my($link, $text) = @_; 
	print "
		<center>
                <font color=\"#000080\" size=\"2\" face=\"Arial\"><b>
		$text
                </b></font>
		</center>
	";
}

sub old_show_headline
{
	my($link, $text) = @_; 

	#- hack to prevent images broken:
	eval("require \"$config_dir/pmpre.cfg\""); $imageswww = "images/" if($imageswww eq "");

	print "
	<table width=100% border=0 cellpadding=0 cellspacing=0><tr><td
		valign=TOP bgcolor=black old=#004080 old=#006675><img src=${imageswww}leftcorner.gif width=13 height=16 align=TOP><a 
		href=$link><font face=Verdana size=3 color=#FFFFFF><b>$text</b></font></a></td>
	</tr></table>
	";
}


sub template_rule_form
{
        my ($ruleid, $action, $field, $text, $temp) = @_;
	#print "<font color=green>($ruleid)($action, $field, $text, $temp)</font>";

	eval("\%actions =  ( $variable{'tempz'} )");
	eval("\@base = ($variable{'base'})");

        print "\n\n\n<br><table border=0><tr><td>$font\n";
        print "<form action=setup.cgi>";
	print "<input type=hidden name=action value=template_rules>\n";
	print "<input type=hidden name=ruleid value=$ruleid>\n";
        print "While on ";
        print "<select name=rule_action>\n";
	print "<option></option>\n";
        foreach(sort keys %actions){

                if($action eq $_){
                        print "<option selected>$_</option>\n";
                }else{
                        print "<option>$_</option>\n";
                }
        }
        print "</select>";
        print " page if ";
        print "<select name=rule_field>\n";
	print "<option></option>\n";
	print "<option>------ special -------</option>\n";
	if($field eq "subscription"){
		print "<option selected>subscription</option>\n";
	}else{
		print "<option>subscription</option>\n";
	}
	if($field eq "approved"){
		print "<option value=\"approved\" selected>approved (yes/no)</option>\n";
	}else{
		print "<option value=\"approved\">approved (yes/no)</option>\n";
	}
	print "<option></option>\n";
	print "<option>------ fields -------</option>\n";
        foreach(@base){
                if($field eq $_){
                        print "<option selected>$_</option>\n";
                }else{
                        print "<option>$_</option>\n";
                }
        }
        print "</select>";

        print " equals to ";
        print "<input type=text size=10 name=rule_text value=\"$text\">";

        print "<br>Then use ";
        print "<select name=rule_temp>\n";
	print "<option></option>\n";
        foreach(sort keys %actions){
                if($temp eq $_){
                        print "<option selected>$_</option>\n";
                }else{
                        print "<option>$_</option>\n";
                }
        }
        print "</select>";
        print " template.\n\n";
        print "</td><td>";
	if($action ne "" || $text ne ""){
		print "<input type=hidden name=do value=modify>\n";
		print "<input type=submit name=submit value=\" modify rule \">\n";
	}else{
		print "<input type=hidden name=do value=add>\n";
		print "<input type=submit name=submit value=\" add rule \">\n";
	}
        print "</form>\n";
	if($action ne "" || $text ne ""){
		print "<form action=setup.cgi>";
		print "<input type=hidden name=action value=template_rules>\n";
		print "<input type=hidden name=ruleid value=$ruleid>\n";
		print "<input type=hidden name=do value=delete>\n";
		print "<input type=submit name=submit value=\" delete rule \">\n";
		print "</form>\n";
	}
        print "</td></tr></table><br>\n";
}


1;
