#!/usr/bin/perl
##############################################
##                                          ##
##  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.       ##
##                                          ##
##############################################

 ###############################
 # find the root if this is IIS:
 ###############################
 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;
		$OS = "NT";
        }
 }



require "${root}lib/pm.lib"; 
require "${root}lib/admin.lib"; 
require "${root}lib/payment.lib"; 
require "${root}data/config/pmpre.cfg";
$strip_html = "no";
$iamadmin = 1;
$no_strip_pipe = 1;
&readit;

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

if($input{'pass'} eq ""){
    $input{'pass'} = $req->cookie("pmadm");
}

if($input{'action'} eq "admin_menu"){
           my $packed_cookie = $req->cookie(
                                        -NAME           => "pmadm",
                                        -VALUE          => $input{'pass'},
                                        -EXPIRES        => "+7d",
                                        -PATH           => "/"
            );
            print $req->header(-COOKIE => $packed_cookie);
            $header_set = 1;
}elsif($input{'action'} eq "logout"){
           my $packed_cookie = $req->cookie(
                                        -NAME           => "pmadm",
                                        -VALUE          => "byebye",
                                        -EXPIRES        => "-1h",
                                        -PATH           => "/"
            );
            print $req->header(-COOKIE => $packed_cookie);
            $header_set = 1;
	    $input{'action'} = "admin_logout";
	    &tempwiz;
	    exit;
}else{
	print "Content-type: text/html\n\n";
}

if(&admin_pass_check ne "yes")
{
	if($input{'pass'} ne ""){
		print "<center><font size=1 face=arial color=red>You can reset your password by deleting admin.pass file manually</font></center>";
	}	
	$input{'action'} = "admin"; 
	&tempwiz; 
	exit;
} else {
	$admin_checked=1; 
}

#tempwiz('adminheader');


if( $input{'action'} eq "users" )
	{ &users; }
elsif( $input{'action'} eq "message" )
	{ $input{'from'} = $admin; &tempwiz; }
elsif( $input{'action'} eq "messanger" )
	{ &messanger($database); }
elsif( $input{'action'} eq "deleted_user" )
	{ &remove_row; $input{'action'}="users"; &users; }
elsif( $input{'action'} eq "backup" )
	{ &backup_list; &tempwiz("backup"); &admin_end; }
elsif( $input{'action'} eq "backedup" )
	{ &backup; &backup_list; $input{'action'}="backup"; &tempwiz; &admin_end; }
elsif( $input{'action'} eq "retrieve" )
	{ &retrieve; &backup_list; $input{'action'}="backup"; &tempwiz; &admin_end; }
elsif( $input{'action'} eq "export" ){ 
	&export; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "exported" ){ 
	&exported; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "mass_add" ){ 
	$values{'list fields'} = join(", ", @base)."\n"; 
	$values{'list required fields'} = join("|", @not_null); 
	&tempwiz; &admin_end;  
}
elsif( $input{'action'} eq "mass_added" ){ 
	&mass_added; &tempwiz; &admin_end;  
}
elsif( $input{'action'} eq "support" ){ 
	&fetch_support; &tempwiz; &admin_end;  
}
elsif( $input{'action'} eq "forum" ){ 
	&fetch_forum; &tempwiz; &admin_end;  
}
elsif( $input{'action'} eq "latest_versions" ){ 
	&fetch_latest_versions; &tempwiz; &admin_end;  
}
elsif( $input{'action'} eq "change_pass" )
	{ &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "changed_pass" )
	{ 
		&admin_pass_change; 
		$input{'action'}="admin_menu"; 
		$input{'pass'} = pm_encode($input{'pass1'}); 
		$values{'pass'} = $input{'pass'}; 
		&tempwiz; &admin_end;  }
elsif( $input{'action'} eq "approval")
	{ &approval; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "massedit")
	{ &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "massedited")
	{ &massedited; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "edittemp")
	{ &edittemp; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "stats" )
	{ &show_stats; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "tracking" )
	{ &show_tracking; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "env" )
	{ &show_env; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "search_stats" )
	{ &show_search_stats; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "paymentlog" )
	{ &show_paymentlog; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "paymentexpiring" )
	{ &show_paymentexpiring; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "subscriptions" )
	{ &show_subscriptions; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "subscription_manage" )
	{ &subscription_manage; &tempwiz; &admin_end;  }
elsif( $input{'action'} eq "subscription_add" )
	{ &subscription_add; &tempwiz("subscription_manage"); &admin_end;  }
elsif( $input{'action'} eq "subscription_modify" )
	{ &subscription_modify; &tempwiz("subscription_manage"); &admin_end;  }
elsif( $input{'action'} eq "subscription_delete" )
	{ &subscription_delete; &tempwiz("subscription_manage"); &admin_end;  }
elsif( $input{'action'} eq "paymentreports" )
	{ &paymentreports; &tempwiz; &admin_end;  }
else
	{ $input{'action'} = "admin_menu"; &tempwiz; &admin_end; }
	

&admin_end; 

sub errdie{
	($em) = @_;
	print "Terminating Error: $em";
	exit;
}


sub admin_end{
   #tempwiz('adminfooter');
   exit;
}

