###############################################################################
# Notify.pl                                                                   #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2 RC 1                                                 #
# Released:       December 27, 2004                                           #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2005 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by: The YaBB Development Team                                      #
#              with assistance from the YaBB community.                       #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$notifyplver = 'YaBB 2 RC 1 $Revision: 1.23 $';
if($action eq 'detailedversion') { return 1; }

LoadLanguage("Notify");

sub BoardNotify {
	if(!$currentboard) { &fatal_error($maintxt{'1'}); }
	if($iamguest) { &fatal_error("$maintxt{'138'}"); }
	my( $thread, $line, $start, $curmail, $curuser, $curlang );
	if ($INFO{'thread'} =~ m~/~){
		($thread,$start) = split('/',$INFO{'thread'}); 
	} else {
		$thread = $INFO{'thread'};
		$start = $INFO{'start'};
	}
	my $isonlist = 0;

	# Check, if User already gets a notification
	fopen(NOTIFY, "$boardsdir/$currentboard.mail");
	my @notifications = <NOTIFY>;
	fclose(NOTIFY);

	foreach $line (@notifications) {
		$line =~ s/[\n\r]//g;
		($curuser,$curmail,$curlang,$notifytype,$hasviewed) = split (/\|/, $line,5);
		if(${$uid.$username}{'email'} eq "$curmail") { $isonlist = 1; }
		${selected.$notifytype} = qq~ selected="selected"~;
	}

	if ($isonlist){
	$yymain .= qq~
<form action="$scripturl?action=boardnotify2" method="post">
<input type="hidden" name="curboard" value="$currentboard" />
<table border="0" width="100%" cellspacing="1" cellpadding="4" class="bordercolor">
  <tr>
    <td align="left" class="titlebg"><span class="text1"><b>$maintxt{'125'}</b></span></td>
  </tr><tr>
    <td class="windowbg">
    $maintxt{'212'}<br />
<br />
<select name="notify_type">
<option value="1"$selected1>New Threads Only</option>
<option value="2"$selected2>All New Posts</option>
</select><br />
<input type="submit" value="Submit" />
    </td>
  </tr>
</table>
</form>
~;
	} else {
	$yymain .= qq~
<form action="$scripturl?action=boardnotify2" method="post">
<input type="hidden" name="curboard" value="$currentboard" />
<table border="0" width="100%" cellspacing="1" cellpadding="4" class="bordercolor">
  <tr>
    <td class="titlebg"><span class="text1"><b>$maintxt{'125'}</b></span></td>
  </tr><tr>
    <td class="windowbg">
    $maintxt{'126'}<br />
<br />
<select name="notify_type">
<option value="1"$selected>New Threads Only</option>
<option value="2"$selected>All New Posts</option>
</select><br />
<input type="submit" value="Submit" />
    </td>
  </tr>
</table>
</form>
~;
	}
	$yytitle = "$maintxt{'125'}";
	&template;
	exit;
}


