######################################################################
#
#  EPrint Editor
#
#   Allows staff to remove EPrints or transfer them back to the
#   submission buffer.
#
######################################################################
#
#  This file is part of GNU EPrints 2.
#  
#  Copyright (c) 2000-2004 University of Southampton, UK. SO17 1BJ.
#  
#  EPrints 2 is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  EPrints 2 is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with EPrints 2; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
######################################################################

use EPrints;

use strict;

#cjg check item is editable by this user.

#cjg remove does not work

my $session = EPrints::Session->new();

# Check we have privs
if( !$session->auth_check( "editor" ) )
{
	$session->terminate();
	exit( 0 );
}

my( $title, $page ) = &process( $session );

$session->terminate;



sub process
{
	my( $session ) = @_;

	my $eprintid = $session->param( "eprintid" );
	
	my $eprint = new EPrints::DataObj::EPrint( $session, $eprintid );

	if( !defined $eprint )
	{
		$session->render_error( $session->html_phrase(
			"cgi/users/edit_eprint:cant_find_it",
			id=>$session->make_text( $eprintid ) ) );
		return;
	}

	my $dataset = $eprint->get_dataset;

	my $can_edit = $session->current_user->can_edit( $eprint );

	unless( $can_edit )
	{
		$session->render_error( $session->html_phrase(
			"cgi/users/edit_eprint:cant_edit",
			id=>$session->make_text( $eprintid ) ) );
		return;
	}

	my $action = $session->get_action_button;

	if( !defined $action || $action eq "_cancel" || $action eq "stop" )
	{
		&view_page( $session, $eprint );
		return;
	}

	if( $action eq "_toinbox" )
	{
		# Bounce button pressed - get reason
		&bounce_form( $session, 0, $eprint );
		return;
	}

	if( $action eq "_remove" )
	{
		# Remove button pressed - get reason
		&bounce_form( $session, 1, $eprint );
		return;
	}

	if( $action eq "_send" )
	{
		# Actually do the bounce
		&bounce( $session, $eprint );
		return;
	}

	if( $action =~ m/^_to/ )
	{	
		# Status-change button pressed
		my $dsid = $eprint->get_dataset()->id();

		my $ok = 0;
		$ok = $eprint->move_to_archive if( $action eq "_toarchive" );
		$ok = $eprint->move_to_buffer if( $action eq "_tobuffer" );
		$ok = $eprint->move_to_inbox if( $action eq "_toinbox" );
		$ok = $eprint->move_to_deletion if( $action eq "_todeletion" );

		if( $ok )
		{
			my $msg = $session->html_phrase( "cgi/users/edit_eprint:status_change",
					status=>$session->html_phrase( "dataset_fieldopt_dataset_".$eprint->get_dataset()->id() ) );
			&view_page( $session, $eprint, $msg );
		}
		else
		{
			my $msg = $session->html_phrase(
				"cgi/users/edit_eprint:cant_move",
				id=>$session->make_text( $eprintid ) );
			&view_page( $session, $eprint, $msg, 1 );
		}

		
		return;
	}

	if( $action eq "_clone" || $action eq "_copy" )
	{
		my $target_ds_id = 'buffer';
		if( $session->get_repository->get_conf( "skip_buffer" ) )
		{
			$target_ds_id = 'archive';
		}
		my $target_ds = $session->get_repository->get_dataset( $target_ds_id );
		my $copy;
		if( $action eq "_clone" )
		{
			# with files, with link
			$copy = $eprint->clone( $target_ds, 1 );
		}
		else
		{
			# nofiles, no link
			$copy = $eprint->clone( $target_ds, 0, 1 );
		}
	
		if( defined $copy )
		{
			# Copied OK, redirect to buffer
			$session->redirect( 'edit_eprint?eprintid='.$copy->get_id.'&_action_edit=1' );
			return;
		}
		
		$session->render_error( $session->html_phrase(
			"cgi/users/edit_eprint:cant_clone",
			id=>$session->make_text( $eprintid ) ) );
		return;
	}

	if( $eprint->get_dataset->id eq "deletion" )
	{
		unless( $session->get_repository->get_conf( 'allow_edit_deleted' ) )
		{
			$session->render_error( $session->html_phrase(
				"cgi/users/edit_eprint:cant_edit_deleted" ) );
			return;
		}
	}


	#########################################################

	# OK, so we are (presumably) editing it then...
	my $dataview = $session->param( "dataview" );
	$dataview = "summary" if( $dataview ne "full" && $dataview ne "history" );
	my $redir_url =  "edit_eprint?eprintid=$eprintid&dataview=$dataview";


	my $subform = new EPrints::SubmissionForm(
		$session,
		$redir_url,
		1,
		$dataset,
		"edit_eprint" );

	my $stage = $session->param( "stage" );
	# If we are skipping the files stage then we have to work out what the
	# actual last stage is...
	my $laststage = $subform->last_edit_stage;

	my $ls = $session->get_repository->get_conf( "submission_stage_last_for_staff_edit" );
	$laststage = $ls if( defined $ls );

	if( defined $stage && $laststage eq $stage && defined $action && ($action eq "finished" || $action eq "next") )
	{
		my $redir = 1;
		if( $stage eq "meta" )
		{
			my @pages = $dataset->get_type_pages( $eprint->get_value( "type" ) );
			my $pageid = $session->param( "pageid" );
			$redir = 0;
			$redir = 1 if( $pageid eq pop @pages );
		}
		if( $redir )
		{
			# Intercept the verify page, that's what we were doing!
			$session->redirect( $redir_url );
			return;
		}
	}

	$subform->process();
	
	if( $dataset->id eq "archive" || $dataset->id eq "deletion" )
	{
		# If the eprint is in the main archive or deletion area
		# then we need to update its webpage. This will make editing
		# even slower, but editing the main db SHOULD be a rare thing
		# anyway.

		# get it from the DB again - it's probably changed.
		my $eprint = new EPrints::DataObj::EPrint( 
			$session, 
			$eprintid,
			$dataset );

		# update the static pages.
		$eprint->generate_static;
	}
	return;

}