sub fetch_support
{
	my $text = "";
	my $name = "";
	if($input{'text'} ne ""){
		$text = "Just Reporting: Documentation+of+$input{'text'}+variable+is+not+clear.";
	}
	if($ENV{'HTTP_HOST'} ne "" && $ENV{'HTTP_HOST'} ne "localhost"){
		$name = "$ENV{'HTTP_HOST'}";
	}
	#- fetch support form from interlogy site:
	eval("use LWP::Simple");
	eval("\$input{'out'} = get(\"http://www.interlogy.com/about/pmpre_support.html?text=$text&email=$from&name=$name\") ");
}

sub fetch_forum
{
	#- fetch support forum list from interlogy site:
	eval("use LWP::Simple");
	eval("\$input{'out'} = get(\"http://www.interlogy.com/support/pmpre/board/latest_bare.php\")");
}

sub fetch_latest_versions
{
	#- fetch support forum list from interlogy site:
	eval("use LWP::Simple");
	eval("\$input{'out'} = get(\"http://www.interlogy.com/products/pmpre/latest_bare.html\")");
}

sub exported
{
	my $allrows = 1;
	my @fields = ();
	my @checks = ();

	#- find out what the form says
	foreach (keys %input){
		my $v = $input{$_};
		if(m/only(\d)_field/){
			if($v ne ""){
				my $t = "only$1_text";
				$checks{$v} = $input{$t};
				$allrows = 0;
			}
		}elsif(m/field_(.*)/){
			push(@fields, $1);
		}
	}

	#- fix the order
	my @temp = ();
	foreach my $b( @base ){
		foreach my $f( @fields ){
			if($b eq $f){
				push(@temp, $b);
			}
		}	
	}
	@fields = @temp;

	#- think about the first line
	my $out = "";
	if($input{'firstline_names'} eq "yes"){
		$out .= join($input{'delimiter'}, @fields);
		$out .= "\n";
	}

	#- create the export list
	open (DATABASE, "<${root}$database");
	while(my $line = <DATABASE>)
	{
		my $ok = 1;
		my $i = 0;
		my @results = ();
		init($line);
		my $d = $input{'delimiter'};
		foreach(keys %values){
			$values{$_} =~ s/\Q$d\E/ /g;
		}
		if($allrows){
			foreach(@fields){
				$results[$i++] = $values{$_};
			}	
		}else{
			foreach my $c(keys %checks){
				if($values{$c} ne $checks{$c}){
					$ok = 0;
				} 
			}
			if($ok){
				foreach(@fields){
					$results[$i++] = $values{$_};
				}	
			}
		}
		if( $ok ){
			my $newline = join($input{'delimiter'}, @results);
			if($input{'remove_duplicates'} eq "yes"){
				foreach( split("\n", $out) ){
					$ok = 0 if($_ eq $newline);
				}
			}
			if( $ok ){
				$out .= "$newline\n";
			}
		}
	}
	close DATABASE;

	if($out eq ""){
		$input{'export_list'} = "Sorry, no results found!";
	}else{
		$input{'export_list'} = $out; 		
	}

}

sub export
{
	my $size = int((@base)/2);
	my $i = 0;
	$input{'base_checkbox'} = "\n\n<table border=0><tr><td>";
	$input{'base_dropdown'} = "<option> </option>";
	foreach(@base){
		$input{'base_dropdown'} .= "<option>$_</option>";
		$input{'base_checkbox'} .= "\n</td><td>\n" if($size == $i++);
		$input{'base_checkbox'} .= "<input type=checkbox name=\"field_$_\" value=yes>
				<font size=2 face=Arial>$_</font><br>";
	}
	$input{'base_checkbox'} .= "\n\n</td></tr></table>";


}

