#!/usr/bin/perl 
##########################################################################################
# Project: MF Catalog
# Function: Добавление url
#
# Copyright (c) 2001 HITEX
# Author: Vokhmianin Vladimir
# 	nightelf@zr.ru
# 	vladimir@hitexchange.ru
##########################################################################################

	use lib '/srv/www/vhosts/mp3s.ru/lib';
  use wclibvars qw(%config);
  use wclib qw($dbh);
	use ImageCode;
	use mp3s;
	use strict;

	mp3s::not_found if (mp3s::check_user_agent()==2); 

# ------------
# Get the input
  my %FORM = wclib::get_input();

# ----------------------
# Connect to the database
  wclib::db_connect();
  my $sth = '';
  my $query = '';

# --------------------------
# Send header
	wclib::send_header();

	srand(time ^ $$); my $rnd=int(rand(time));

	my %lang=(
		("1","русский"),
		("2","английский"),
		("0","другой")
	);
	my @slang=("1","2","0");

	my $lang_id=$FORM{'lang'};
	unless ($lang_id) {$lang_id=1;}
	my $cat_id=$FORM{'cat'};
	unless ($cat_id) {$cat_id=0;}

	$FORM{'name'}=substr($FORM{'name'},0,50);
	$FORM{'url'}=substr($FORM{'url'},0,250);
	$FORM{'descr'}=substr($FORM{'descr'},0,250);
	$FORM{'email'}=substr($FORM{'email'},0,50);
	my $send_mail=$FORM{'send_mail'};

	wclib::clear(\$FORM{'name'});
	wclib::clear(\$FORM{'descr'});

	my $ext_msg='';

	if ($FORM{'step1'} || $FORM{'step2'}) {

		my @hide=split(/\,/,$FORM{'req'});
		my $freq=0;
		my $req;
		my $lreq=@hide;
		foreach $req (@hide) {
			unless ($FORM{$req}) { $freq=1; }
		}

		my $err=0;
		if ($freq==1) {
			$ext_msg=qq~<tr><td align=center colspan=2><font color=Red><b>Не все обязательные поля заполнены.<br>Проверьте правильность заполнения формы.</b></font><br>&nbsp;<br></td></tr>~;
			$err=1;
		} elsif (!wclib::check_email($FORM{'email'})) {
			$ext_msg=qq~<tr><td align=center colspan=2><font color=Red><b>Не правильно введен Email адрес.<br>Выбирете другой email и повторите попытку заново.</b></font><br>&nbsp;<br></td></tr>~;
			$err=1;
		} elsif (check_url($FORM{'url'})>0) {
			$ext_msg=qq~<tr><td align=center colspan=2><font color=Red><b>Сайт $FORM{'url'} уже занесен в базу.<br>Выбирете другой url и повторите попытку заново.</b></font><br>&nbsp;<br></td></tr>~;
			$err=1;
		} else {
		
			my $status = 1;
			if ($FORM{'step2'}) {
				my $imagecode = ImageCode->new;
				$status = $imagecode -> checkpass($FORM{'hcode'},$FORM{'vcode'});
#				if ($status eq "1"){print "OK code valid";}
#				elsif ($status eq "2"){print "Code was xpired";exit}
#				else{print "Incorrect code";exit}
			}

			if ($status!=1) {
				$ext_msg=qq~<tr><td align=center colspan=2><font color=Red><b>Вы неверно указали цифровой код.</b></font><br>&nbsp;<br></td></tr>~;
				$err=1;
			}

			if ($FORM{'step1'} || $err==1) {

				my $imagecode = ImageCode->new(
					passlength => 4,
    	  	expires => 5,
      		chars => [0..9],
	      	fontsize => 40,
  	    	fontcolors => ['#800000','#008000', '#000080']
				);
				my ($icode,$hcode)=$imagecode -> generatepass();

				my $send_mail_ch=($send_mail)?"":"не";
				unless ($send_mail) {$send_mail=0;}

			  # Output
			 	open(OUT,"./blank/add_conf.html") || print "err";
				while(<OUT>) {

					s/%ext_msg%/$ext_msg/;

					s/%send_mail%/$send_mail/;
					s/%send_mail_ch%/$send_mail_ch/;
					if (s/%lang_ch%//) {
						my $lang_id=",$lang_id,";
						foreach my $key (@slang) {
							if ($lang_id=~/,$key,/) {
								print qq~ $lang{$key} ~;
							}
						}
					}
					s/%lang%/$lang_id/g;
					s/%name%/$FORM{'name'}/g;
					s/%url%/$FORM{'url'}/g;
					s/%descr%/$FORM{'descr'}/g;
					s/%email%/$FORM{'email'}/g;

					s/%category%/list(0,-1,",$cat_id,")/e;

					s/%icode%/$icode/;
					s/%hcode%/$hcode/;

					print;
				}

				wclib::db_disconnect();
				wclib::exit();

			} elsif ($FORM{'step2'}) {

				unless($lang_id) {$lang_id=0;} else {$lang_id=",$lang_id,";}

				wclib::oclear(\$FORM{'name'});
				wclib::oclear(\$FORM{'descr'});

				$query=qq!
					INSERT INTO cURL 
					(name, url, info, LANG_ID, email, date_reg)
					VALUES 
					(?, ?, ?, '$lang_id', ?, sysdate())
				!;
				$sth = $dbh -> prepare($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		  	$sth -> execute($FORM{'name'}, $FORM{'url'}, $FORM{'descr'}, $FORM{'email'}) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				my $url_id = $dbh->{'mysql_insertid'};
		  	$sth -> finish;

				$query = qq!
					INSERT INTO cSWAP
		    	(URL_ID,CAT_ID,date_reg)
					VALUES
					(?,?,sysdate())
				!;
			  $sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
				my @category=split(",",$cat_id);
				foreach my $category_id (@category) {
				  $sth -> execute($url_id,$category_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
		  		$sth -> finish;
				}

				if ($FORM{'add_cat'}) {
					my $date=scalar localtime;
					open (MAIL,"|$config{'sendmail'} -t")||die "$!";
					print MAIL "To:$config{'emailaddy'}\n";
					print MAIL "From:$FORM{'email'}\n";
					print MAIL "Subject: [mp3s.ru] >> add category\n\n";
					print MAIL "\n\n";
					print MAIL "------------------------------------------------------\n";
					print MAIL "$FORM{'add_cat'}\n";
					print MAIL "------------------------------------------------------\n";
					print MAIL "\n";
					close(MAIL); 
				}

			  # Output
 				open(OUT,"./blank/add_ok.html");
				while(<OUT>) {
					s/%email%/$FORM{'email'}/;
					print;
				}
		
				wclib::db_disconnect();
				wclib::exit();

			}
		}
	}
	
  # Output
 	open(OUT,"./blank/add.html");
	while(<OUT>) {
		s/%referrer%/$ENV{'HTTP_REFERER'}/e;

		s/%ext_msg%/$ext_msg/;

		s/%send_mail_ch%/ checked/;
		if (s/%lang%//) {
			my $lang_id=",$lang_id,";
			foreach my $key (@slang) {
				my $ch=($lang_id=~/,$key,/)?" checked":"";
				print qq~<input type=checkbox name=lang value="$key"$ch> $lang{$key} ~;
			}
		}
		s/%name%/$FORM{'name'}/;
		s/%url%/$FORM{'url'}/;
		s/%descr%/$FORM{'descr'}/;
		s/%email%/$FORM{'email'}/;
		print;
	}

	wclib::db_disconnect();

##########################################################################################
# Выводим каталог лотов
##########################################################################################

sub list {
	my ($pcat_id,$enclosure,$category_id)=@_;

	my $indent = "";
	$enclosure++;
	for( my $i = 0; $i < $enclosure; $i++ ) {
  	$indent .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	}

	my $query = qq!
		SELECT CAT_ID, name, Visible
		FROM cCategory
    WHERE Visible=0 AND PARENT_ID=?
		ORDER BY Sort
	!;
  my $sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
  $sth -> execute($pcat_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
  while (my ($cat_id,$cat_name,$vis) = $sth -> fetchrow_array) {
		my $sel=($category_id=~/,$cat_id,/)?" checked":"";
		my $ch=(check_category($cat_id)==0)?qq~<input type="checkbox" name="cat" value="$cat_id"$sel>~:qq~&nbsp;<b>&gt;&gt;</b>&nbsp;<img src="http://www.mp3s.ru/img/pix.gif" width=1 height=16>~;
		#qq~<img src="http://www.mp3s.ru/img/pix.gif" width=20 height=16>~;
		my ($b,$e)=("<font color=cc0000><b>","</b></font>");
		if ($ch=~/checkbox/) { ($b,$e)=("<font color=777777>","</font>"); }
		if ($enclosure==0) {
			print qq~$ch<b>$cat_name</b><br>~;
		} else {
			print qq~$indent$ch$b$cat_name$e<br>~;
		}
		&list($cat_id,$enclosure,$category_id);
	}
  $sth -> finish;
	return "";
}

##########################################################################################
# Проверяем название категории по id
##########################################################################################

sub check_category {
	my $category_id=shift;
	my $query = qq!
		SELECT COUNT(*)
		FROM cCategory
    WHERE Visible=0 AND PARENT_ID=?
	!;
  my $sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
  $sth -> execute($category_id) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
  my ($count) = $sth -> fetchrow_array;
  $sth -> finish;
	return $count;
}

##########################################################################################
# Проверяем название категории по id
##########################################################################################

sub check_url {
	my $url=shift;
	my $query = qq!
		SELECT COUNT(*)
		FROM cURL
    WHERE URL=?
	!;
  my $sth = $dbh -> prepare ($query) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
  $sth -> execute($url) || wclib::panic("Соединение с базой невозможно", $dbh->errstr.":".$query);
  my ($count) = $sth -> fetchrow_array;
  $sth -> finish;
	return $count;
}

##########################################################################################
# EOF Last Update: 28.10.2006 15:18:44, Vokhmianin Vladimir