# Show metadata & options:

sub view_page
{
	my( $session, $eprint, $msg, $is_error ) = @_;

	my $page = $session->make_doc_fragment();
	
	$page->appendChild( $eprint->render_citation );	

	if( defined $msg )
	{
		my $style = "border: solid 1px #0f0; background-color: #cfc; padding: 1em; margin-top: 1em";
		if( $is_error )
		{
			$style = "border: solid 1px #f00; background-color: #fcc; padding: 1em; margin-top: 1em";
		}
		my $div = $session->make_element( "div", style=>$style );
		$div->appendChild( $msg );
		$page->appendChild( $div );
	}

	my $table = $session->make_element( "table",
					style=>"margin-top: 1em;",
					border=>"0",
					cellpadding=>"3" );
	$page->appendChild( $table );

	$table->appendChild( $session->render_row(
		$session->html_phrase( "cgi/users/edit_eprint:description" ),
		$eprint->render_description ) );

	$table->appendChild( $session->render_row(
		$session->html_phrase( "cgi/users/edit_eprint:status" ),
		$session->html_phrase( "dataset_fieldopt_dataset_".$eprint->get_dataset()->id() ) ) );

	my $usersname;
	my $user = new EPrints::User( 
			$session,
 			$eprint->get_value( "userid" ) );
	if( defined $user )
	{
		$usersname = $session->make_element( "a", 
				href=>$session->get_repository->get_conf( "perl_url" )."/user?userid=".$user->get_value( "userid" ) );
		$usersname->appendChild( 
			$user->render_description() );
	}
	else
	{
		$usersname = $session->make_text( "?" );
	}
	$table->appendChild( $session->render_row(
		$session->html_phrase( "eprint_fieldname_userid" ),
		$usersname ) );


	$table->appendChild( $session->render_row(
		$session->html_phrase( "eprint_fieldname_datestamp" ),
		$eprint->render_value( "datestamp" ) ) );

	$table->appendChild( $session->render_row(
		$session->html_phrase( "eprint_fieldname_status_changed" ),
		$eprint->render_value( "status_changed" ) ) );

	$table->appendChild( $session->render_row(
		$session->html_phrase( "eprint_fieldname_lastmod" ),
		$eprint->render_value( "lastmod" ) ) );
	
		
	# Possible actions
	# inbox buffer archive deletion
	#   *     *       *       *      edit
	#   *     *                      remove - and send message to depositing user
	#         *                      move to inbox - and send message to user
	#   *             *              move to buffer  - "
	#         *               *      move to archive  - "
	#                 *              move to deletion  - "
	#                 *       *      clone(new version) to buffer
	#   *     *       *       *      copy(as template) to buffer

	# actions for this form begin with _ (except edit and
	# those passed to submission form)

	my $sb = $session->get_repository->get_conf( "skip_buffer" );	
	my @actions = ();
	my $dsid = $eprint->get_dataset->id;

	if( $dsid eq "inbox" )
	{
		if( defined $sb && $sb == 1 )
		{
			push @actions, "_toarchive";
		}
		else
		{
			push @actions, "_tobuffer";
		}
	}

	if( $dsid eq "buffer" )
	{
		if( defined $eprint->get_user() )
		{
			push @actions, "_toinbox";
		}
		push @actions, "_toarchive";
	}

	if( $dsid eq "archive" )
	{
		if( defined $sb && $sb == 1 )
		{
			push @actions, "_toinbox";
		}
		else
		{
			push @actions, "_tobuffer";
		}
		push @actions, "_todeletion";
	}

	if( $dsid eq "deletion" )
	{
		push @actions, "_toarchive";
	}

	if( $dsid eq "archive" || $dsid eq "deletion" )
	{
		push @actions, "_clone";
	}

	if( $dsid eq "inbox" || $dsid eq "buffer" )
	{
		push @actions, "_remove";
	}
	
	push @actions, "_copy";



	my $dataview = $session->param( "dataview" );
	$dataview = "summary" if( $dataview ne "full" && $dataview ne "history" );


	my @list = ();

	foreach( @actions )
	{
		my $url = "edit_eprint?eprintid=".$eprint->get_id."&dataview=".$dataview."&_action_".$_."=1";
		my $a = $session->render_link( $url );
		$a->appendChild( $session->html_phrase( "cgi/users/edit_eprint:action_".$_ ) );
		push @list , $a;
	}

	{
		my $url = "buffer";
		my $a = $session->render_link( $url );
		$a->appendChild( $session->html_phrase( "cgi/users/edit_eprint:view_buffer" ) );
		push @list , $a;
	}

	$table->appendChild( $session->render_row(
		$session->html_phrase( "cgi/users/edit_eprint:actions" ),
		render_links_list( $session, @list ) ) );

	unless( $dsid eq "deletion" && !$session->get_repository->get_conf( 'allow_edit_deleted' ) )
	{
		@list = ();

		my $subform = new EPrints::SubmissionForm( $session, '', 1, $eprint->get_dataset, "edit_eprint" );
		my @stages = $subform->get_stages;
		foreach my $stage ( @stages )
		{
			next if $stage eq "done";
			next if $stage eq "verify";
			next if $stage eq "return";
			if( $stage eq "meta" )
			{
				my @pages = $eprint->get_dataset->get_type_pages( $eprint->get_value("type") );
				foreach my $page ( @pages )
				{
					my $url = "edit_eprint?eprintid=".$eprint->get_id."&dataview=".$dataview."&_action_jump=1&stage=".$stage."&pageid=".$page;
					my $a = $session->render_link( $url );
					$a->appendChild( $session->html_phrase( "metapage_title_".$page ) );
					push @list, $a;
				}
				next;
			}
			my $url = "edit_eprint?eprintid=".$eprint->get_id."&dataview=".$dataview."&_action_jump=1&stage=".$stage;
			my $a = $session->render_link( $url );
			$a->appendChild( $session->html_phrase( "cgi/users/edit_eprint:stage_".$stage ) );
			push @list, $a;
		}

		$table->appendChild( $session->render_row(
			$session->html_phrase( "cgi/users/edit_eprint:edit" ),
			render_links_list( $session, @list ) ) );
	}


	# EXPORT

	@list = ();
	my @plugins = $session->plugin_list( 
					type=>"Export",
					can_accept=>"dataobj/eprint", 
					is_visible=>"staff" );
	foreach my $plugin_id ( @plugins ) {
		my $plugin = $session->plugin( $plugin_id );
		my $url = $plugin->dataobj_export_url( $eprint, 1 );
		my $a = $session->render_link( $url );
		$a->appendChild( $plugin->render_name() );
		push @list, $a;
	}

	$table->appendChild( $session->render_row(
		$session->html_phrase( "cgi/users/edit_eprint:export" ),
		render_links_list( $session, @list ) ) );

	# VIEWS

	@list = ();	
	foreach my $view ( qw/ summary full history / )
	{
		my $li = $session->make_element( "li", style=>"margin-bottom: 1em;" );
		my $label = $session->html_phrase( "cgi/users/edit_eprint:view_".$view );
		if( $view eq $dataview )
		{
			my $strong = $session->make_element( "strong" );
			$strong->appendChild( $label );
			push @list, $strong;
		}
		else
		{
			my $url = "edit_eprint?eprintid=".$eprint->get_id."&dataview=".$view;
			my $a = $session->render_link( $url );
			$a->appendChild( $label );
			push @list, $a;
		}
	}

	$table->appendChild( $session->render_row(
		$session->html_phrase( "cgi/users/edit_eprint:views" ),
		render_links_list( $session, @list ) ) );


	# VIEW DETAILS
	
	my( $data, $title );
	($data,$title) = $eprint->render if( $dataview eq "summary" );
	($data,$title) = $eprint->render_full if( $dataview eq "full" );
	($data,$title) = $eprint->render_history if( $dataview eq "history" );

	$page->appendChild( $session->render_ruler );
	$page->appendChild( $data );

	$session->build_page( $session->html_phrase( "cgi/users/edit_eprint:form_title" ), $page, "move_form" );
	$session->send_page();
}