sub mass_added{

	#- check for the unwanted windows character:
	$input{'data'} =~ s/\r/\n/g;
	$input{'data'} =~ s/\n\n/\n/g;

	my($fields, @rows) = split("\n", $input{'data'});
	$input{'data'} = ""; #- free the memory
	$d = $input{'delimeter'}; 
	$d = "|" if($d eq "");
	$d =~ s/(\W)/\\$1/g;
	my(@fields) = split(/$d/, $fields);

	#print "<font color=navy>$fields</font><br>";
	#print "<font color=red>@rows</font>";

	#- check the first line
	#- it should include required fields 
	my $fc = 0;
	foreach $f(@fields){
		if($f eq "login"){
			$login_field = $fc;
		} elsif($f eq "ID"){
			$ID_field = $fc;
		} elsif($f eq "email"){
			$email_field = $fc;
		} elsif($f eq "register_date"){
			$register_date_field = $fc;
		} elsif($f eq "update_date"){
			$update_date_field = $fc;
		} elsif($f eq "sortable_register_date"){
			$sortable_register_date_field = $fc;
		} elsif($f eq "sortable_update_date"){
			$sortable_update_date_field = $fc;
		}
		foreach $nn(@not_null){
			if($nn eq $f){
				$foundnn{$nn} = $fc;
			}
		}
		$fc++;	
	}
	if($ID_field<1){ $fields[$fc] = "ID"; $ID_field = $fc++; }
	if($email_field<1){ $fields[$fc] = "email"; $email_field = $fc++; }
	if($register_date_field<1){ $fields[$fc] = "register_date"; $register_date_field = $fc++; }
	if($update_date_field<1){ $fields[$fc] = "update_date"; $update_date_field = $fc++; }
	if($sortable_register_date_field<1){ $fields[$fc] = "sortable_register_date"; $sortable_register_date_field = $fc++; }
	if($sortable_update_date_field<1){ $fields[$fc] = "sortable_update_date"; $sortable_update_date_field = $fc++; }

	foreach(@not_null){
		if($foundnn{$_} eq ""){
			$problem_fatal .= "<br>$_ is a required field and it is missing"
				unless($_ eq "ID" || $_ eq "password"); 
		}
	}
	
	#- check the login field format
	&get_existing_logins;
	foreach(@rows){
		#- todo: changed brakes back to normal
		#my(@ea) = split(/\|/, $_);
		my(@ea) = split(/$d/, $_);
		my $login = $ea[$login_field];
		if ($login =~ /[^A-Za-z0-9]/) {
			$rejected{$login} = "Login field should only include alphanumeric chracters!";
			next;
		}

		#- check the login if already exists
		if($existing_logins{$login} == 1){
			$rejected{$login} = "Login already exists in the database!";
			next;
		}elsif($existing_logins{$login} == 2){
			$rejected{$login} = "Duplicate entry!";
			next;
		}else{
			$existing_logins{$login} = 2;
		}
		
		#- check required fields
		my $r = 0;
		foreach(keys %foundnn){
			my $fc = $foundnn{$_};
			if($ea[$fc] eq "" || $ea[$fc] eq " "){
				$rejected{$login} .= "Required field $_ is missing! ";
				$r = 1;
			}
		}
		if($r){
			next;
		}

		#- check the email field format
                if( $check_email eq "yes")
                {
                        if($email_field ne ""){
                                if(!($ea[$email_field] =~ m/^([\w\-\.\!\%\+]+\@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*\.[a-zA-Z0-9\-]+)$/)){
                                        $rejected{$login} = "Email format is not correct! ($ea[$email_field])";
                                        next;
                                }
                        }
                }

		#- create the dates and IDs
		&time_n_ID;
		if($ea[$register_date_field] eq ""){
			$ea[$register_date_field] = $today;
		}
		if($ea[$update_date_field] eq ""){
			$ea[$update_date_field] = $today;
		}
		if($ea[$sortable_register_date_field] eq ""){
			$ea[$sortable_register_date_field] = $sortabledate;
		}
		if($ea[$sortable_update_date_field] eq ""){
			$ea[$sortable_update_date_field] = $sortabledate;
		}
		if($ea[$ID_field] < 10){
			$ea[$ID_field]=$ID;
		}

		#for($i=0; $i<@ea; $i++){
		#	print "($i=$fields[$i]=$ea[$i])"; 
		#}	
		my %fea;
		for($i=0; $i<@fields; $i++){
			$fea{$fields[$i]} = $ea[$i];
		}
		my @bfea;
		foreach(@base){
			if($fea{$_} eq ""){
				$fea{$_} = " ";
			} 
			push(@bfea, $fea{$_});	
		}	
		$accepted .= join("|", @bfea)."\n";

	}

	#- put accested lines and other warnings into variables
	$input{'rejected'} = "    ";
	foreach(keys %rejected){
		$input{'rejected'} = "<li>Rejected <b>$_</b>: $rejected{$_}";
	}

	#- if complete, give a success page
	if($input{'submit'} eq "Complete" && $problem_fatal eq ""){
		$input{'out'} = "The new users have been successfully added to the database!"; 	
		open (DATABASE, ">>${root}$database");
		print DATABASE ${accepted};
		close(DATABASE);

		return;
	}

	#- add to accepted lines
	$input{'out'} = "
		<form action=admin.cgi method=post>
		<input type=hidden name=action value=mass_added>
		<input type=hidden name=pass value=$input{'pass'}>
		<p><textarea name=data cols=100 rows=20 wrap=off>".join("|", @base)."\n"."${accepted}</textarea><br>
		<input type=submit name=submit value=Preview>
	";
	if($problem_fatal eq ""){
		$input{'out'} .= "\n <input type=submit name=submit value=Complete>";		
	}else{
		$input{'out'} .= "\n <font color=red><b>Fatal problem!</b>$problem_fatal</font>";
	}

}

sub get_existing_logins{
 open (DATABASE, "<${root}$database");
 while(<DATABASE>)
 {
	 if (m/^(.*?)\|/){
		$existing_logins{$1} = 1;
	 }
 }
 close DATABASE;
}

sub show_env{

	my $type = "Apache";
	if($ENV{'SERVER_SOFTWARE'} =~ m/IIS/){
		$type = "Windows IIS";
	}
	$values{'env'} = "\n\n<center><font size=2 face=\"Verdana,Arial\" color=navy><b>Server Environment Variables:
				</b></font></center><p>\n";
	$values{'env'} .= "\n\n<table>\n";
	$values{'env'} .= "\n\n<tr><td>Server Type:</td><td>$type</td></tr>\n";
	$values{'env'} .= "\n\n<tr><td>Sendmail Locations:</td><td>\n";
	$values{'env'} .= `whereis sendmail`;
	$values{'env'} .= "\n\n</td></tr><tr><td>Default Sendmail Location:</td><td>\n";
	$values{'env'} .= `which sendmail`;
	$values{'env'} .= "\n\n</td></tr>";
	$values{'env'} .= "\n\n<tr><td>Image::Magick Installed?</td><td>\n";
	eval("use Image::Magick");
	if ($@) { 
		$values{'env'} .= "no";
	} else {
		$values{'env'} .= "yes";
	}
	$values{'env'} .= "\n\n</td></tr>";
	$values{'env'} .= "\n\n<tr><td><br>Environment Variables:</td><td>\n";
	$values{'env'} .= "\n\n</td></tr>";
	foreach (keys %ENV){
		$values{'env'} .= "\n<tr>\n";
		my $envline = $ENV{$_};
		$envline =~ s/\,/\, /g;
		
	       $values{'env'} .= "<td>$_:</td> <td width=300>$envline</td>\n";
		$values{'env'} .= "\n</tr>\n";
	}

	$values{'env'} .= "\n\n</table>\n";


}