sub BoardNotify2 {

# This value is important. If we have it too high,
# Someone can over-use server resources by changing notification type.
# As changing to "notify of all new posts" writes to the thread.mail files
# This value limits it to writing to the latest thread.mail files only
# The competant admin can increase it if they so desire.
# It shouldn't be a problem except on larger boards,
# And rarely does anyone update a topic that is older than this.

$flood_notify_cutoff = 99;


#	if( $currentboard eq '' ) { &fatal_error($maintxt{'1'}); }
	if($iamguest) { &fatal_error($maintxt{'138'}); }

$currentboard = $FORM{'curboard'};
$notify_type = $FORM{'notify_type'};

	if (!-e "$boardsdir/$currentboard.mail") {
		fopen(NOTIFY, ">$boardsdir/$currentboard.mail");
		print NOTIFY "$username|${$uid.$username}{'email'}|${$uid.$username}{'language'}|$notify_type|1\n";
		fclose(NOTIFY);
	} else {
		fopen(NOTIFY, "+<$boardsdir/$currentboard.mail");
		seek NOTIFY,0,0;
		my @notifications = <NOTIFY>;
		seek NOTIFY,0,0;
		truncate NOTIFY,0;
		# add user to the notification file
		print NOTIFY "$username|${$uid.$username}{'email'}|${$uid.$username}{'language'}|$notify_type|1\n";
		foreach $line (@notifications) {
			chomp $line;
			($curuser,$curmail,$curlang,$notifytype,$hasviewed) = split (/\|/, $line,5);
			$line = "$curuser|$curmail|$curlang|$notifytype|";
			if($username ne $curuser) { print NOTIFY "$line\n"; }
		}
		fclose(NOTIFY);
	}



if ($notify_type = "2") {

	fopen(THREADNOTIFY, "$boardsdir/$currentboard.txt");
	my @all_threads = <THREADNOTIFY>;
	fclose(THREADNOTIFY);
	$i = 1;
	foreach $thread (@all_threads) {
	if ($i == $flood_notify_cutoff) { last; }
	chomp $thread;
	($threadid,$void,$void,$void,$void,$void,$void,$void,$void) = split (/\|/, $thread);

	if (!-e "$datadir/$threadid.mail") {
		fopen(NOTIFY, ">$datadir/$threadid.mail");
		print NOTIFY "$username|${$uid.$username}{'email'}|${$uid.$username}{'language'}|1|1\n";
		fclose(NOTIFY);
	} else {
		fopen(NOTIFY, "+<$datadir/$threadid.mail");
		seek NOTIFY,0,0;
		my @notifications = <NOTIFY>;
		seek NOTIFY,0,0;
		truncate NOTIFY,0;
		# add user to the notification file
		print NOTIFY "$username|${$uid.$username}{'email'}|${$uid.$username}{'language'}|1|1\n";
		foreach $line (@notifications) {
			chomp $line;
			($curuser,$curmail,$curlang,$notifytype,$hasviewed) = split (/\|/, $line,5);
			$line = "$curuser|$curmail|$curlang|$notifytype|";
			if($username ne $curuser) { print NOTIFY "$line\n"; }
		}
		fclose(NOTIFY);
	}
		$i++;
	}
}

	$yySetLocation = qq~$scripturl?board=$currentboard~;
	&redirectexit;

}


sub BoardNotify3 {

	if($iamguest) { &fatal_error("$maintxt{'138'}"); }
	my( $variable, $dummy, $dummy2, $boardno, $curmail, $curuser, $curlang );

	foreach $variable (keys %FORM) {
		$new_notify = $FORM{"$variable"};
		($dummy2,$boardno) = split(/-/,$variable);
		if ($dummy2 eq "board"){

			fopen(NOTIFY, "+<$boardsdir/$boardno.mail");
			seek NOTIFY,0,0;
			my @notifications = <NOTIFY>;
			# change notification type
				truncate NOTIFY,0;
				seek NOTIFY,0,0;
				foreach $line (@notifications) {
					$line =~ s/[\n\r]//g;
					($curuser,$curmail,$curlang,$notifytype,$hasviewed) = split (/\|/, $line);
					if($username eq $curuser) {
$line = "$curuser|$curmail|$curlang|$new_notify|$hasviewed";
						print NOTIFY "$line\n";
					}
				}
				fclose(NOTIFY);
		}
	}

	$yySetLocation = qq~$scripturl?action=shownotify~;
	&redirectexit;
}


