###############################################################################
# Notify.pl                                                                   #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2.2                                                  #
# Packaged:       June 5, 2008                                                #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2008 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.2.2 $Revision: 1.17.2.7 $';
if ($action eq 'detailedversion') { return 1; }

&LoadLanguage('Notify');

sub ManageBoardNotify {
	my $todo     = $_[0];
	my $theboard = $_[1];
	my $user     = $_[2];
	my $userlang = $_[3];
	my $notetype = $_[4];
	my $noteview = $_[5];
	if ($todo eq "load" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {
		## open board mail file and build hash name / detail
		if (-e "$boardsdir/$theboard.mail") {
			fopen(BOARDNOTE, "$boardsdir/$theboard.mail");
			%theboard = map /(.*)\t(.*)/, <BOARDNOTE>;
			fclose(BOARDNOTE);
		}
	}
	if ($todo eq "add") {
		$theboard{$user} = "$userlang|$notetype|$noteview";
	}
	if ($todo eq "update") {
		if (exists $theboard{$user}) {
			my ($memlang, $memtype, $memview) = split(/\|/, $theboard{$user});
			if ($userlang) { $memlang = qq~$userlang~; }
			if ($notetype) { $memtype = qq~$notetype~; }
			if ($noteview) { $memview = $noteview; }
			$theboard{$user} = "$memlang|$memtype|$memview";
		}
	}
	if ($todo eq "delete") {
		if ($user =~ /,/)	{	# been sent a list to kill, not a single
			my @oldusers = split(',', $user);
			foreach my $user (@oldusers)	{
				if (exists $theboard{$user}) {
					delete($theboard{$user});
				}
			}
		}	
		else	{	
		if (exists $theboard{$user}) {
			delete($theboard{$user});
			}
		}
	}
	if ($todo eq "save" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {
		fopen(BOARDNOTE, ">$boardsdir/$theboard.mail");
		print BOARDNOTE map "$_\t$theboard{$_}\n", sort { $theboard{$a} cmp $theboard{$b} } keys %theboard;
		fclose(BOARDNOTE);
		undef %theboard;
		if (!-s "$boardsdir/$theboard.mail") { unlink("$boardsdir/$theboard.mail"); }
	}
}

sub BoardNotify {
	if (!$currentboard) { &fatal_error("no_access"); }
	if ($iamguest)      { &fatal_error("members_only"); }
	my ($curuser, $curlang, $notifytype);
	$selected1 = "";
	$selected2 = "";
	$deloption = "";
	my ($boardname, undef) = split(/\|/, $board{"$currentboard"}, 2);
	&ToChars($boardname);
	&ManageBoardNotify("load", $currentboard);
	$yymain .= qq~
	<form action="$scripturl?action=boardnotify3;board=$currentboard" method="post">
	<table border="0" width="600" cellspacing="1" cellpadding="4" align="center" class="bordercolor">
		<tr>
		<td colspan="2" align="left" class="titlebg">
		<img src="$imagesdir/notify.gif" alt="" /> <span class="text1"><b>$notify_txt{'136'} - $boardname</b></span>
		</td>
		</tr><tr>
		<td class="windowbg" width="70%" align="left" valign="middle"><br />
	~;

	if (exists $theboard{$username}) {
		($memlang, $memtype, $memview) = split(/\|/, $theboard{$username});
		${ selected . $memtype } = qq~ selected="selected"~;
		$deloption = qq~<option value="3">$notify_txt{'134'}</option>~;
		$yymain .= qq~$notify_txt{'137'} &nbsp;~;
	} else {
		$yymain .= qq~$notify_txt{'126'} &nbsp;~;
	}
	$yymain .= qq~
		<br /><br />
		</td><td class="windowbg" width="30%" align="center" valign="middle">
		<select name="$currentboard">
		<option value="1"$selected1>$notify_txt{'132'}</option>
		<option value="2"$selected2>$notify_txt{'133'}</option>
		$deloption
		</select>
		</td></tr>
		<tr>
		<td colspan="2" class="catbg" align="center">
		<input type="submit" value="$notify_txt{'124'}" class="button" />
		</td>
		</tr>
	</table>
	</form>
	~;
	undef %theboard;
	$yytitle = "$notify_txt{'125'}";
	&template;
	exit;
}

sub BoardNotify2 {
	if ($iamguest) { &fatal_error("members_only"); }
	foreach $variable (keys %FORM) {
		if ($variable eq 'formsession') { next; }
		$notify_type = $FORM{"$variable"};
		if ($notify_type == 1 || $notify_type == 2) {
			&ManageBoardNotify("add", $variable, $username, ${$uid.$username}{'language'}, $notify_type, "1");
		} elsif ($notify_type == 3) {
			&ManageBoardNotify("delete", $variable, $username);
		}
	}
	if ($action eq "boardnotify3") {
		$yySetLocation = qq~$scripturl?board=$INFO{'board'}~;
	} else {
		$yySetLocation = qq~$scripturl?action=shownotify~;
	}
	&redirectexit;
}

sub ManageThreadNotify {
	my $todo      = $_[0];
	my $thethread = $_[1];
	my $user      = $_[2];
	my $userlang  = $_[3];
	my $notetype  = $_[4];
	my $noteview  = $_[5];

	if ($todo eq "load" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {
		##  open mail file and build hash 
		if (-e "$datadir/$thethread.mail") {
			fopen(THREADNOTE, "$datadir/$thethread.mail");
			%thethread = map /(.*)\t(.*)/, <THREADNOTE>;
			fclose(THREADNOTE);
		}
	}
	if ($todo eq "add") {
		$thethread{$user} = "$userlang|$notetype|$noteview";
	}
	if ($todo eq "update") {
		if (exists $thethread{$user}) {
			($memlang, $memtype, $memview) = split(/\|/, $thethread{$user});
			if ($userlang) { $memlang = qq~$userlang~; }
			if ($notetype) { $memtype = qq~$notetype~; }
			if ($noteview) { $memview = $noteview; }
			$thethread{$user} = "$memlang|$memtype|$memview";
		}
	}
	if ($todo eq "delete") {
		if ($user =~ /,/)	{	# been sent a list to kill, not a single
			my @oldusers = split(',', $user);
			foreach my $user (@oldusers)	{
				if (exists $thethread{$user}) {
					delete($thethread{$user});
				}
			}
		}
		else	{
			if (exists $thethread{$user}) {
				delete($thethread{$user});
			}
		}
	}
	if ($todo eq "save" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {
		fopen(THREADNOTE, ">$datadir/$thethread.mail");
		print THREADNOTE map "$_\t$thethread{$_}\n", sort { $thethread{$a} cmp $thethread{$b} } keys %thethread;
		fclose(THREADNOTE);
		undef %thethread;
		if (!-s "$datadir/$thethread.mail") { unlink("$datadir/$thethread.mail"); }
	}
}

sub Notify {
	if ($iamguest) { &fatal_error("members_only"); }
	my ($thread, $line, $start, $curuser, $curlang);
	if ($INFO{'thread'} =~ m~/~) {
		($thread, $start) = split('/', $INFO{'thread'});
	} else {
		$thread = $INFO{'thread'};
		$start  = $INFO{'start'};
	}
	&ManageThreadNotify("load", "$thread");
	$yymain .= qq~
	<table border="0" width="600" cellspacing="1" cellpadding="4" align="center" class="bordercolor">
		<tr>
		<td align="left" class="titlebg">
		<img src="$imagesdir/notify.gif" alt="" /> <span class="text1"><b>$notify_txt{'118'}</b></span>
		</td>
		</tr><tr>
		<td class="windowbg" align="center"><br />
	~;
	if (exists $thethread{$username}) {
		$yymain .= qq~$notify_txt{'117'}<br /><br /><b><a href="$scripturl?action=notify3;thread=$thread/$start" style="font-weight: bold;">$notify_txt{'115'}</a> - <a href="$scripturl?num=$thread/$start" style="font-weight: bold;">$notify_txt{'116'}</a></b>~;
	} else {
		$yymain .= qq~$maintxt{'126'}<br /><br /><b><a href="$scripturl?action=notify2;thread=$thread/$start" style="font-weight: bold;">$notify_txt{'115'}</a> - <a href="$scripturl?num=$thread/$start" style="font-weight: bold;">$notify_txt{'116'}</a></b>~;
	}
	$yymain .= qq~
		</td>
		</tr>
	</table>
	~;
	undef %thethread;
	$yytitle = "$notify_txt{'125'}";
	&template;
	exit;
}

sub Notify2 {
	if ($iamguest) { &fatal_error("members_only"); }
	my ($thread, $start);
	if ($INFO{'thread'} =~ m~/~) {
		($thread, $start) = split('/', $INFO{'thread'});
	} else {
		$thread = $INFO{'thread'};
		$start  = $INFO{'start'};
	}
	&ManageThreadNotify("add", $thread, $username, ${$uid.$username}{'language'}, "1", "1");
	$yySetLocation = qq~$scripturl?num=$thread/$start~;
	&redirectexit;
}

sub Notify3 {
	if ($iamguest) { &fatal_error("members_only"); }
	my ($thread, $start);
	if ($INFO{'thread'} =~ m~/~) {
		($thread, $start) = split('/', $INFO{'thread'});
	} else {
		$thread = $INFO{'thread'};
		$start  = $INFO{'start'};
	}
	if (-e "$datadir/$thread.mail") {
		&ManageThreadNotify("delete", $thread, $username);
	}
	$yySetLocation = qq~$scripturl?num=$thread/$start~;
	&redirectexit;
}

sub Notify4 {
	if ($iamguest) { &fatal_error("members_only"); }
	my ($variable, $notype, $threadno);
	foreach $variable (keys %FORM) {
		($notype, $threadno) = split(/-/, $variable);
		if ($notype eq "thread") {
			&ManageThreadNotify("delete", $threadno, $username);
		}
	}
	$action = 'shownotify';
	&ShowNotifications;
}

sub updateLanguage {
	my $user    = $_[0];
	my $newlang = $_[1];
	my ($threadfile, $boardfile);
	foreach $boardfile (@bmaildir) {
		($myboard, undef) = split(/\./, $boardfile);
		&ManageBoardNotify("update", $myboard, $user, $newlang, "", "");
	}
	foreach $threadfile (@tmaildir) {
		($mythread, undef) = split(/\./, $threadfile);
		&ManageThreadNotify("update", $mythread, $user, $newlang, "", "");
	}
}

sub removeNotifications {
	my $user = $_[0];
	my ($boardfile, $threadfile);
	foreach $boardfile (@bmaildir) {
		($myboard, undef) = split(/\./, $boardfile);
		&ManageBoardNotify("delete", $myboard, $user);
	}
	foreach $threadfile (@tmaildir) {
		($mythread, undef) = split(/\./, $threadfile);
		&ManageThreadNotify("delete", $mythread, $user);
	}
}


sub ShowNotifications {
	  ## bye bye guest....
	  if ($iamguest) { &fatal_error("members_only"); }

	  $yynavigation = qq~&rsaquo; <a href="$scripturl?action=mycenter" class="nav">$img_txt{'mycenter'}</a> &rsaquo; $img_txt{'418'}~;

	  # Show Javascript for 'check all' notifications
	  $showNotifications .= qq~
<script language="Javascript1.2" type="text/javascript">
	  <!--
		    function checkAll(j) {
				for (var i = 0; i < document.threadnotify.elements.length; i++) {
					  if (j == 0 ) {document.threadnotify.elements[i].checked = true;}
				}
		    }
		    function uncheckAll(j) {
				for (var i = 0; i < document.threadnotify.elements.length; i++) {
					  if (j == 0 ) {document.threadnotify.elements[i].checked = false;}
				}
		    }
	  //-->
</script>

	  <form action="$scripturl?action=boardnotify2" method="post" name="boardnotify">
	  <table border="0" width="100%" align="center" cellspacing="1" cellpadding="4" class="bordercolor">
		    <tr><td colspan="2" align="left" class="titlebg">
		    <img src="$imagesdir/notify.gif" alt="" /> <span class="text1"><b>$notify_txt{'136'}</b></span>
		    </td></tr>
	  ~;

	  ($board_notify,$thread_notify) = &NotificationAlert;
	  my ($num,$new);
	  # Board notifications
	  foreach (keys %$board_notify) { # boardname, boardnotifytype , new
		     $num++;

		     my ($selected1, $selected2);
		     if (${$$board_notify{$_}}[1] == 1) { # new topics
				 $selected1 = qq~ selected="selected"~;
		     } else { # all new posts
				 $selected2 = qq~ selected="selected"~;
		     }

		     if (${$$board_notify{$_}}[2]) {
			   $new = qq~<img src="$imagesdir/on.gif" alt="$notify_txt{'333'}" border="0" style="vertical-align: middle;" />~;
		     } else {
			   $new = qq~<img src="$imagesdir/off.gif" alt="$notify_txt{'334'}" border="0" style="vertical-align: middle;" />~;
		     }

		     ## output notify detail - option 3 = remove notify
		     $boardblock .= qq~
		     <tr><td align="left" width="65%" class="windowbg">
		     $new <a href="$scripturl?board=$_">${$$board_notify{$_}}[0]</a>
		     </td><td align="center" width="35%" class="windowbg">
		     <select name="$_">
				 <option value="1"$selected1>$notify_txt{'132'}</option>
				 <option value="2"$selected2>$notify_txt{'133'}</option>
				 <option value="3">$notify_txt{'134'}</option>
		     </select>
		     </td></tr>
		     ~;
	  }

	  if (!$num) { # no board notifies up
		    $showNotifications .= qq~
		    <tr><td colspan="2" align="left" class="windowbg2">
		    <br />
		    $notify_txt{'139'}<br /><br />
		    </td></tr>
		    ~;
	  } else { # list boards
		    $showNotifications .= qq~
		    <tr><td align="left" class="catbg">
		    <b>$notify_txt{'135'}</b>
		    </td><td align="center" class="catbg">
		    <b>$notify_txt{'138'}</b>
		    </td></tr>
		    $boardblock
		    <tr><td colspan="2" align="center" class="windowbg">
		    <input type="submit" value="$notify_txt{'124'}" class="button" />&nbsp; <input type="reset" value="$notify_txt{'121'}" class="button" />
		    </td></tr>
		    ~;
	  }

	  $showNotifications .= qq~
	  </table>
	  </form>
	  <br /><br />

	  <form action="$scripturl?action=notify4" method="post" name="threadnotify">
	  <table border="0" width="100%" align="center" cellspacing="1" cellpadding="4" class="bordercolor">
	  <tr><td align="left" colspan="2" class="titlebg">
		    <img src="$imagesdir/notify.gif" alt="" /> <span class="text1"><b>$notify_txt{'118'}</b></span>
	  </td></tr>
	  ~;

	  $num = 0;
	  foreach (keys %$thread_notify) { # mythread, msub, new, username_link, catname_link, boardname_link, lastpostdate
		     $num++;

		     ## build block for display
		     $threadblock .= qq~
		     <tr><td align="left" width="85%" class="windowbg2">
				 <b><a href="$scripturl?num=${$$thread_notify{$_}}[0]/new">${$$thread_notify{$_}}[2] ${$$thread_notify{$_}}[1]</a></b> $notify_txt{'120'} ${$$thread_notify{$_}}[3]
				 <br /><span class="small">${$$thread_notify{$_}}[4] &raquo; ${$$thread_notify{$_}}[5] - $notify_txt{'lastpost'} ${$$thread_notify{$_}}[6]</span>
		     </td><td align="center" width="15%" class="windowbg2">
				 <input type="checkbox" name="thread-${$$thread_notify{$_}}[0]" value="1" />
		     </td></tr>
		     ~;
	  }

	  if (!$num) { ## no threads listed
		    $showNotifications .= qq~
		    <tr><td colspan="2" align="left" class="windowbg2">
		    <br />
		    $notify_txt{'119'}<br /><br />
		    </td></tr>
		    ~;
	  } else { ## output details
		    $showNotifications .= qq~
		    <tr><td align="left" class="catbg">
		    <b>$notify_txt{'140'}</b>
		    </td><td align="center" class="catbg">
		    <b>$notify_txt{'134'}</b>
		    </td></tr>
		    $threadblock
		    <tr><td align="right" width="85%" class="catbg"><span class="small">$notify_txt{'144'}</span></td>
		    <td align="center" width="15%" class="catbg"><input type="checkbox" name="checkall" value="" onclick="if (this.checked) checkAll(0); else uncheckAll(0);" /></td>
		    <tr><td colspan="2" align="center" class="windowbg">
		    <input type="submit" value="$notify_txt{'124'}" class="button" />&nbsp; <input type="reset" value="$notify_txt{'121'}" class="button" />
		    </td></tr>
		    ~;
	  }
	  $showNotifications .= qq~
	  </table>
	  </form>
	  ~;

	  $yytitle = "$notify_txt{'124'}";

	  ## and finally, add jump menu for a route back.
	  if (!$view) {
		&jumpto;
		$yymain .= qq~$showNotifications$selecthtml~;
		&template;
		exit;
	  }
}

sub NotificationAlert {
	  my ($myboard, %board_notify, $mythread, %thread_notify);

	  ## pull list of board and post .mail files
	  &getMailFiles; # sub in Subs.pl, output @bmaildir and @tmaildir

	  # needed for $new - icon (on/off/new.gif)
	  &BoardTotals("load"); # sub in System.pl, for ${$uid.$myboard}{'lastposttime'}
	  &getlog(1);	     # sub in Subs.pl, for $yyuserlog{$myboard}

	  ## run through boards list
	  foreach (@bmaildir) {
		    ## board name from file name
		    $myboard = (split(/\./, $_))[0];

		    ## load in hash of name / detail for board
		    &ManageBoardNotify("load", "$myboard");

		    if (exists $theboard{$username}) {
			  ## grab board name
			  my $boardname = (split(/\|/, $board{"$myboard"}))[0];

			  $board_notify{"$myboard"} = [ $boardname,
								  (split(/\|/, $theboard{$username}))[1], # boardnotifytype
								  ($max_log_days_old && int(${$uid.$myboard}{'lastposttime'} && ($yyuserlog{$myboard} < int(${$uid.$myboard}{'lastposttime'}) || $yyuserlog{$myboard} < $date - ($max_log_days_old * 86400))) ? 1 : 0) # new == 1
								 ];

			  undef %theboard;
		    }
	  }

	  &LoadCensorList;

	  ##  load board names
	  unless ($mloaded == 1) { require "$boardsdir/forum.master"; } # for $board{...}

	  foreach $threadfile (@tmaildir) { # threads next
		    $mythread = (split(/\./, $threadfile))[0]; # number of the thread

		    ## load threads hash
		    &ManageThreadNotify("load", "$mythread");

		    if (exists $thethread{$username}) {
			  ## load ctb file for board data
			  &MessageTotals ("load", $mythread);

			  ## pull out board and last post
			  my $boardid = ${$mythread}{'board'};
			  my ($msub,$new,$username_link,$catname_link,$boardname_link,$lastpostdate);
			  if ($action eq 'shownotify') {
				if (!${${$boardid.$mythread}}[0]) {
				    my ($mid,$msubject,$mname,$musername);
				    fopen(BOARDTXT, "$boardsdir/$boardid.txt") || &fatal_error("cannot_open","$boardsdir/$boardid.txt", 1);
				    foreach (<BOARDTXT>) {
						 ($messageid, $messagesubject, $mname, undef, undef, undef, $musername, undef, undef) = split(/\|/, $_);
						 ${$boardid.$messageid} = [$messagesubject,$mname,$musername];
				    }
				    fclose(BOARDTXT);
				}
				$msub = ${${$boardid.$mythread}}[0];
				$mname = ${${$boardid.$mythread}}[1];
				$musername = ${${$boardid.$mythread}}[2];

				&ToChars($msub);
				$msub =~ s/\[m.*?\]/$maintxt{'758'}/;
				$msub = &Censor($msub);  # censor subject text !

				## run through the categories until we hit the match for category name
				my ($catname,$thiscatid,$catid);
				my $boardname = (split(/\|/, $board{$boardid}))[0]; # grab boardname from list
				checkboardname: foreach $catid (@categoryorder) {
								 foreach (split(/\,/, $cat{$catid})) {
									    ## find the match, grab data and jump out
									    if ($_ eq $boardid) {
										  $catname = (split(/\|/, $catinfo{$catid}))[0];
										  $thiscatid = $catid;
										  last checkboardname;
									    }
								 }
				}
				$catname_link = qq~<a href="$scripturl?catselect=$thiscatid">$catname</a>~;
				$boardname_link = qq~<a href="$scripturl?board=$boardid">$boardname</a>~;

				## build view profile link, if real name exists
				&LoadUser($musername); # load poster
				if (${$uid.$musername}{'realname'}) {
				    $username_link = qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$musername}">${$uid.$musername}{'realname'}</a>~;
				} elsif ($mname) {
				    $username_link = $mname;
				} else {
				    $username_link = $musername;
				}

				## format last post for output
				$lastpostdate = &timeformat(${$mythread}{'lastpostdate'});
			  }

			  if ($max_log_days_old) {
				# Decide if thread should have the "NEW" indicator next to it.
				# Do this by reading the user's log for last read time on thread,
				# and compare to the last post time on the thread.
				my $dlp  = int($yyuserlog{$mythread});
				my $dlpb = int($yyuserlog{"$boardid--mark"});
				$dlp  = $dlp > $dlpb ? $dlp : $dlpb;
				if ($yyuserlog{"$mythread--unread"} || $dlp < ${$mythread}{'lastpostdate'} || $dlp < $date - ($max_log_days_old * 86400)) {
				    $new = qq~<img src="$imagesdir/new.gif" alt="$notify_txt{'335'}" border="0"/>~;
				}
			  }

			  $thread_notify{"$mythread"} = [$mythread, $msub, $new, $username_link, $catname_link, $boardname_link, $lastpostdate];
		    }
	  }
	  (\%board_notify,\%thread_notify);
}

1;