sub approval{
	
        if($input{'waiting'} ne ""){
                #-                          
                open(H, "<${root}$content_pass_file") or errdie "Cannot open htpassword file: $!\n";
                @lines = <H>;               
                close H;                    

                my $encrypted = crypt($input{$input{'waiting'}}, $encrypt_addon);
                push(@lines, "$input{'waiting'}:$encrypted\n");

                open(H, ">${root}$content_pass_file") or errdie "Cannot open htpassword file: : $!";
                print H @lines;
                close H;

			#- approved email
			if($input{'send_email'} eq "yes" && $send_confirmation eq "yes"){
				 open (DATABASE, "<${root}$database");
	 			 while ($thisrow = <DATABASE>){
  					if ($thisrow =~ m/^$input{'waiting'}\|(.*)/){
   						&init($thisrow);
					}
				 }
	 			 close DATABASE;
				 print "<center><font color=green size=1 face=arial>sending email to $values{'email'}...</font></center>";
				 &confirm_approval;
			}
			elsif($input{'send_email'} eq "yes" && $send_confirmation ne "yes"){
				print "not sending email, because send_confirmation is disabled 
						in pmpre configuration";
			}

        }

        if($input{'approved'} ne ""){
                #-
                open(H, "<${root}$content_pass_file") or errdie "Cannot open htpassword file: $!\n";
                @lines = <H>;
                close H;

                foreach(@lines){
                        if(!(m/^$input{'approved'}:/i)){
                                push(@newlines, $_);
                        }
                }  

                open(H, ">${root}$content_pass_file") or errdie "Cannot open htpassword file: $!\n";
                print H @newlines;
                close H;

        }
        

        
        #- open .htpassword and get all logins
        open(H, "<${root}$content_pass_file") or errdie "Cannot open htpassword file: $!";
        while(my $l = <H>){
                my ($lo) = split(/\:/, $l);
                $hlogins .= "|${lo}|";
        } 
        close(H);
        
        #- open database and get all logins
        open(D, "<${root}$database") or errdie "Cannot open database: $!";
        my @dlines = <D>;
        close(D);

        #- find the ones that don't exist in the htpass
        foreach(@dlines){
		    if($htaccess_use_id eq "no"){
    	                ($lgn, $dump, $didtemp) = split(/\|/, $_);
		    } else {
	                ($lgn, $didtemp) = split(/\|/, $_);
		    }
		    #$lgn = lc($lgn);
                $did{$lgn} = $didtemp;
                if($hlogins =~ m/\|${lgn}\|/){
                        push(@approved, $lgn);
                }else{
                        push(@waiting, $lgn);
                }
        }

	#- sort them
        @approved = sort @approved;
        @waiting = sort @waiting;

        #- list them
        $values{'awaiting'} .= "\n<form action=admin.cgi method=post>";
        $values{'awaiting'} .= "\n<input type=hidden name=pass value=\"$input{'pass'}\">";
        $values{'awaiting'} .= "\n<input type=hidden name=action value=approval>";
        $values{'awaiting'} .= "\n<table border=0><tr>";
        $values{'awaiting'} .= "<td cellpadding=10 cellspacing=10>";
        $values{'awaiting'} .= "<select size=20 name=waiting >";
        $values{'awaiting'} .= "\n<option value=>------- Waiting --------";
        foreach(@waiting){
                $values{'awaiting'} .= "\n<option value=\"$_\">$_";
        }
        $values{'awaiting'} .= "</select>";
        $values{'awaiting'} .= "</td><td cellpadding=10 cellspacing=10>";
        $values{'awaiting'} .= "<input type=submit name=do value=\"approve >>\"><br><br>";
        $values{'awaiting'} .= "<input type=submit name=do value=\"<< disapprove\">";
        $values{'awaiting'} .= "</td><td cellpadding=10 cellspacing=10>";
        $values{'awaiting'} .= "<select size=20 name=approved >";
        $values{'awaiting'} .= "\n<option value=>------- Approved --------";
        foreach(@approved){
                $values{'awaiting'} .= "\n<option value=\"$_\">$_";
        }
        $values{'awaiting'} .= "</select></td>";
        $values{'awaiting'} .= "</table>";
        foreach(@waiting){
                $values{'awaiting'} .= "\n<input type=hidden name=\"$_\" value=$did{$_}>";
        }
	  $values{'awaiting'} .= "\n<input type=checkbox checked name=send_email value=yes> Send email to approved members<br>";
        $values{'awaiting'} .= "\n</form>";

}