sub BoardNotify4 {

if($iamguest) { &fatal_error("$maintxt{'138'}"); }
$boardno = $INFO{'board'};

if(-e "$boardsdir/$boardno.mail") {

	my( $thread, $line, $start, $curmail, $curuser, $curlang );

	fopen(NOTIFY, "+<$boardsdir/$boardno.mail");
	seek NOTIFY,0,0;
	my @notifications = <NOTIFY>;

	# if there is only one entry and this is the address which is to remove, remove the file at all

	if( $#notifications eq 0) {
		fclose(NOTIFY);
		unlink("$boardsdir/$boardno.mail");
	} else {

	# remove user from the notification file
		truncate NOTIFY,0;
		seek NOTIFY,0,0;
		foreach $line (@notifications) {
			$line =~ s/[\n\r]//g;
			($curuser,$curmail,$curlang,$notifytype,$hasviewed) = split (/\|/, $line);

			if($username ne $curuser) { print NOTIFY "$line\n"; }
		}
		fclose(NOTIFY);

	}
}

	$yySetLocation = qq~$scripturl?action=shownotify~;
	&redirectexit;

}


sub Notify {
#	if( $currentboard eq '' ) { &fatal_error($maintxt{'1'}); }
	if($iamguest) { &fatal_error("$maintxt{'138'}"); }
	my( $thread, $line, $start, $curmail, $curuser, $curlang );
	if ($INFO{'thread'} =~ m~/~){
		($thread,$start) = split('/',$INFO{'thread'}); 
	} else {
		$thread = $INFO{'thread'};
		$start = $INFO{'start'};
	}
	my $isonlist = 0;

	# Check, if User already gets a notification
	fopen(NOTIFY, "$datadir/$thread.mail");
	my @notifications = <NOTIFY>;
	fclose(NOTIFY);

	foreach $line (@notifications) {
		$line =~ s/[\n\r]//g;
		($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $line);
		if(${$uid.$username}{'email'} eq "$curmail") { $isonlist = 1; }
	}

	if ($isonlist){
	$yymain .= qq~
<table border="0" width="100%" cellspacing="1" class="bordercolor">
  <tr>
    <td align="left" class="titlebg"><span class="text1"><b>$maintxt{'125'}</b></span></td>
  </tr><tr>
    <td class="windowbg">
    $maintxt{'212'}<br />
    <b><a href="$scripturl?action=notify3;thread=$thread/$start">$maintxt{'163'}</a> - <a href="$scripturl?num=$thread/$start">$maintxt{'164'}</a></b>
    </td>
  </tr>
</table>
~;
	} else {
	$yymain .= qq~
<table border="0" width="100%" cellspacing="1" class="bordercolor">
  <tr>
    <td class="titlebg"><span class="text1"><b>$maintxt{'125'}</b></span></td>
  </tr><tr>
    <td class="windowbg">
    $maintxt{'126'}<br />
    <b><a href="$scripturl?action=notify2;thread=$thread/$start">$maintxt{'163'}</a> - <a href="$scripturl?num=$thread/$start">$maintxt{'164'}</a></b>
    </td>
  </tr>
</table>
~;
	}
	$yytitle = "$maintxt{'125'}";
	&template;
	exit;
}

sub NoNotify {
# This Sub removes the read flag from .mail files even if the poster
# Hasn't selected to be notified of replies
# Has the nice side-effect of removing notifications
# If the user unticks the notificiation box, when notification was enabled.
	if (-e "$datadir/$thread.mail") {
		fopen(NOTIFY, "+<$datadir/$thread.mail");
		seek NOTIFY,0,0;
		my @notifications = <NOTIFY>;
		seek NOTIFY,0,0;
		truncate NOTIFY,0;
		seek NOTIFY,0,0;
		foreach $line (@notifications) {
			chomp $line;
			($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $line);
			$line = "$curuser|$curmail|$curlang|$isboardnotify|";
			if($username ne $curuser) { print NOTIFY "$line\n"; }
		}
		fclose(NOTIFY);
	}
}