sub bounce_form
{
	my( $session, $delete, $eprint ) = @_;

	# Get the user's details
	my $user = $eprint->get_user();
	# We can't bounce it if there's no user associated - but
	# we can still delete it.
	if( !defined $user && !$delete)
	{
		$session->render_error( 
			$session->html_phrase( "cgi/users/edit_eprint:no_user" ),
			"buffer" );
		return;
	}

	my $page = $session->make_doc_fragment();

	my $form = $session->render_form( "post", "edit_eprint" );
	if( defined $user )
	{
		$page->appendChild( $session->html_phrase( "cgi/users/edit_eprint:bounce_form_intro", langpref=>$user->render_value( "lang" ) ) );
		my $div = $session->make_element( "div", class => "formfieldinput" );
		my $textarea = $session->make_element(
			"textarea",
			name => "reason",
			rows => 20,
			cols => 60,
			wrap => "virtual" );
		# remove any markup:
		my $title = $session->make_text( EPrints::Utils::tree_to_utf8( $eprint->render_description() ) );

		my $phraseid = '';
		if( $delete )
		{
			if( $eprint->get_dataset->id eq "inbox" )
			{
				$phraseid = "mail_delete_reason.inbox";
			}
			else
			{
				$phraseid = "mail_delete_reason";
			}
		}
		else
		{
			$phraseid = "mail_bounce_reason";
		}
	
		$textarea->appendChild( $session->html_phrase( $phraseid, title => $title ) );
		$div->appendChild( $textarea );
		$form->appendChild( $div );

		$form->appendChild( $session->render_action_buttons(
			"_send" => $session->phrase( "cgi/users/edit_eprint:action_send" ),
			"_cancel" => $session->phrase( "cgi/users/edit_eprint:action_cancel" ),
 		) );
	}
	else
	{
		my $p = $session->make_element( "p" );
		$p->appendChild( $eprint->render_description() );
		$form->appendChild( $p );

		$form->appendChild( $session->render_action_buttons(
			"_send" => $session->phrase( "cgi/users/edit_eprint:action_reallydelete" ),
			"_cancel" => $session->phrase( "cgi/users/edit_eprint:action_cancel" ), ));
	}
	

	$form->appendChild( $session->render_hidden_field( "eprintid", $eprint->get_value( "eprintid" ) ) );
	$form->appendChild( $session->render_hidden_field( "dataset", $eprint->get_dataset()->id() ) );
	$form->appendChild( $session->render_hidden_field( "delete", $delete ) );

	$page->appendChild( $form );

	$session->build_page(
		$session->html_phrase( "cgi/users/edit_eprint:title_".( $delete ? "delete" : "bounce" )."_form" ),
		$page,
		"editeprint_form" );
	$session->send_page();
}


