# FILE: fcn-msdl.pl
# DESCRIPTION: Message Management (Delete Message)
#-------------------------------------------------------------------------------
# DISCUS COPYRIGHT NOTICE
#
# Discus is copyright (c) 2002 by DiscusWare, LLC, all rights reserved.
# The use of Discus is governed by the Discus License Agreement which is
# available from the Discus WWW site at:
#    http://www.discusware.com/discus/license
#
# Pursuant to the Discus License Agreement, this copyright notice may not be
# removed or altered in any way.
#-------------------------------------------------------------------------------

use strict;
use vars qw($GLOBAL_OPTIONS $DCONF $PARAMS);

###
### remove_message
###
### Removes messages from a page.
###

sub remove_message {
	my ($arg, $tree_file_in, $cat_array, $file_in) = @_;
	my $p = {};
	$p->{lock} = 1;
	$p->{no_error} = 1 if $PARAMS->{no_exit} == 1;
	my $file = defined $file_in ? $file_in : GetPage($arg->{topic}, $arg->{page}, $p);
	return undef if $file->{head}->{topic_number} != $arg->{topic};
	my $_mr = 0; my @_ag = (); my @_nm = (); my @_nn = (); my @_nnt = ();
	foreach my $msgref (@{ $file->{messages} }) {
		if ($arg->{td}->{"*"} || $arg->{td}->{$msgref->{number}}) {
			$_mr += 1;
			my $text = $msgref->{text};
			if (! $arg->{no_delete_attachments} ) {
				push @_ag, map { $_->{filename} } @{attachment_scan($text)};
			}
			push @_nn, $msgref;
			push @_nnt, $msgref->{number};
		} else {
			push @_nm, $msgref;
		}
	}
	$file->{messages} = \@_nm;
	$file->{general}->{subtopic_raw} = 1;
	$file->{general}->{messages_raw} = 0;
	SetPage($file, { unlock => 1 }) if ! defined $file_in;
	dreq("fcn-tree");
	my $tree = defined $tree_file_in ? $tree_file_in : read_tree($arg->{topic}, { no_unlock => 1 });
	($tree, $cat_array) = tree_remove_message($tree, $cat_array, [ {page => $arg->{page}, messages => join(",", @_nnt)} ]);
	if (! defined $tree_file_in) {
		write_tree($arg->{topic}, $tree, { no_lock => 1 });
		topic_tree_to_main($tree);
	}
	my $dirname = (-e "$DCONF->{message_dir}/$arg->{topic}" ? "$DCONF->{message_dir}/$arg->{topic}" : "$DCONF->{secdir}/$arg->{topic}");
	foreach my $u (@_ag) {
		unlink "$dirname/$u";
	}
	if (! defined $arg->{no_log_action}) {
		dreq("fcn-logs");
		if ($DCONF->{pro} && $GLOBAL_OPTIONS->{database} == 1) {
			my $dbh = db_connect();
			delete_entry ({ files_already_locked => $arg->{files_already_locked}, database => "log", dbh => $dbh, messages => $arg->{td} });
			delete_entry ({ files_already_locked => $arg->{files_already_locked}, database => "search", dbh => $dbh, messages => $arg->{td} });
		} else {
			delete_entry ({ files_already_locked => $arg->{files_already_locked}, messages => $arg->{td}, topic => $arg->{topic} });
		}
	}
	if (! defined $arg->{no_page_update}) {
		pages_upward_update($tree, $cat_array, [ $arg->{page} ], undef );
		dreq("topic-pg"); regenerate_topic_page();
	}
	return {
		tree => $tree,
		cat_array => $cat_array,
		oldfile => $file,
	};
}



1;