{
        my $cf = $input{'changefrom'};
        my $ct = $input{'changeto'};
        my $no_of_tempz = keys %tempz;
        my $tout = "$no_of_tempz files are scanned...";
        foreach my $tn(keys %tempz){
                my $tf = $tempz{$tn};
                if( open(TEMPR, "<${root}$tf") ) {
                        my @arrtempfile = <TEMPR>;
                        #my $tempfile = join("", @arrtempfile);
                        close TEMPR;
                        my @newarrtempfile = ();
                        foreach my $line(@arrtempfile){
                                if($line =~ m/\Q${cf}/){
                                        $modifiedfiles{$tn} = $tf;
                                        $line =~ s/\Q${cf}/${ct}/g;
                                }
                                push(@newarrtempfile, $line);
                        }
                        open(TEMPW, ">${root}$tf") or print "Cannot open ${root}$tf for writing: $!\n<br>";
                        print TEMPW @newarrtempfile;
                        close TEMPW;
                        #open(TEMPW, ">/tmp/temp/$tn") or print $!;
                        #print TEMPW @newarrtempfile;
                        #close TEMPW;
                        #print "\ndiff /tmp/temp/$tn $tf";
                        #print `diff /tmp/temp/$tn $tf`;
                        #print "\n";
                } else { print "Cannot open ${root}$tf for reading: $!\n<br>"; }
        }

        $no_of_modifiedfiles = keys %modifiedfiles;
        if( $no_of_modifiedfiles < 1){
                $tout .= "<br>String not found on any of the files.";
        }else{
                $tout .= "<br>String has been replaced on $no_of_modifiedfiles files:<ul>";
                foreach(keys %modifiedfiles){
                        $tout .= "\n<li>$_ ($modifiedfiles{$_})";
                }
                $tout .= "</ul>\n\n";
        }
        $input{'output'} = $tout;
}

