#!/usr/bin/perl
# ben-adembaba@hotmail.com    mail@turkdvb.com
# www.turkdvb.com


use WebminCore;
do '../csp-lib.pl';
&init_config();
do '../cs-lib.pl';
use Time::Local;

sub list_exports
{
local (@rv, $pos, $lnum, $h, $o, $line);
return @list_exports_cache if (@list_exports_cache);
open(EXP, $config{'cccam_cfg'});
$lnum = 0;
while($line = <EXP>) {
	local $slnum = $lnum;
	$line =~ s/\s+$//g;
	while($line =~ /\\$/) {
		# continuation character!
		$line =~ s/\\$//;
		$line .= <EXP>;
		$line =~ s/\s+$//g;
		$lnum++;
		}
$user = '([a-zA-Z0-9öçşüğı\-_.?+=]+)'; #$3
$pass = '([a-zA-Z0-9öçşüğı\-_.?+=]+)'; #$4

$au  = '(([0-9]+)([ ]+)([0-9]+)([ ]+)([0-9]+))'; #$5
$saat = '(([ ]+){([ ]+)}([ ]+){ ([0-9-:, ]+)([ ]+)}+)';

$not = '(#Not=(.*))';
$mail = '(#Mail=([a-zA-Z0-9-_@.]+))';
$tarih  = '(#Tarih=(([0-9]{4,4})-([0-9]{1,2})-([0-9]{1,2})))';


$rshr = '(([0-9]+):([0-9]+):([0-9]+)),? ?';
$chn = '([a-zA-Z0-9:, ]{3,800})';
	if ($line =~ /^\s*(#*)([Ff:]+) $user $pass? ?$au?([ ]+)?(({ )($rshr$chn?)( }))?$saat?([ ]+)?$tarih?([ ]+)?$mail?([ ]+)?$not?/) {
		local $active = !$1;
		local $dir = $3;
		local $rest = $6;
                if ($dir =~ /^$config{'cccam_cfg'}/) {
			$lnum++;
			next;
               		}
		$pos = 0;

			local %exp;
			$exp{'active'} = $active;
			$exp{'aktif'} = !$1 ? scalar(@rv):'';
			$exp{'deaktif'} = $1 ? scalar(@rv):'';
            $exp{'dir'} = $3,
            $exp{'user'} = $3,
			$exp{'passaword'} = $4,
			$exp{'au'} = $5,
			$exp{'yasak'} = $19,
			$exp{'reshare'} = $15,
			$exp{'reshare_index'} = $18,

#			$exp{'p_lokal'} = $19,

			$exp{'saat'} = $25,
			$exp{'tarih'} = $29,
		  $exp{'yil'} = $30,
		  $exp{'ay'} = $31,
		  $exp{'gun'} = $32,

			$exp{'mail'} = $35,
			$exp{'not'} = $38,
			$rest = $3;

			$exp{'line'} = $slnum;
			$exp{'eline'} = $lnum;
			$exp{'pos'} = $pos++;
			$exp{'index'} = scalar(@rv);

###############################################



eval{$date=timelocal(0,0,0,$32,$31-1,$30-1900)};
if ($date > time()){
}else{
$exp{'user'} = $3;
$exp{'sira'} = scalar(@rv);

}

#################################################
			push(@rv, \%exp);

		}
	$lnum++;
	}
close(EXP);
@list_exports_cache = @rv;
return @list_exports_cache;
}
&use_webmin();
# delete_export(&export)
# Delete an existing export
sub delete_export
{
local @exps = &list_exports();
local @same = grep { $_ ne $_[0] && $_->{'line'} eq $_[0]->{'line'} } @exps;
local $lref = &read_file_lines($config{'cccam_cfg'});
if (@same) {
	# other exports on the same line.. cannot totally delete
	splice(@$lref, $_[0]->{'line'}, $_[0]->{'eline'}-$_[0]->{'line'}+1,
	       &make_exports_line(@same));
	map { $_->{'line'} = $_->{'eline'} = $_[0]->{'line'} } @same;
	}
else {
	# remove export line
	splice(@$lref, $_[0]->{'line'}, $_[0]->{'eline'}-$_[0]->{'line'}+1);
	# unmount the directory if it is mounted with --bind
	local $dir = $_[0]->{'dir'};

	for(my $i=0; $i<@mounted; $i++) {
	    my $p = $mounted[$i];
	    if (($p->[0] eq $dir) and ($p->[2] eq "bind")) {
		&mount::unmount_dir($p->[1], $p->[0], $p->[2]);
	    }
	}
	# remove it from the fstab file
	for(my $i=0; $i<@mounts; $i++) {
	    my $p = $mounts[$i];
	    if (($p->[0] eq $dir) and ($p->[2] eq "bind")) {
		&mount::delete_mount($i);
	    }
	}
    }
@list_exports_cache = grep { $_ ne $_[0] } @list_exports_cache;
&flush_file_lines();
}

# create_export(&export)
sub create_export
{
&open_tempfile(EXP, ">>$config{'cccam_cfg'}");
&print_tempfile(EXP, &make_exports_line($_[0]),"\n");
&close_tempfile(EXP);
}

# modify_export(&export, &old)
sub modify_export
{
local @exps = &list_exports();
local @same = grep { $_->{'line'} eq $_[1]->{'line'} } @exps;
local $lref = &read_file_lines($config{'cccam_cfg'});
if ($_[0]->{'dir'} eq $_[1]->{'dir'} &&
    $_[0]->{'active'} == $_[1]->{'active'} || @same == 1) {
	# directory or active not changed, or on a line of it's own
	splice(@same, &indexof($_[1],@same), 1, $_[0]);
	splice(@$lref, $_[1]->{'line'}, $_[1]->{'eline'}-$_[1]->{'line'}+1,
	       &make_exports_line(@same));
	}
else {
	# move to a line of it's own
	splice(@same, &indexof($_[1],@same), 1);
	splice(@$lref, $_[1]->{'line'}, $_[1]->{'eline'}-$_[1]->{'line'}+1,
	       &make_exports_line(@same));
	push(@$lref, &make_exports_line($_[0]));
	}
&flush_file_lines();
}

# make_exports_line([&export]+)
sub make_exports_line
{
local ($e, @htxt);
foreach $e (@_) {
	local %opts = %{$e->{'options'}};
	if (%opts || !$e->{'passaword'}) {
		push(@htxt, $e->{'passaword'}."(".
			    join(",", map { $opts{$_} eq "" ? $_
							    : "$_=$opts{$_}" }
			    (keys %opts)).")");
		}
	else { push(@htxt, $e->{'passaword'}); }
	}
return ($_[0]->{'active'} ? "" : "#").
             ("F: $_[0]->{'dir'} $_[0]->{'passaword'} ").
             ($_[0]->{'au'}      ? "$_[0]->{'au'} ":"").
             ($_[0]->{'reshare'} ? "{ $_[0]->{'reshare'}"     : "{").
             ($_[0]->{'yasak'}   ? ", $_[0]->{'yasak'} }"     : " }").
             ($_[0]->{'saat'}    ? " { } { $_[0]->{'saat'} }" : "").
             ($_[0]->{'gun'}     ? " #Tarih=$_[0]->{'yil'}-$_[0]->{'ay'}-$_[0]->{'gun'}" : "").
             ($_[0]->{'mail'}    ? " #Mail=$_[0]->{'mail'}" : "").
             ($_[0]->{'not'}     ? " #Not=$_[0]->{'not'}" : "");
}

######################
#############################################################################
######################
#############################################################################
sub get_config
{
local $file = $_[0] || $config{'cccam_cfg'};
if (!defined(@get_config_cache)) {
	local $lnum = 0;
	@get_config_cache = ( );
	&open_readfile(CONF, $file);
	while(<CONF>) {
		s/\r|\n//g;
                s/#.*$//;
		if (/^(#?)(.*)( : )(.*)/) {
			push(@get_config_cache, { 'name' => $2,
						  'port' => $4,
						  'enabled' => !$1,
						  'line' => $lnum,
						  'file' => $file });
			}
		$lnum++;
		}
	close(CONF);
	}
return \@get_config_cache;
}

# find(name, &conf, disabled-mode)
sub find
{
local ($name, $conf, $dis) = @_;
local @rv = grep { $_->{'name'} eq $name } @$conf;
if ($dis == 0) {
	# Enabled only
	@rv = grep { $_->{'enabled'} } @rv;
	}
elsif ($dis == 1) {
	# Disabled only
	@rv = grep { !$_->{'enabled'} } @rv;
	}
return wantarray ? @rv : $rv[0];
}

# find_value(name, &conf)
sub find_value
{
local ($name, $conf, $dis) = @_;
local @rv = map { $_->{'port'} } &find($name, $conf, $dis);
return wantarray ? @rv : $rv[0];
}

sub find_svalue
{
local $rv = &find_value(@_);
return $rv;
}

#############################################################################
###################### xxxxxxxxx ############################################
#############################################################################
sub ay
{
[ [],
[ "01", "Ocak" ],
[ "02", "Şubat" ],
[ "03", "Mart" ],
[ "04", "Nisan" ],
[ "05", "Mayıs" ],
[ "06", "Haziran" ],
[ "07", "Temmuz" ],
[ "08", "Ağustos" ],
[ "09", "Eylül" ],
[ "10", "Ekim" ],
[ "11", "Kasım" ],
[ "12", "Aralık" ] ]
}
sub yil
{
[ [],map { [ $_, ($_+0) ] } ( 2010 .. 2020 )];
}

sub services_button
{
return undef if (!&supports_users());
return &theme_user_chooser_button(@_)
	if (defined(&theme_user_chooser_button));
my $form = defined($_[2]) ? $_[2] : 0;
my $w = $_[1] ? 600 : 320;
my $h = 270;
if ($_[1] && $gconfig{'db_sizeusers'}) {
	($w, $h) = split(/x/, $gconfig{'db_sizeusers'});
	}
elsif (!$_[1] && $gconfig{'db_sizeuser'}) {
	($w, $h) = split(/x/, $gconfig{'db_sizeuser'});
	}
return "<input type=button onClick='ifield = form.$_[0]; chooser = window.open(\"./user_chooser.cgi?multi=$_[1]&user=\"+escape(ifield.value), \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=$w,height=$h\"); chooser.ifield = ifield; window.ifield = ifield' value=\"ServisEkle\">\n";
}
#############################################################################
###################### Üye Ekle
#############################################################################
sub turkdvb_com
{
$style="style='border-style: dashed; border-width: 1px'";
($date, $time) = split(/\s+/, &make_date(time()));
print "<tr>";
print &ui_table_start("$text{'users_title1'}  | $text{'index_bugun'}:$date","width=600");

print &ui_form_start("save_users.cgi", "post");
print "<input type=hidden name=new value=1>\n";
print "<input type=hidden name=active value=1>\n";
@mcc="<b><font color=red>*</font><b>";

print "<tr><td><b>$text{'users_username'} @mcc</b><br><input name=dir size=19></td>\n";
print "<td><b>$text{'users_passaword'} @mcc</b><br><input name=passaword size=19></td>\n";

print "<td><b>$text{'users_reshare1'}<br>".
		&ui_select("reshare", $exp->{'reshare'},
				    [ [ "0:0:1", "Kapalı"],
                      [ "0:0:2", "Reshare1"],
                      [ "0:0:3", "Reshare2"],
                      [ "0:0:4", "Reshare3"],
                      [ "0:0:5", "Reshare4"],
                      [ "0:0:6", "Reshare5"] ]),"</td>\n";


print "<td $style align=center><b>$text{'users_tarih'}</b><br>", 
   (&ui_select("year", $exp->{'yil'}-1,
		   [ map { [ ($_) ] } ( 2010 .. 2023 ) ]).
	&ui_select("month", $exp->{'ay'}-1,
		   [ map { [ $_+1 ] } ( 0 .. 11 ) ]).
	&ui_textbox("day", $exp->{'gun'}, 2).
	&date_chooser_button("day", "month", "year")),"</td></tr>\n";


print &ui_table_hr();



print "<tr><td><b>$text{'users_not'}</b><br><input name=not size=19></td>\n";

print "<td><b>$text{'users_mail'}</b><br><input name=mail size=19></td>\n";

print "<td><b>$text{'users_au'}<br>".
                  &ui_select("au", $exp->{'au'},
				    [ [ "2 0 0", "$text{'no'}" ],
				      [ "2 0 1", "$text{'yes'}" ] ]),"</td>\n";

#style='border-style: outset; border-width: 1px'

print "<td align=center><b>$text{'users_saat'}</b><br>
       <font size=1>$text{'example'}</font> : </b>
       <font size=1 color=red>12:00-17:00,</font>
       <font size=1 color=blue>19:00-20:00</font><br>
       <input name=saat size=26></td>\n";
print "<td></td></tr>\n";

print "<td><b></b></td></tr>\n";
print &ui_hidden_table_start($text{'service_blok'},"width=%100", 1, "services");

print "<tr><td>",&ui_table_row($text{'service_blocked'},
    &services_button("yasak", 1)."<br>".
	&ui_textarea("yasak", join("\n", $exp->{'yasak'}), 7, 50)."<br>".
	&services_button("yasak", 1)),"</td></tr>\n";

print &ui_hidden_table_end("services");
print "<tr><td align=right>", &ui_form_end([ [ 'save', $text{'create'} ] ]),"</td></tr>\n";

print &ui_table_end();


}

####################################################################################################
############################ ara ###################################################
sub ara
{
print &ui_table_start("$text{'ara_header'}","width=200");
print &ui_form_start("users.cgi", "post");
print "<input type=hidden name=araok value=1>\n";
print "<tr><td><b></b><input name=ara size=21></td>\n";
print "<td align=right>", &ui_form_end([ [ 'save', $text{'ara'} ] ]),"</td></tr>\n";
print &ui_table_end();

}
###################################################################################
sub ara1
{
"<form action=users.cgi>
<input type=hidden name=araok value=1 />
Üye$text{'ara'}<input name=ara type=textbox size=10>
<input name=save type=submit value=$text{'ara'}></form>"
}

##################################################################
################################# Remove Warn File ####################################
sub rm_logwarnings{
$conf = &get_config();
$warnfile = &find_svalue("LOG WARNINGS", $conf);
system "rm -rf $warnfile";
}
#######################################################################################
sub istatistik_uye{
$conf = &get_config();
@exps = &list_exports();
	$total = &unique(map { $_->{'index'} } @exps);


	$deaktif = &unique(map { $_->{'deaktif'} } @exps);
	$aktif = &unique(map { $_->{'aktif'} } @exps);

$end = &unique(map { eval { $date=timelocal(0,0,0,$_->{'gun'},$_->{'ay'}-1,$_->{'yil'}-1900)};
$date > time() ? '': $_->{'tarih'} ? $_->{'dir'}:"" } @exps);

@toplamuye=$total;
@enddate=$end-1;
@aktifuye=$aktif-1;
@deaktifuye=$deaktif-1;

$logwarnings = &find_svalue("LOG WARNINGS", $conf);
$sharingport = &find_svalue("SERVER LISTEN PORT", $conf);
$webinfoport = &find_svalue("WEBINFO LISTEN PORT", $conf);




print "<table cellpadding=5><tr>";
 print "<td valign=top><table class=ui_table>";
   print "<tr class=row0><td align=right>Toplam Müşteri Sayısı : </td> <td><font color=blue>@toplamuye</font></td></tr>";
   print "<tr class=row1><td align=right>Aktif Müşteriler : </td>      <td><font color=blue>@aktifuye</font></td></tr>";
   print "<tr class=row0><td align=right>Deaktif Müşteriler  : </td>   <td><font color=blue>@deaktifuye</font></td></tr>";
   print "<tr class=row1><td align=right>Üyeliği Bitenler : </td>      <td><font color=blue>@enddate</font></td></tr>";
 print "</table></td>";

   print "<td valign=top><table class=ui_table><br /></table></td>";

 print "<td valign=top><table class=ui_table>";
   print "<tr class=row1><td align=right>CCcam Sharing Port : </td> <td><font color=blue>$sharingport</font></td></tr>";
   print "<tr class=row0><td align=right>CCcam Web Info Port : </td>      <td><font color=blue>$webinfoport</font></td></tr>";
   print "<tr class=row1><td align=right>Log Warning  : </td>   <td><font color=blue>$logwarnings</font></td></tr>";
 print "</table></td>";
print "</tr></table> ";



}
#######################################################################################

1;