#!/usr/local/bin/perl
# mailq_search.cgi
# Display some messages from the mail queue

require './postfix-lib.pl';
require './boxes-lib.pl';
&ReadParse();
$access{'mailq'} || &error($text{'mailq_ecannot'});
&ui_print_header(undef, $text{'searchq_title'}, "");

# Get all of the queued messages that this user can see
open(MAILQ, "$config{'mailq_cmd'} 2>/dev/null |");
while(<MAILQ>) {
	next if (/^(\S+)\s+is\s+empty/i || /^\s+Total\s+requests:/i);
	if (/^([^\s\*]+)\*?\s*(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+)\s+(.*)/) {
		push(@qfiles, { 'id' => $1,
			        'size' => $2,
				'date' => $3,
				'from' => $4 });
		}
	elsif (/\((.*)\)/ && @qfiles) {
		$qfiles[$#qfiles]->{'status'} = $1;
		}
	elsif (/^\s+(\S+)/ && @qfiles) {
		$qfiles[$#qfiles]->{'to'} .= "$1 ";
		}
	}
close(MAILQ);

# Do the search
$neg = ($in{'field'} =~ s/^!//);
@qfiles = grep { my $r = &compare_field($_);
		 $neg ? !$r : $r } @qfiles;

print "<p><b>",&text($in{'field'} =~ /^\!/ ? 'search_results3' :
	  'search_results2', scalar(@qfiles), "<tt>$in{'match'}</tt>"),"</b><p>\n";
if (@qfiles) {
	# Show matching messages
	print "<form action=delete_queues.cgi>\n";
	print &select_all_link("file", 0, $text{'mailq_all'}),"&nbsp;\n";
	print &select_invert_link("file", 0, $text{'mailq_invert'}),"<br>\n";
	print "<table border width=100%>\n";
	print "<tr $tb> <td><br></td> <td><b>$text{'mailq_id'}</b></td> ",
	      "<td><b>$text{'mailq_date'}</b></td> ",
	      "<td><b>$text{'mailq_from'}</b></td> ",
	      "<td><b>$text{'mailq_to'}</b></td> ",
	      "<td><b>$text{'mailq_size'}</b></td> ",
	      "<td><b>$text{'mailq_status'}</b></td> </tr>\n";
	for($i=0; $i<@qfiles; $i++) {
		$q = $qfiles[$i];
		print "<tr $cb>\n";
		print "<td><input type=checkbox name=file value=$q->{'id'}></td>\n";
		print "<td><a href='view_mailq.cgi?id=$q->{'id'}'>$q->{'id'}</a></td>\n";
		local $size = $q->{'size'} > 1000000 ?
				int($q->{'size'} / 1000000)." MB" :
			      $q->{'size'} > 1000 ?
				int($q->{'size'} / 1000)." kB" :
				$q->{'size'}." b";
		print "<td><font size=1>$q->{'date'}</td>\n";
		print "<td><font size=1>",&html_escape($q->{'from'}),
		      "</font></td>\n";
		print "<td><font size=1>",&html_escape($q->{'to'}),
		      "</font></td>\n";
		print "<td><font size=1>$size</font></td>\n";
		print "<td><font size=1>",&html_escape($q->{'status'}),
		      "</font></td>\n";
		print "</tr>\n";
		}
	print "</table>\n";
	print &select_all_link("file", 0, $text{'mailq_all'}),"&nbsp;\n";
	print &select_invert_link("file", 0, $text{'mailq_invert'}),"<p>\n";
	print "<input type=submit value='$text{'mailq_delete'}'><p>\n";
	print "</form>\n";
	}
else {
	print "<b>$text{'searchq_none'}</b> <p>\n";
	}

&ui_print_footer("list_mailq.cgi", $text{'mailq_return'},
	"", $text{'index_return'});

sub compare_field
{
if ($in{'field'} eq 'size') {
	return $_[0]->{$in{'field'}} > $in{'match'};
	}
else {
	return $_[0]->{$in{'field'}} =~ /\Q$in{'match'}\E/i;
	}
}