sub edittemp
{
	my $tout;
	if($input{'file'} ne ""){
		$tp = $tempz{$input{'file'}};
		if($tp ne "" && $input{'text'} ne "")
		{
			open(T, ">${root}$tp") or print "${root}$tp: $! (did you set the template files as writable?)<p>\n";
			print T $input{'text'};
			close T;
			$tout .= "<p>";
		}
	}

	$tout .= "\n\n\n<table border=0 cellpadding=0 cellspacing=0>
		<form method=get action=admin.cgi>
		<tr>
			<td colspan=2>";

	# create a drop down list from tempz array
	#- get addon folder list
	#- get profile folder list
	#- get member folder list
	#- get search folder list
	foreach(keys %tempz){
		my $t = $tempz{$_};
		if($t =~ m/templates\/addon/){
			push(@t_addon, $_);
		}elsif($t =~ m/templates\/common/){
			push(@t_common, $_);
		}elsif($t =~ m/templates\/member/){
			push(@t_member, $_);
		}elsif($t =~ m/templates\/profile/){
			push(@t_profile, $_);
		}elsif($t =~ m/templates\/search/){
			push(@t_search, $_);
		}elsif($t =~ m/templates\/admin/){
			push(@t_admin, $_);
		}elsif($t =~ m/templates\/blog/){
			push(@t_blog, $_);
		}else{
			push(@t_other, $_);
		}
	}

	$tout .= "<input type=hidden name=pass value=$input{'pass'}>";
	$tout .= "<input type=hidden name=action value=edittemp>";

	$tout .= "<select name=nexttemp>";

	$tout .= "<option>---select a template---\n";

	$tout .= "<option>\n";

	$tout .= "<option>---common---------------\n";
	foreach(sort @t_common){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---profile--------------\n";
	foreach(sort @t_profile){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---addon---------------\n";
	foreach(sort @t_addon){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---member--------------\n";
	foreach(sort @t_member){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---search--------------\n";
	foreach(sort @t_search){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---blog--------------\n";
	foreach(sort @t_blog){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---other--------------\n";
	foreach(sort @t_other){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "<option>\n";

	$tout .= "<option>---admin--------------\n";
	foreach(sort @t_admin){
		if($input{'nexttemp'} eq $_){
			$tout .= "<option selected>$_\n"; 
		}else{
			$tout .= "<option>$_\n";
		}
	}

	$tout .= "</select>\n\n";

	$tout .= "<input type=submit name=submit value=load>";

	$tout .= "
		</td></tr>
		</form>
		<tr><td colspan=2>";

	# create a form for each edit=profile type


	if($input{'nexttemp'} ne ""){
		$tp = $tempz{$input{'nexttemp'}};
		if($tp ne "")
		{
			open(T, "<${root}$tp") or die "${root}$tp: $!";
			@l = <T>;
			close T;
			$template = join("", @l);
			$template =~ s/\<\/textarea\>/\&lt;\/textarea\>/ig; 
			$template =~ s/\r\n/\n/g;
			$template =~ s/\&nbsp/\&amp\;nbsp/g;
			$tout .= "<form method=post action=admin.cgi name=name>";
			$tout .= "<input type=hidden name=pass value=$input{'pass'}>";
			$tout .= "<input type=hidden name=action value=edittemp>";
			$tout .= "<input type=hidden name=nexttemp value=\"$input{'nexttemp'}\">";
			$tout .= "<input type=hidden name=file value=\"$input{'nexttemp'}\">";
			$tout .= "<textarea name=text cols=120 rows=30>$template</textarea>";
			$tout .= "</td></tr><tr><td align=left>";
			$tout .= "<input name=\"string\" type=\"text\" size=\"5\" onChange=\"n=0;\">";
			$tout .= "<input type=\"button\" value=\"find\" onClick=\"javascript:findInPage(document.name.string.value)\">";
			$tout .= "</td><td align=right>";
			$tout .= "<input type=submit name=submit value=\"  modify  \">";
			$tout .= "</td></tr></table>";
			$tout .= "</form>";
		}
	}

	$input{'action'} = "tempedit";
	$values{'output'} = $tout;
}

sub massedited
{
        my $cf = $input{'changefrom'};
        my $ct = $input{'changeto'};
        my $no_of_tempz = keys %tempz;
        my $tout = "$no_of_tempz files are scanned...";
        foreach my $tn(keys %tempz){
                my $tf = $tempz{$tn};
                if( open(TEMPR, "<${root}$tf") ) {
                        my @arrtempfile = <TEMPR>;
                        #my $tempfile = join("", @arrtempfile);
                        close TEMPR;
                        my @newarrtempfile = ();
                        foreach my $line(@arrtempfile){
                                if($line =~ m/\Q${cf}/){
                                        $modifiedfiles{$tn} = $tf;
                                        $line =~ s/\Q${cf}/${ct}/g;
                                }
                                push(@newarrtempfile, $line);
                        }
                        open(TEMPW, ">${root}$tf") or print "Cannot open ${root}$tf for writing: $!\n<br>";
                        print TEMPW @newarrtempfile;
                        close TEMPW;
                        #open(TEMPW, ">/tmp/temp/$tn") or print $!;
                        #print TEMPW @newarrtempfile;
                        #close TEMPW;
                        #print "\ndiff /tmp/temp/$tn $tf";
                        #print `diff /tmp/temp/$tn $tf`;
                        #print "\n";
                } else { print "Cannot open ${root}$tf for reading: $!\n<br>"; }
        }

        $no_of_modifiedfiles = keys %modifiedfiles;
        if( $no_of_modifiedfiles < 1){
                $tout .= "<br>String not found on any of the files.\n";
        }else{
                $tout .= "<br>String has been replaced on $no_of_modifiedfiles files:<ul>";
                foreach(keys %modifiedfiles){
                        $tout .= "\n<li>$_ ($modifiedfiles{$_})";
                }
                $tout .= "</ul>\n\n";
        }
        $input{'output'} = $tout;
}


sub backup
{
 &get_time;
 my @rowz;
 open (DATABASE, "<${root}$database");
 while (($line = <DATABASE>))
 {	push (@rowz, $line); }
 close DATABASE;

 open (DATABASE, ">${root}$backup_folder/$timeno.dat");
 print DATABASE @rowz;
 close DATABASE;
}

sub retrieve
{
 my @rowz;
 if($input{'file'} eq ""){ &err("no file is selected for backup");exit;}
 open (DATABASE, "<${root}$backup_folder/$input{'file'}");
 while (($line = <DATABASE>))
 {	push (@rowz, $line); }
 close DATABASE;

 open (DATABASE, ">${root}$database");
 foreach $rowz(@rowz) {print DATABASE $rowz};
 close DATABASE;
}
sub backup_list
{
        opendir(FOLDER, "${root}$backup_folder");
        @files = readdir(FOLDER);
        closedir FOLDER;

        $values{'backup list'} .= "<select name=file size=5>\n";
        foreach $file(reverse(@files))
        {
         if ($file =~ m/\.dat/)
         {$values{'backup list'} .=   "<OPTION VALUE=\"$file\"> $file\n";}
        }
        $values{'backup list'} .= "</select>\n";
}

sub users
{
      $admin_link = 1;
      if($input{'sortby'} eq ""){
	      $list_alphabetic = "no";
      }
      $input{'sortby'} = "sortable_register_date";
      $input{'reverse'} = "yes";
      $tempz{'list_table'} = 	$tempz{'admin_list_table'};
      $tempz{'list_table_next'} = 	$tempz{'admin_list_table'};
	if($input{'catvalue'} eq ""){
		$input{'catvalue'} = "all";
	}
	&list;
	$values{'pass'} = $input{'pass'};
	&tempwiz;
}


exit;




sub env
{
 print "<table><tr><td>";
 print join("\n<br>", keys %ENV); 
 print "</td><td>";
 print join("\n<br>", values %ENV); 
 print "</td></tr></table>";
}

&check_secure;

if ($input{'action'} eq "menu")
	{&menu;}
elsif ($input{'action'} eq "list")
	{&admin_list;}
elsif ($input{'action'} eq "message_central")
	{&message_central;}
elsif ($input{'action'} eq "statistics")
	{&statistics;}
 else {&admin_login;}

sub menu 
{
		print qq~
	
		<body bgcolor=#008080 text=#FFFFFF link=#FFFFFF vlink=#FFFFFF>
		<p align=center><font face=arial><strong>Membership
		Administration</strong></font></p>
		
		    <li><p align=left><a href=admin.cgi?action=list&check=$input{'check'}><font face=arial><strong>List</a>: </strong></font><font
		        size=2 face=arial>Gives the listing of all members </font></p>
		    </li>
		    <li><p align=left><a href=admin.cgi?action=message_central&check=$input{'check'}><font face=arial><strong>Message
		        Central:</strong></font></a></p>
		    </li>
		    <li><p align=left><a href=board.cgi?action=admin><font face=arial><strong> Board Admin:</strong></font></a></p>
		    </li>
		    <li><p align=left><a href=admin.cgi?action=statistics&check=$input{'check'}><font face=arial><strong>Statistics: </strong></font></a></p>
		    </li>
		    <li><font face=arial><strong>Archive: </strong></font><br><b>archive
		        no:</b> this is the text used in the archive file name. You
		        can use it as week number. <b>Caution:</b> if you give a number,
		        which is already exist, it will overwrite it! <br>
		         <form
		        action=http://www.interlogy.com/cgi-bin/globalthink/archive.pl
		        method=get>
		            <p>arhchive no:<input type=text size=25
		            name=name><br>
		            link text:<input type=text size=25 name=text><br>
		            <select name=branch size=1>
		                <option value=bussiness> bussiness</option>
		                <option value=arts> arts</option>
		                <option value=health> health</option>
		                <option value=lifestyle> lifestyle</option>
		                <option value=spiritual> spiritual</option>
		                <option value=technology> technology</option>
		            </select><input type=submit name=submit
		            value=Submit></p>
		        </form>
		    </li>
		    <li><p align=left><font face=arial><strong>Delete:</strong></font>
			<font
		        size=2 face=arial>This will remove the account permanently!</font></p>
		    </li>
		<form action=delete.cgi method=get>
			<font size=2 face=Verdana>Login Name: </font>
			<input type=text color=grey name=0 size=25>
			<input type=hidden name=1 value=admin_says_so>
		<input type=submit name=submit value=Delete></p>
		    <li><p align=left><font face=arial><strong>Membership Approval: </strong></font><font
		        size=2 face=arial>These entries are waiting for your
		        approval.</font></li>
        $ourapprovel_html
	        <p>

		</ul>
		<p>&nbsp;</p>
		</body>
		</html>
	
	~;


}

sub statistics{
	print "<h4> STATISTICS </H4> <p><br>";
	open(STATISTICS, "<${root}$statistics_file");
	while (( $stats = <STATISTICS>))
	{
		print "$stats\n";
	}
	close STATISTICS;
	exit;
}


sub message_central{
	open (FILE, "<${root}$message_central_file") or die " can not open $approve_file!";
	while (($ourfile = <FILE>))
	{
		print "$ourfile\n";
	}
	close FILE;
	exit;
}	

	
sub last_visitors
{
  
  @statz = reverse(@statz);

  #last 20
  $recent = $input{'number'};
  $stats_html = "<TABLE border=0 cellspacing=0 cellpadding=3 width=700 align=center>";
  $stats_html .= "\n<tr>";
  $stats_html .= "\n\t<td bgcolor=navy nowrap> <FONT color=white face=arial size=2> <B>  Time </TD>";
  $stats_html .= "\n\t<td bgcolor=navy align=right nowrap> <FONT color=white face=arial size=2><B>  Login   </TD>";
  $stats_html .="\n\t<td bgcolor=navy align=right nowrap> <FONT color=white face=arial size=2> <B>   IP </TD>";
  $stats_html .= "\n\t<td bgcolor=navy align=right nowrap> <FONT color=white face=arial size=2><B>  Browser   </TD>";
  $stats_html .= "\n\t<td bgcolor=navy align=right nowrap> <FONT color=white face=arial size=2><B>  O/S   </TD>";
  $stats_html .= "\n</tr>";

 if($input{'next'}<1){
	$input{'next'} = 0;
 }

 for($i = $input{'next'}; $i<$input{'next'}+$recent && $i<$values{'total logins'}; $i++)
 {
 	@fieldz = split(/\|/, $statz[$i]);
	$stats_html .= "\n<tr>\n";
	$stats_html .= "<td bgcolor=white nowrap> <FONT color=cc0000 face=arial size=2> <B>  $fieldz[3] </TD>";
	#print "<td>$fieldz[1]</td>";
	$stats_html .= "\n\t<td bgcolor=ffffdd align=right nowrap> <FONT color=000000 face=arial size=2><B>";
	$stats_html .= "<a href=pm.cgi?login=$fieldz[2]&action=display>$fieldz[2]</a>  </TD>";
	if($fieldz[5] eq "")
	{
	 $stats_html .= "\n\t<td bgcolor=ffffdd align=right nowrap> <FONT color=000000 face=arial size=2> <B> $fieldz[4] </td>";
	}
	else
	{
	 $stats_html .= "\n\t<td bgcolor=ffffdd align=right nowrap> <FONT color=000000 face=arial size=2> <B> $fieldz[5] </td>";
	}
	$stats_html .= "\n\t<td bgcolor=ffffdd align=left nowrap> <FONT color=000000 face=arial size=2><B>  $fieldz[6] </TD>";
	$stats_html .= "\n\t<td bgcolor=ffffdd align=left nowrap> <FONT color=000000 face=arial size=2><B>  $fieldz[7] </TD>";
	$stats_html .= "\n<tr>\n";
 }	
  $stats_html .= "</table>\n";
  $input{'next'} += $i; 
  if($i<$values{'total logins'}){
	$stats_html .= "<br><a href=admin.cgi?action=stats&pass=$input{'pass'}&number=$input{'number'}&next=$input{'next'}>next</a><br>";
  }

}

sub show_search_stats 
{

 if($input{'number'}<1){
 	$input{'number'} = 0;
 }

 open (STAT, "<${root}$h_search");
 while (($line = <STAT>))
 {	push (@statz, $line); }
 close STAT;

 @statz = reverse(@statz);

 $values{'total searches'} = @statz;
 if($values{'total searches'} > 10000){
	print "<p><b>Warning:</b> Delete(reset) $h_search file if this page gets very slow!<p>";
 }

 $where_next = 0;
 $stats_html .= "<table border=0><tr>
  <td bgcolor=navy align=right> <font color=white face=arial size=2><b>IP</b></td>
  <td bgcolor=navy align=left> <font color=white face=arial size=2><b>Query</b></td>
  </tr>";
 for($i=$input{'number'}; $i<$input{'number'}+20; $i++){
   $where_next++;
   $fcolor = ($where_next%2)?"navy":"teal";
   if($statz[$i] ne ""){
	   my($IP, $query) = split(/\|/, $statz[$i]);
	   $query_readable = join("<br>", split(/\&/, $query));
	   $stats_html .= "<tr><td valign=top><font color=$fcolor face=arial size=1>$IP</td>
		<td><a href=\"search.cgi?$query\" target=_blank><font color=$fcolor face=arial size=1>$query_readable</font></a></td></tr>";
   }
 } 
 $stats_html .= "</table><p>
		<a href=\"javascript:history.go(-1)\">Back</a>  "; 

 if($input{'number'}+20<$values{'total searches'}){
	 $where_next = $input{'number'}+20;
	 $stats_html .= "- <a href=admin.cgi?action=search_stats&pass=$input{'pass'}&number=$where_next>Next</a>";
 }

 $values{'stats'} = $stats_html;

}

 
sub show_stats 
{

 if($input{'number'}<1){
 	$input{'number'} = 20;
 }

 open (STAT, "<${root}$stat_file");
 while (($line = <STAT>))
 {	push (@statz, $line); }
 close STAT;

 $values{'total logins'} = @statz;
 if($values{'total logins'} > 10000){
	print "<p><b>Warning:</b> Delete stats.dat file if this page gets very slow!<p>";
 }

 &last_visitors;

 ($sec, $min, $hr, $today, $thismonth, $ye, $wd, $yd, $ds) =  localtime();

 my $day=$yd; my $win; my $exp;
 for(my $i=0; ($i<@statz)&&($yd-$day<20); $i++)
 {
	@statdetail = split(/\|/, $statz[$i]);
 	@digits = split(//, $statdetail[0]);
 	$day = 100*$digits[13]+10*$digits[14]+$digits[15]-100;
	@daycount[$day]++;
	if($statdetail[6] eq "Explorer") { $exp++; }
	if($statdetail[7] =~ m/Win/i) { $win++; }
	#print "$day -> $daycount[$day] -> $win -> $exp\n";
 }

 $values{'stats'} = $stats_html;

}

sub show_tracking
{

 my $perpage = 20;
 my $start = 0;
 if($input{'next'}>0){
	$start = $input{'next'};
 	$input{'next'} += $perpage;
 }

 my $nolines = 0;
 my $end = $start + $perpage;

 #- get the number of line on the file
 open (TRACK, "<${root}$track_file");
 $nolines++ while(<TRACK>);
 close TRACK;
 if($nolines > 10000){
	print "<p><b>Warning:</b> Delete or trim track.dat file if this page gets very slow!<p>";
 }

 $reverse_start = $nolines - $start;
 $reverse_end = $nolines - $end;

 my $count = 0;
 open (TRACK, "<${root}$track_file");
 while (($line = <TRACK>))
 {
	if($count<$reverse_start && $count>=$reverse_end){		
		push (@trackz, $line); 
	}
	$count++;
 }
 close TRACK;

  my $track_html = "";
  if($track_user ne "yes"){
	$track_html .= "<p>Currently disabled. <a href=setup.cgi?action=modify&variable=track_user>Enable this feature</a>.<p>";
  }

  $track_html .= "<TABLE border=0 cellspacing=0 cellpadding=3 width=700 align=center>";
  $track_html .= "\n<tr>";
  $track_html .="\n\t<td bgcolor=navy align=left width=200> <FONT color=white face=arial size=2> <B>  Time </TD>";
  $track_html .= "\n\t<td bgcolor=navy nowrap> <FONT color=white face=arial size=2> <B>  Login </TD>";
  $track_html .= "\n\t<td bgcolor=navy align=left nowrap> <FONT color=white face=arial size=2><B>  Action </TD>";
  $track_html .= "\n</tr>";


 foreach(reverse @trackz){
	my($l, $a, $t) = split /\|/;
	$track_html .= "\n<tr>";
	$track_html .="\n\t<td bgcolor=white align=left width=180> <FONT color=red face=arial size=2> <B>  $t </TD>";
	$track_html .= "\n\t<td bgcolor=ffffdd nowrap> <FONT color=black face=arial size=2> <b> <a href=pm.cgi?action=display&login=$l>$l</a> </TD>";
	$track_html .= "\n\t<td bgcolor=ffffdd align=left> <FONT color=black face=arial size=2><B>  $a </TD>";
	$track_html .= "\n</tr>";
 }
 $track_html .= "<tr><td><a href=\"javascript:history.go(-1)\">back</a></td><td></td><td align=right> ";
 $track_html .= "<a href=admin.cgi?action=tracking&next=$end>next</a>" if($reverse_end > 0);
 $track_html .=	"</td></tr>"; 
 $track_html .= "</table>\n";


 $values{'tracking'} = $track_html;
}