sub bounce
{
	my( $session, $eprint ) = @_;

	my $delete = $session->param( "delete" );

	# Get the user's details
	my $user = $eprint->get_user();
	# We can't bounce it if there's no user associated - but
	# we can still delete it.
	if( !defined $user && !$delete)
	{
		# Can't find the user
		view_page( $session, $eprint, $session->html_phrase( "cgi/users/edit_eprint:no_user" ), 1 );
		return;
	}
	
	my $success = 0;
	
	if( $delete )
	{
		# Delete the submission
		$success = $eprint->remove();
	}
	else
	{
		# Transfer the EPrint back to the user's inbox
		$success = $eprint->move_to_inbox();
	}
	
	unless( $success )
	{
		# Couldn't be bounced at all
		view_page( $session, $eprint, $session->html_phrase( "cgi/users/edit_eprint:bord_fail" ), 1 );
		return;
	}

	if( !defined $user )
	{
		# Can't send mail to a user what does not
		# exist.
		view_page( $session, $eprint );
		return;
	}

	my $mail = $session->make_element( "mail" );
	$mail->appendChild( $session->make_text( $session->param( "reason" ) ) );

	# Successfully transferred, mail the user with the reason
	if( $user->mail(
		"cgi/users/edit_eprint:subject_bounce",
		$mail,
		$session->current_user() ) )
	{
		$eprint->log_mail_owner( $mail );

		# Successfully bounced, redirect
		view_page( $session, $eprint );
		return;
	}

	# Couldn't mail
	view_page( 
		$session, 
		$eprint, 
		$session->html_phrase( "cgi/users/edit_eprint:mail_fail",
			username=>$user->render_value( "username" ),
			email=>$user->render_value( "email" ) ),
		1 );
}

sub render_links_list
{
	my( $session, @list ) = @_;

	my $f = $session->make_doc_fragment;
	my $first = 1;
	foreach my $item ( @list )
	{
		if( $first ) 
		{
			$first = 0;
		}
		else
		{
			$f->appendChild( $session->make_text( " | " ) );
		}
		$f->appendChild( $item );
	}
	return $f;
}