sub Notify2 {
#	if( $currentboard eq '' ) { &fatal_error($maintxt{'1'}); }
	if($iamguest) { &fatal_error($maintxt{'138'}); }
	my( $thread, $line, $start, $curmail, $curuser, $curlang, $isboardnotify );
	if ($INFO{'thread'} =~ m~/~){
		($thread,$start) = split('/',$INFO{'thread'}); 
	} else {
		$thread = $INFO{'thread'};
		$start = $INFO{'start'};
	}

	if (!-e "$datadir/$thread.mail") {
		fopen(NOTIFY, ">$datadir/$thread.mail");
		print NOTIFY "$username|${$uid.$username}{'email'}|${$uid.$username}{'language'}||1\n";
		fclose(NOTIFY);
	} else {
		fopen(NOTIFY, "+<$datadir/$thread.mail");
		seek NOTIFY,0,0;
		my @notifications = <NOTIFY>;
		seek NOTIFY,0,0;
		truncate NOTIFY,0;
		# add user to the notification file
		print NOTIFY "$username|${$uid.$username}{'email'}|${$uid.$username}{'language'}||1\n";
		foreach $line (@notifications) {
			chomp $line;
			($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $line);
			$line = "$curuser|$curmail|$curlang||";
			if($username ne $curuser) { print NOTIFY "$line\n"; }
		}
		fclose(NOTIFY);
	}
	$yySetLocation = qq~$scripturl?num=$thread/$start~;
	&redirectexit;
}

sub Notify3 {
	if($iamguest) { &fatal_error("$maintxt{'138'}"); }
	my( $thread, $line, $start, $curmail, $curuser, $curlang );
	if ($INFO{'thread'} =~ m~/~){
		($thread,$start) = split('/',$INFO{'thread'}); 
	} else {
		$thread = $INFO{'thread'};
		$start = $INFO{'start'};
	}

	fopen(NOTIFY, "+<$datadir/$thread.mail");
	seek NOTIFY,0,0;
	my @notifications = <NOTIFY>;
	# if there is only one entry and this is the address which is to remove, remove the file at all

	if( $#notifications eq 0) {
		fclose(NOTIFY);
		unlink("$datadir/$thread.mail");
	} else {
	# remove user from the notification file
		truncate NOTIFY,0;
		seek NOTIFY,0,0;
		foreach $line (@notifications) {
			$line =~ s/[\n\r]//g;
			($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $line);
			if($username ne $curuser) { print NOTIFY "$line\n"; }
		}
		fclose(NOTIFY);
	}
	$yySetLocation = qq~$scripturl?num=$thread/$start~;
	&redirectexit;
}

sub Notify4 {
	if($iamguest) { &fatal_error("$maintxt{'138'}"); }
	my( $variable, $dummy, $dummy2, $threadno, $curmail, $curuser, $curlang );

	foreach $variable (keys %FORM) {
	 	$dummy = $FORM{$variable};
		($dummy2,$threadno) = split(/-/,$variable);
		if ($dummy2 eq "thread"){
			fopen(NOTIFY, "+<$datadir/$threadno.mail");
			seek NOTIFY,0,0;
			my @notifications = <NOTIFY>;
			# if there is only one entry and this is the address which is to remove, remove the file at all
		
			if( $#notifications eq 0) {
				fclose(NOTIFY);
				unlink("$datadir/$threadno.mail");
			} else {
			# remove user from the notification file
				truncate NOTIFY,0;
				seek NOTIFY,0,0;
				foreach $line (@notifications) {
					$line =~ s/[\n\r]//g;
					($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $line);
					if($username ne $curuser) { print NOTIFY "$line\n"; }
				}
				fclose(NOTIFY);
			}
		}
	}
	&ShowNotifications;
}

sub ShowNotifications {
	if($iamguest) { &fatal_error("$maintxt{'138'}"); }

	my(@dirdata,@datdata,$filename,$entry,@entries,$mnum,$dummy,$msub,$mname,$memail,$mdate,$musername,$micon,$mattach,$mip,$mmessage,@messages,@found_number,@found_subject,@found_date,@found_username);

	# Read all .mail-Files and search for username
	opendir (DIRECTORY,"$datadir");
	@dirdata = readdir(DIRECTORY);
	closedir (DIRECTORY);
	@datdata = grep(/mail/,@dirdata);


	# Read all .mail-Files and search for username
	# This time, in the Boards Dir
	opendir (DIRECTORY,"$boardsdir");
	@dirboard = readdir(DIRECTORY);
	closedir (DIRECTORY);
	@boardnotify = grep(/mail/,@dirboard);


	foreach $boardfile (@boardnotify) {
		fopen(BOARDNOTIFY, "$boardsdir/$boardfile");
			@bentries = <BOARDNOTIFY>;
		fclose(BOARDNOTIFY);

	    foreach $bentry (@bentries) {
	        $bentry =~ s/[\n\r]//g;
			($curuser,$curmail,$curlang,$boardnotifytype,$hasviewed) = split (/\|/, $bentry);
			if ($curuser eq $username) {
				($myboard, $dummy) = split(/\./,$boardfile);
				push(@found_board,$myboard);
				push(@found_notify_type,$boardnotifytype);
			}
		}
	}


# Display Board notifications
$yymain .= qq~
<form action="$scripturl?action=boardnotify3" method="post">
<table border="0" width="100%" cellspacing="1" cellpadding="6" class="bordercolor">
 <tr>
  <td align="left" class="titlebg">
   <span class="text1"><b>Board $maintxt{'418'}</b></span>
  </td>
 </tr><tr>
  <td align="left" class="windowbg">
   
    <br />
~;

$i = 0;
foreach $item (@found_board) {

if ($found_notify_type[$i] == 1) {
	$selected1 = qq~ selected="selected"~;
} else {
	$selected2 = qq~ selected="selected"~;
}

$yymain .= qq~<a href="$scripturl?action=boardnotify4;board=$item">Remove</a>&nbsp;
<select name="board-$item">
	<option value="1"$selected1>New Threads Only</option>
	<option value="2"$selected2>All New Posts</option>
</select>
 in the board: <a href="$scripturl?board=$item">$item</a>
<br />
<br />~;

$i++;
}



$yymain .= qq~
</td>
</tr>
<tr>
<td align="left" class="windowbg">
<input type="submit" value="$maintxt{'417'}" />
</td>
</tr>
</table>
</form>
<br />
~;

	# Load Censor List
	&LoadCensorList;
	
	foreach $filename (@datdata) {
		fopen(NOTIFY, "$datadir/$filename");
		@entries = <NOTIFY>;
		fclose(NOTIFY);
	        foreach $entry (@entries) {
	        	$entry =~ s/[\n\r]//g;
				($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $entry);
	        	if ($curuser eq $username) {
				if ($isboardnotify) { next };
				($mnum, $dummy) = split(/\./,$filename);
				fopen(FILE, "$datadir/$mnum.txt");
				@messages = <FILE>;
				fclose(FILE);
				($msub, $mname, $memail, $mdate, $musername, $micon, $mattach, $mip,  $mmessage) = split(/\|/,$messages[0]);
				&ToChars($msub);
				push(@found_number,$mnum);
				push(@found_subject,$msub);
				push(@found_date,$mdate);
				push(@found_username,$musername);
				push(@found_name,$mname);
			}
		}
	}

	# Display all Entries
	$yymain .= qq~
<table border="0" width="100%" cellspacing="1" cellpadding="6" class="bordercolor">
 <tr>
  <td align="left" class="titlebg">
   <span class="text1"><b>$maintxt{'418'}</b></span>
  </td>
 </tr><tr>
  <td align="left" class="windowbg">
   
    <br />
~;


	if (@found_number==0) {
		$yymain .= "$maintxt{'414'}<br /><br />&nbsp;";
	} else {
		$found_subject[$counter] = &Censor($found_subject[$counter]);
		$yymain .= qq~<form action="$scripturl?action=notify4" method="post">
<table align="left">
  <tr>
      <td align="left" colspan="2" class="windowbg">$maintxt{'415'}:<br />&nbsp;</td></tr>
~;
		$counter=0;
		foreach $entry (@found_number) {

			&LoadUser($found_username[$counter]);
			if(${$uid.$found_username[$counter]}{'realname'}) {
				$username_link = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$found_username[$counter]}">${$uid.$found_username[$counter]}{'realname'}</a>~;
			} elsif($found_name[$counter]) {
				$username_link = $found_name[$counter];
			} else {
				$username_link = $found_username[$counter];				
			}

			$yymain .= "<tr><td align=\"left\">";
			$yymain .= qq~<input type="checkbox" name="thread-$found_number[$counter]" value="1" /></td>~;
			$yymain .= qq~<td align="left"><b><a href="$scripturl?num=$found_number[$counter]">$found_subject[$counter]</a></b> $maintxt{'525'} $username_link</td></tr>\n~;
			$counter++;
		}
		$yymain .= "<tr><td colspan=\"2\"><br /><span class=\"windowbg\">$maintxt{'416'}</span><br />&nbsp;</td></tr>\n";
		$yymain .= qq~<tr><td>&nbsp;</td><td><input type="reset" value="$maintxt{'278'}" />&nbsp;&nbsp;&nbsp;<input type="submit" value="$maintxt{'417'}" /></td></tr>~;
		$yymain .= "</table></form><br />&nbsp;\n";
	}

	$yymain .= qq~
  </td>
 </tr>
</table>
~;
	$yytitle = "$maintxt{'417'}";
	&template;
	exit;
}

sub remove_notifications {
	my (@deademails) = @_;
	my (@maildir, $filename, @newlist, $line, $deadmail, $curuser, $curlang, $curmail);

	opendir (DIRECTORY,"$datadir");
	@maildir = grep {/\.mail$/} readdir(DIRECTORY);
	closedir (DIRECTORY);

	foreach $filename (@maildir) {
		fopen(NOTIFY, "+<$datadir/$filename") || &fatal_error("$maintxt{'23'} $filename", 1);
		seek(NOTIFY,0,0);
		my @notifications = <NOTIFY>;
		foreach $line (@notifications){
			($curuser,$curmail,$curlang,$isboardnotify,$hasviewed) = split (/\|/, $line);
	        	$line =~ s/[\n\r]//g;
			foreach $deadmail(@deademails) { 
				$deadmail =~ s/[\n\r]//g; 
					if (lc($curmail) ne lc($deadmail)){push (@newlist, "$line\n");}
			}
		}
		if ($#newlist > 0) {
			truncate(NOTIFY,0);
			seek(NOTIFY,0,0);
			print NOTIFY @newlist;
			fclose(NOTIFY);
			$done .= "$filename\n";
		}
		else {
			fclose(NOTIFY);
			unlink("$datadir/$filename");
		}
	}
}

sub replace_notifications {
	my ($user) = $_[0];
	my (@maildir, $filename, $curuser, $curlang, $curmail, $found);

	opendir (DIRECTORY,"$datadir");
	@maildir = grep {/\.mail$/} readdir(DIRECTORY);
	closedir (DIRECTORY);

	foreach $filename (@maildir) {
		$found = 0;
		fopen(NOTIFY, "+<$datadir/$filename") || &fatal_error("$maintxt{'23'} $filename", 1);
		seek(NOTIFY,0,0);
		my @notifications = <NOTIFY>;
		truncate(NOTIFY,0);
		seek(NOTIFY,0,0);
		foreach $line (@notifications){
			($curuser,$curmail,$curlang) = split (/\|/, $line,3);
	        	$line =~ s/[\n\r]//g;
			if ($user eq $curuser){
				$found = 1;
				&LoadUser($user);
				print NOTIFY "$curuser|${$uid.$user}{'email'}|${$uid.$user}{'language'}\n";
			} else {
				print NOTIFY "$line\n";
			}
		}
		fclose(NOTIFY);
	}
}

1;
