<?php

/*
Undo Delete Plugin for MyBB
Copyright (C) 2009 Sebastian Wunderlich

This program 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 3 of the License, or
(at your option) any later version.

This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/

if(!defined('IN_MYBB'))
{
	die();
}

define('BACKUPTABLE_PREFIX','backup_');
define('BACKUPTABLES',serialize(array('attachments','polls','pollvotes','posts','threads','threadsubscriptions')));

$plugins->add_hook('admin_tools_action_handler','undodelete_admin_action');
$plugins->add_hook('admin_tools_menu','undodelete_admin_menu');
$plugins->add_hook('admin_tools_permissions','undodelete_admin_permissions');
$plugins->add_hook('admin_load','undodelete_admin');
$plugins->add_hook('class_moderation_delete_thread_start','undodelete_backup_thread');
$plugins->add_hook('class_moderation_delete_post_start','undodelete_backup_post');
$plugins->add_hook('class_moderation_delete_poll','undodelete_backup_poll');
$plugins->add_hook('remove_attachments_do_delete','undodelete_backup_attachment');
$plugins->add_hook('remove_attachment_do_delete','undodelete_backup_attachment');

function undodelete_info()
{
	global $lang;
	undodelete_lang();
	return array
	(
		'name'=>$lang->undodelete_info_name,
		'description'=>$lang->undodelete_info_description,
		'website'=>'http://mods.mybboard.net/view/undo-delete',
		'author'=>'Sebastian Wunderlich',
		'version'=>'1.2',
		'guid'=>'ddec607d04838d9a320fc870c55589b1',
		'compatibility'=>'14*,16*'
	);
}

function undodelete_activate()
{
	change_admin_permission('tools','undodelete');
}

function undodelete_deactivate()
{
	change_admin_permission('tools','undodelete',-1);
}

function undodelete_install()
{
	global $db;
	undodelete_uninstall();
	foreach(unserialize(BACKUPTABLES) as $table)
	{
		$db->query('CREATE TABLE '.TABLE_PREFIX.BACKUPTABLE_PREFIX.$table.' LIKE '.TABLE_PREFIX.$table);
	}
}

function undodelete_is_installed()
{
	global $db,$plugins_cache;
	foreach(unserialize(BACKUPTABLES) as $table)
	{
		if($db->table_exists(BACKUPTABLE_PREFIX.$table))
		{
			$install=true;
		}
	}
	if($install||(is_array($plugins_cache)&&is_array($plugins_cache['active'])&&$plugins_cache['active']['undodelete']))
	{
		return true;
	}
	return false;
}

function undodelete_uninstall()
{
	global $db;
	undodelete_trash_attachments();
	foreach(unserialize(BACKUPTABLES) as $table)
	{
		$db->drop_table(BACKUPTABLE_PREFIX.$table);
	}
}

function undodelete_lang()
{
	global $lang;
	$lang->load('undodelete',false,true);
	$l['undodelete_info_name']='Undo Delete';
	$l['undodelete_info_description']='Allows you to restore deleted threads, posts, polls and attachments.';
	$l['undodelete_main_title']='Backup Stats';
	$l['undodelete_main_description']='Here you can view some stats of backup tables.';
	$l['undodelete_main_table']='Backup Stats';
	$l['undodelete_main_table_table']='Table';
	$l['undodelete_main_table_entries']='Entries';
	$l['undodelete_main_table_status']='Status';
	$l['undodelete_main_control_truncate']='Truncate Table';
	$l['undodelete_main_control_recreate']='Recreate Table';
	$l['undodelete_main_control_truncate_question']='Are you sure you wish to delete all entries of this table?';
	$l['undodelete_main_control_recreate_question']='Are you sure you wish to recreate this table?';
	$l['undodelete_threads_title']='Threads';
	$l['undodelete_threads_description']='Here you can manage deleted threads.';
	$l['undodelete_threads_table']='Saved Threads';
	$l['undodelete_threads_table_id']='ID';
	$l['undodelete_threads_table_forum']='Forum';
	$l['undodelete_threads_table_subject']='Subject';
	$l['undodelete_threads_table_author']='Author';
	$l['undodelete_threads_table_date']='Date';
	$l['undodelete_threads_control_all']='Restore Thread';
	$l['undodelete_threads_control_all_question']='Are you sure you wish to restore this thread?';
	$l['undodelete_posts_title']='Posts';
	$l['undodelete_posts_description']='Here you can manage deleted posts.';
	$l['undodelete_posts_table']='Saved Posts';
	$l['undodelete_posts_table_id']='ID';
	$l['undodelete_posts_table_thread']='Thread';
	$l['undodelete_posts_table_message']='Message';
	$l['undodelete_posts_table_author']='Author';
	$l['undodelete_posts_table_date']='Date';
	$l['undodelete_posts_popup_viewer']='Undo Delete Post Viewer';
	$l['undodelete_posts_popup_close']='Close Window';
	$l['undodelete_posts_popup_post']='Post';
	$l['undodelete_posts_popup_subject']='Subject';
	$l['undodelete_polls_title']='Polls';
	$l['undodelete_polls_description']='Here you can manage deleted polls.';
	$l['undodelete_polls_table']='Saved Polls';
	$l['undodelete_polls_table_id']='ID';
	$l['undodelete_polls_table_thread']='Thread';
	$l['undodelete_polls_table_question']='Question';
	$l['undodelete_polls_table_date']='Date';
	$l['undodelete_attachments_title']='Attachments';
	$l['undodelete_attachments_description']='Here you can view and manage deleted attachments.';
	$l['undodelete_attachments_table']='Saved Attachments';
	$l['undodelete_attachments_table_id']='ID';
	$l['undodelete_attachments_table_post']='Post';
	$l['undodelete_attachments_table_filename']='Filename';
	$l['undodelete_attachments_table_author']='Uploader';
	$l['undodelete_attachments_table_date']='Date';
	$l['undodelete_attachments_control_view']='View Attachment';
	$l['undodelete_update_title']='Update Tables';
	$l['undodelete_update_description']='If there is a difference between a core table and its backup table Undo Delete will not work. Here you can see what you have to modify to update your backup tables manually. <strong>If you not know what this means recreate affected tables.</strong>';
	$l['undodelete_update_table']='Database Structure Difference Analysis: {1}';
	$l['undodelete_delete_backup']='Delete Backup';
	$l['undodelete_restore_backup']='Restore Backup';
	$l['undodelete_delete_backup_question']='Are you sure you wish to delete this backup?';
	$l['undodelete_restore_backup_question']='Are you sure you wish to restore this backup?';
	$l['undodelete_truncate_success']='Successfully truncated backup table.';
	$l['undodelete_truncate_error']='Could not truncate backup table.';
	$l['undodelete_recreate_success']='Successfully recreated backup table.';
	$l['undodelete_recreate_error']='Could not recreate backup table.';
	$l['undodelete_delete_success']='Successfully deleted backup.';
	$l['undodelete_delete_error']='Could not delete backup.';
	$l['undodelete_restore_success']='Successfully restored backup.';
	$l['undodelete_restore_error']='Could not restore backup.';
	$l['undodelete_update_success']='All backup tables are up to date.';
	$l['undodelete_update_error']='There are outdated backup tables you have to modify.';
	$l['undodelete_no_backups']='There are currently no backups available.';
	$l['undodelete_dateline']='{1}, {2}';
	$l['undodelete_legend_table_success']='Backup table up to date';
	$l['undodelete_legend_table_error']='Backup table out of date';
	$l['undodelete_legend_forum_available']='Forum available';
	$l['undodelete_legend_forum_unavailable']='Forum not available';
	$l['undodelete_legend_thread_available']='Thread available';
	$l['undodelete_legend_thread_unavailable']='Thread not available';
	$l['undodelete_legend_post_available']='Post available';
	$l['undodelete_legend_post_unavailable']='Post not available';
	$l['undodelete_legend_backup_available']='Backup available';
	$l['undodelete_legend_poll_new']='Thread contains a new poll';
	$l['undodelete_can_manage_backups']='Can manage backups?';
	foreach($l as $key=>$val)
	{
		if(!$lang->$key)
		{
			$lang->$key=$val;
		}
	}
}

function undodelete_check_table($table,$hard=false,$count=false)
{
	global $db;
	if(!$db->table_exists(BACKUPTABLE_PREFIX.$table))
	{
		$db->query('CREATE TABLE '.TABLE_PREFIX.BACKUPTABLE_PREFIX.$table.' LIKE '.TABLE_PREFIX.$table);
	}
	$create=$db->show_create_table($table);
	$create=preg_replace('#AUTO_INCREMENT=([0-9]+) #Usi','',$create);
	$create_backup=$db->show_create_table(BACKUPTABLE_PREFIX.$table);
	$create_backup=str_replace(TABLE_PREFIX.BACKUPTABLE_PREFIX.$table,TABLE_PREFIX.$table,$create_backup);
	$create_backup=preg_replace('#AUTO_INCREMENT=([0-9]+) #Usi','',$create_backup);
	if($create!=$create_backup)
	{
		$return[]=$table;
		$return[]='error';
		if($count)
		{
			$return[]=$db->num_rows($db->simple_select(BACKUPTABLE_PREFIX.$table));
		}
		return $return;
	}
	if($hard)
	{
		$return[]=$table;
		$return[]='success';
		if($count)
		{
			$return[]=$db->num_rows($db->simple_select(BACKUPTABLE_PREFIX.$table));
		}
		return $return;
	}
	return false;
}

function undodelete_compare_table($table)
{
	global $db,$lang;
	undodelete_lang();
	require_once MYBB_ROOT.'inc/3rdparty/diff/Diff.php';
	require_once MYBB_ROOT.'inc/3rdparty/diff/Diff/Renderer/inline.php';
	$create_backup=$db->show_create_table(BACKUPTABLE_PREFIX.$table);
	$create_backup=preg_replace('#AUTO_INCREMENT=([0-9]+) #Usi','',$create_backup);
	$create=$db->show_create_table($table);
	$create=str_replace(TABLE_PREFIX.$table,TABLE_PREFIX.BACKUPTABLE_PREFIX.$table,$create);
	$create=preg_replace('#AUTO_INCREMENT=([0-9]+) #Usi','',$create);
	$create_backup=explode("\n",$create_backup);
	$create=explode("\n",$create);
	$diff=&new Text_Diff('auto',array($create_backup,$create));
	$renderer=&new Text_Diff_Renderer_inline();
	$itable=new Table;
	$itable->construct_cell('<pre>'.$renderer->render($diff).'</pre>');
	$itable->construct_row();
	$itable->output($lang->sprintf($lang->undodelete_update_table,TABLE_PREFIX.BACKUPTABLE_PREFIX.$table));
}

function undodelete_trash_attachments()
{
	global $mybb,$db;
	if(!$db->table_exists(BACKUPTABLE_PREFIX.'attachments'))
	{
		return false;
	}
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'attachments','attachname,thumbnail');
	while($attachment=$db->fetch_array($query))
	{
		@unlink('../'.$mybb->settings['uploadspath'].'/'.$attachment['attachname'].'.backup');
		if($attachment['thumbnail'])
		{
			@unlink('../'.$mybb->settings['uploadspath'].'/'.$attachment['thumbnail'].'.backup');
		}
		$date_directory=explode('/',$attachment['attachname']);
		if(@is_dir('../'.$mybb->settings['uploadspath'].'/'.$date_directory[0]))
		{
			@rmdir('../'.$mybb->settings['uploadspath'].'/'.$date_directory[0]);
		}
	}
	return true;
}

function undodelete_clean_query(&$query)
{
	global $db;
	$query=$db->escape_string($query);
}

function undodelete_admin_action(&$action)
{
	$action['undodelete']=array('active'=>'undodelete');
}

function undodelete_admin_menu(&$sub_menu)
{
	global $lang;
	undodelete_lang();
	end($sub_menu);
	$key=(key($sub_menu))+10;
	$sub_menu[$key]=array
	(
		'id'=>'undodelete',
		'title'=>$lang->undodelete_info_name,
		'link'=>'index.php?module=tools/undodelete'
	);
}

function undodelete_admin_permissions(&$admin_permissions)
{
	global $lang;
	undodelete_lang();
	$admin_permissions['undodelete']=$lang->undodelete_can_manage_backups;
}

function undodelete_admin()
{
	global $mybb,$page,$db,$lang;
	undodelete_lang();
	require_once MYBB_ROOT.'inc/functions_rebuild.php';
	if($page->active_action!='undodelete')
	{
		return false;
	}
	if($mybb->input['action'])
	{
		foreach(unserialize(BACKUPTABLES) as $table)
		{
			if(undodelete_check_table($table))
			{
				$errors[]=undodelete_check_table($table);
			}
		}
	}
	$sub_tabs['undodelete']=array
	(
		'title'=>$lang->undodelete_main_title,
		'link'=>'index.php?module=tools/undodelete',
		'description'=>$lang->undodelete_main_description
	);
	$sub_tabs['undodelete_threads']=array
	(
		'title'=>$lang->undodelete_threads_title,
		'link'=>'index.php?module=tools/undodelete&amp;action=threads',
		'description'=>$lang->undodelete_threads_description
	);
	$sub_tabs['undodelete_posts']=array
	(
		'title'=>$lang->undodelete_posts_title,
		'link'=>'index.php?module=tools/undodelete&amp;action=posts',
		'description'=>$lang->undodelete_posts_description
	);
	$sub_tabs['undodelete_polls']=array
	(
		'title'=>$lang->undodelete_polls_title,
		'link'=>'index.php?module=tools/undodelete&amp;action=polls',
		'description'=>$lang->undodelete_polls_description
	);
	$sub_tabs['undodelete_attachments']=array
	(
		'title'=>$lang->undodelete_attachments_title,
		'link'=>'index.php?module=tools/undodelete&amp;action=attachments',
		'description'=>$lang->undodelete_attachments_description
	);
	$sub_tabs['undodelete_update']=array
	(
		'title'=>$lang->undodelete_update_title,
		'link'=>'index.php?module=tools/undodelete&amp;action=update',
		'description'=>$lang->undodelete_update_description
	);
	if(!$mybb->input['action'])
	{
		if($mybb->input['truncate'])
		{
			$tables=unserialize(BACKUPTABLES);
			if(in_array($mybb->input['truncate'],$tables))
			{
				if($mybb->input['truncate']=='attachments')
				{
					undodelete_trash_attachments();
				}
				$db->query('TRUNCATE TABLE '.TABLE_PREFIX.BACKUPTABLE_PREFIX.$mybb->input['truncate']);
				if($mybb->input['truncate']=='threads')
				{
					$db->query('TRUNCATE TABLE '.TABLE_PREFIX.BACKUPTABLE_PREFIX.'threadsubscriptions');
				}
				if($mybb->input['truncate']=='polls')
				{
					$db->query('TRUNCATE TABLE '.TABLE_PREFIX.BACKUPTABLE_PREFIX.'pollvotes');
				}
				flash_message($lang->undodelete_truncate_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_truncate_error,'error');
			}
			admin_redirect($sub_tabs['undodelete']['link']);
		}
		if($mybb->input['recreate'])
		{
			$tables=unserialize(BACKUPTABLES);
			if(in_array($mybb->input['recreate'],$tables))
			{
				if($mybb->input['recreate']=='attachments')
				{
					undodelete_trash_attachments();
				}
				$db->drop_table(BACKUPTABLE_PREFIX.$mybb->input['recreate']);
				if($mybb->input['recreate']=='threads'||$mybb->input['recreate']=='threadsubscriptions')
				{
					$db->drop_table(BACKUPTABLE_PREFIX.'threadsubscriptions');
					$db->drop_table(BACKUPTABLE_PREFIX.'threads');
				}
				if($mybb->input['recreate']=='polls'||$mybb->input['recreate']=='pollvotes')
				{
					$db->drop_table(BACKUPTABLE_PREFIX.'pollvotes');
					$db->drop_table(BACKUPTABLE_PREFIX.'polls');
				}
				flash_message($lang->undodelete_recreate_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_recreate_error,'error');
			}
			admin_redirect($sub_tabs['undodelete']['link']);
		}
		$page->add_breadcrumb_item($lang->undodelete_info_name);
		$page->output_header($lang->undodelete_info_name);
		$page->output_nav_tabs($sub_tabs,'undodelete');
		$itable=new Table;
		$itable->construct_header($lang->undodelete_main_table_table);
		$itable->construct_header($lang->undodelete_main_table_entries);
		$itable->construct_header($lang->undodelete_main_table_status);
		$itable->construct_header($lang->controls);
		foreach(unserialize(BACKUPTABLES) as $table)
		{
			$status=undodelete_check_table($table,true,true);
			$itable->construct_cell('<strong>'.TABLE_PREFIX.BACKUPTABLE_PREFIX.$status[0].'</strong>');
			$itable->construct_cell($status[2]);
			$itable->construct_cell('<img src="styles/'.$page->style.'/images/icons/'.$status[1].'.gif" alt="['.$status[1].']" style="vertical-align:middle;" />');
			$popup=new PopupMenu('table_'.$status[0],$lang->options);
			if(($status[0]!='pollvotes'&&$status[0]!='threadsubscriptions')&&$status[2]!=0)
			{
				$add_truncate=1;
			}
			if($status[1]=='error')
			{
				$add_recreate=1;
			}
			if($add_truncate||$add_recreate)
			{
				if($add_truncate)
				{
					$popup->add_item($lang->undodelete_main_control_truncate,$sub_tabs['undodelete']['link'].'&amp;truncate='.$status[0].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_main_control_truncate_question.'\')');
					unset($add_truncate);
				}
				if($add_recreate)
				{
					$popup->add_item($lang->undodelete_main_control_recreate,$sub_tabs['undodelete']['link'].'&amp;recreate='.$status[0].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_main_control_recreate_question.'\')');
					unset($add_recreate);
				}
				$itable->construct_cell($popup->fetch());
			}
			else
			{
				$itable->construct_cell('&nbsp;');
			}
			$itable->construct_row();
		}
		$itable->output($lang->undodelete_main_table);
		echo <<<LEGEND
<fieldset>
<legend>$lang->legend</legend>
<img src="styles/$page->style/images/icons/success.gif" alt="[success]" style="vertical-align:middle;" /> $lang->undodelete_legend_table_success<br />
<img src="styles/$page->style/images/icons/error.gif" alt="[error]" style="vertical-align: middle;" /> $lang->undodelete_legend_table_error<br />
</fieldset>
LEGEND;
		$page->output_footer();
	}
	if($mybb->input['action']=='threads')
	{
		if($errors)
		{
			flash_message($lang->undodelete_update_error,'error');
			admin_redirect($sub_tabs['undodelete_update']['link']);
		}
		if($mybb->input['restore'])
		{
			if(undodelete_restore_thread(intval($mybb->input['restore'])))
			{
				flash_message($lang->undodelete_restore_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_restore_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_threads']['link']);
		}
		if($mybb->input['all'])
		{
			if(undodelete_restore_all(intval($mybb->input['all'])))
			{
				flash_message($lang->undodelete_restore_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_restore_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_threads']['link']);
		}
		if($mybb->input['delete'])
		{
			if(undodelete_trash_thread(intval($mybb->input['delete'])))
			{
				flash_message($lang->undodelete_delete_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_delete_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_threads']['link']);
		}
		$page->add_breadcrumb_item($lang->undodelete_info_name,$sub_tabs['undodelete']['link']);
		$page->add_breadcrumb_item($sub_tabs['undodelete_threads']['title']);
		$page->output_header($lang->undodelete_info_name.' - '.$sub_tabs['undodelete_threads']['title']);
		$page->output_nav_tabs($sub_tabs,'undodelete_threads');
		$itable=new Table;
		$itable->construct_header($lang->undodelete_threads_table_id);
		$itable->construct_header($lang->undodelete_threads_table_forum);
		$itable->construct_header($lang->undodelete_threads_table_subject);
		$itable->construct_header($lang->undodelete_threads_table_author);
		$itable->construct_header($lang->undodelete_threads_table_date);
		$itable->construct_header($lang->controls);
		$query=$db->simple_select(BACKUPTABLE_PREFIX.'threads','*','',array('order_by'=>'fid','order_dir'=>'desc'));
		if($db->num_rows($query)>0)
		{
			while($thread=$db->fetch_array($query))
			{
				if($mybb->input['highlight']==$thread['tid'])
				{
					$highlight=array('style'=>'background-color:#fffbd9');
				}
				else
				{
					$highlight='';
				}
				$itable->construct_cell($thread['tid'],$highlight);
				$forum=get_forum($thread['fid']);
				if($forum)
				{
					$itable->construct_cell('<a href="'.$mybb->settings['bburl'].'/'.get_forum_link($thread['fid']).'" title="'.htmlspecialchars_uni($forum['name']).'" target="_blank"><img src="styles/'.$page->style.'/images/icons/world.gif" alt="[available]" style="vertical-align:middle;" /></a>',$highlight);
				}
				else
				{
					$itable->construct_cell('<img src="styles/'.$page->style.'/images/icons/cross.gif" alt="[unavailable]" title="'.$thread['fid'].'" style="vertical-align:middle;" />',$highlight);
					$lock=$thread['tid'];
				}
				$itable->construct_cell('<strong>'.htmlspecialchars_uni($thread['subject']).'</strong>',$highlight);
				$user=get_user($thread['uid']);
				$itable->construct_cell(build_profile_link(format_name($thread['username'],$user['usergroup'],$user['displaygroup']),$thread['uid'],'_blank'),$highlight);
				$itable->construct_cell($lang->sprintf($lang->undodelete_dateline,my_date($mybb->settings['dateformat'],$thread['dateline']),my_date($mybb->settings['timeformat'],$thread['dateline'])),$highlight);
				$popup=new PopupMenu('thread_'.$thread['tid'],$lang->options);
				if($lock!=$thread['tid'])
				{
					$popup->add_item($lang->undodelete_restore_backup,$sub_tabs['undodelete_threads']['link'].'&amp;restore='.$thread['tid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_restore_backup_question.'\')');
					$popup->add_item($lang->undodelete_threads_control_all,$sub_tabs['undodelete_threads']['link'].'&amp;all='.$thread['tid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_threads_control_all_question.'\')');
				}
				$popup->add_item($lang->undodelete_delete_backup,$sub_tabs['undodelete_threads']['link'].'&amp;delete='.$thread['tid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_delete_backup_question.'\')');
				$itable->construct_cell($popup->fetch(),$highlight);
				$itable->construct_row();
			}
		}
		else
		{
			$itable->construct_cell($lang->undodelete_no_backups,array('colspan'=>6));
			$itable->construct_row();
		}
		$itable->output($lang->undodelete_threads_table);
		echo <<<LEGEND
<fieldset>
<legend>$lang->legend</legend>
<img src="styles/$page->style/images/icons/world.gif" alt="[availabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_forum_available<br />
<img src="styles/$page->style/images/icons/cross.gif" alt="[unavailabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_forum_unavailable<br />
</fieldset>
LEGEND;
		$page->output_footer();
	}
	if($mybb->input['action']=='posts')
	{
		if($errors)
		{
			flash_message($lang->undodelete_update_error,'error');
			admin_redirect($sub_tabs['undodelete_update']['link']);
		}
		if($mybb->input['restore'])
		{
			if(undodelete_restore_post(intval($mybb->input['restore'])))
			{
				flash_message($lang->undodelete_restore_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_restore_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_posts']['link']);
		}
		if($mybb->input['delete'])
		{
			if(undodelete_trash_post(intval($mybb->input['delete'])))
			{
				flash_message($lang->undodelete_delete_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_delete_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_posts']['link']);
		}
		if($mybb->input['view'])
		{
			$query=$db->simple_select(BACKUPTABLE_PREFIX.'posts','uid,username,subject,message,dateline','pid='.intval($mybb->input['view']));
			if($db->num_rows($query)==1)
			{
				$post=$db->fetch_array($query);
				require_once MYBB_ROOT.'inc/class_parser.php';
				$parser=new postParser;
				$parser_options=array
				(
					'allow_mycode'=>1,
					'allow_smilies'=>1,
					'nl2br'=>1,
					'allow_imgcode'=>1
				);
				$message=$parser->parse_message($post['message'],$parser_options);
				echo <<<POPUP
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head profile="http://gmpg.org/xfn/1">
		<title>$lang->undodelete_posts_popup_viewer</title>
		<link rel="stylesheet" href="styles/$page->style/main.css" type="text/css" />
		<link rel="stylesheet" href="styles/$page->style/popup.css" type="text/css" />
	</head>
	<body id="popup">
		<div id="popup_container">
			<div class="popup_title"><a href="#" onclick="window.close();" class="close_link">$lang->undodelete_posts_popup_close</a>$lang->undodelete_posts_popup_viewer</div>
			<div id="content">
POPUP;
				$user=get_user($post['uid']);
				$itable=new Table();
				$itable->construct_cell($lang->undodelete_posts_popup_subject);
				$itable->construct_cell(htmlspecialchars_uni($post['subject']));
				$itable->construct_row();
				$itable->construct_cell($lang->undodelete_posts_table_author);
				$itable->construct_cell(build_profile_link(format_name($post['username'],$user['usergroup'],$user['displaygroup']),$post['uid'],'_blank'));
				$itable->construct_row();
				$itable->construct_cell($lang->undodelete_posts_table_date);
				$itable->construct_cell($lang->sprintf($lang->undodelete_dateline,my_date($mybb->settings['dateformat'],$post['dateline']),my_date($mybb->settings['timeformat'],$post['dateline'])));
				$itable->construct_row();
				$itable->construct_cell($message,array('colspan'=>2));
				$itable->construct_row();
				$itable->output($lang->undodelete_posts_popup_post);
				echo <<<POPUP
			</div>
		</div>
	</body>
</html>
POPUP;
			}
			exit();
		}
		$page->add_breadcrumb_item($lang->undodelete_info_name,$sub_tabs['undodelete']['link']);
		$page->add_breadcrumb_item($sub_tabs['undodelete_posts']['title']);
		$page->output_header($lang->undodelete_info_name.' - '.$sub_tabs['undodelete_posts']['title']);
		$page->output_nav_tabs($sub_tabs,'undodelete_posts');
		$itable=new Table;
		$itable->construct_header($lang->undodelete_posts_table_id);
		$itable->construct_header($lang->undodelete_posts_table_thread);
		$itable->construct_header($lang->undodelete_posts_table_message);
		$itable->construct_header($lang->undodelete_posts_table_author);
		$itable->construct_header($lang->undodelete_posts_table_date);
		$itable->construct_header($lang->controls);
		$query=$db->simple_select(BACKUPTABLE_PREFIX.'posts','*','',array('order_by'=>'tid','order_dir'=>'desc'));
		if($db->num_rows($query)>0)
		{
			while($post=$db->fetch_array($query))
			{
				if($mybb->input['highlight']==$post['pid'])
				{
					$highlight=array('style'=>'background-color:#fffbd9');
				}
				else
				{
					$highlight='';
				}
				$itable->construct_cell($post['pid'],$highlight);
				$thread=get_thread($post['tid']);
				if($thread)
				{
					$itable->construct_cell('<a href="'.$mybb->settings['bburl'].'/'.get_thread_link($thread['tid']).'" title="'.htmlspecialchars_uni($thread['subject']).'" target="_blank"><img src="styles/'.$page->style.'/images/icons/world.gif" alt="[availabe]" style="vertical-align:middle;" /></a>',$highlight);
				}
				elseif($db->num_rows($db->simple_select(BACKUPTABLE_PREFIX.'threads','tid','tid='.$post['tid']))==1)
				{
					$itable->construct_cell('<a href="'.$sub_tabs['undodelete_threads']['link'].'&amp;highlight='.$post['tid'].'" title="'.$post['tid'].'"><img src="styles/'.$page->style.'/images/icons/custom.gif" alt="[deleted]" style="vertical-align:middle;" /></a>',$highlight);
					$lock=$post['pid'];
				}
				else
				{
					$itable->construct_cell('<img src="styles/'.$page->style.'/images/icons/cross.gif" alt="[unavailabe]" title="'.$post['tid'].'" style="vertical-align:middle;" />',$highlight);
					$lock=$post['pid'];
				}
				$itable->construct_cell('<a href="javascript:MyBB.popupWindow(\''.$sub_tabs['undodelete_posts']['link'].'&amp;view='.$post['pid'].'\',\'post_'.$post['pid'].'\',450,450);">'.htmlspecialchars_uni($post['subject']).'</a>',$highlight);
				$user=get_user($post['uid']);
				$itable->construct_cell(build_profile_link(format_name($post['username'],$user['usergroup'],$user['displaygroup']),$post['uid'],'_blank'),$highlight);
				$itable->construct_cell($lang->sprintf($lang->undodelete_dateline,my_date($mybb->settings['dateformat'],$post['dateline']),my_date($mybb->settings['timeformat'],$post['dateline'])),$highlight);
				$popup=new PopupMenu('post_'.$post['pid'],$lang->options);
				if($lock!=$post['pid'])
				{
					$popup->add_item($lang->undodelete_restore_backup,$sub_tabs['undodelete_posts']['link'].'&amp;restore='.$post['pid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_restore_backup_question.'\')');
				}
				$popup->add_item($lang->undodelete_delete_backup,$sub_tabs['undodelete_posts']['link'].'&amp;delete='.$post['pid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_delete_backup_question.'\')');
				$itable->construct_cell($popup->fetch(),$highlight);
				$itable->construct_row();
			}
		}
		else
		{
			$itable->construct_cell($lang->undodelete_no_backups,array('colspan'=>6));
			$itable->construct_row();
		}
		$itable->output($lang->undodelete_posts_table);
		echo <<<LEGEND
<fieldset>
<legend>$lang->legend</legend>
<img src="styles/$page->style/images/icons/world.gif" alt="[availabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_thread_available<br />
<img src="styles/$page->style/images/icons/custom.gif" alt="[deleted]" style="vertical-align:middle;" /> $lang->undodelete_legend_backup_available<br />
<img src="styles/$page->style/images/icons/cross.gif" alt="[unavailabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_thread_unavailable<br />
</fieldset>
LEGEND;
		$page->output_footer();
	}
	if($mybb->input['action']=='polls')
	{
		if($errors)
		{
			flash_message($lang->undodelete_update_error,'error');
			admin_redirect($sub_tabs['undodelete_update']['link']);
		}
		if($mybb->input['restore'])
		{
			if(undodelete_restore_poll(intval($mybb->input['restore'])))
			{
				flash_message($lang->undodelete_restore_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_restore_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_polls']['link']);
		}
		if($mybb->input['delete'])
		{
			if(undodelete_trash_poll(intval($mybb->input['delete'])))
			{
				flash_message($lang->undodelete_delete_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_delete_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_polls']['link']);
		}
		$page->add_breadcrumb_item($lang->undodelete_info_name,$sub_tabs['undodelete']['link']);
		$page->add_breadcrumb_item($sub_tabs['undodelete_polls']['title']);
		$page->output_header($lang->undodelete_info_name.' - '.$sub_tabs['undodelete_polls']['title']);
		$page->output_nav_tabs($sub_tabs,'undodelete_polls');
		$itable=new Table;
		$itable->construct_header($lang->undodelete_polls_table_id);
		$itable->construct_header($lang->undodelete_polls_table_thread);
		$itable->construct_header($lang->undodelete_polls_table_question);
		$itable->construct_header($lang->undodelete_polls_table_date);
		$itable->construct_header($lang->controls);
		$query=$db->simple_select(BACKUPTABLE_PREFIX.'polls','*','',array('order_by'=>'tid','order_dir'=>'desc'));
		if($db->num_rows($query)>0)
		{
			while($poll=$db->fetch_array($query))
			{
				if($mybb->input['highlight']==$poll['pid'])
				{
					$highlight=array('style'=>'background-color:#fffbd9');
				}
				else
				{
					$highlight='';
				}
				$itable->construct_cell($poll['pid'],$highlight);
				$thread=get_thread($poll['tid']);
				if($thread)
				{
					if($thread['poll']&&$thread['poll']!=$poll['pid'])
					{
						$itable->construct_cell('<a href="'.$mybb->settings['bburl'].'/'.get_thread_link($thread['tid']).'" title="'.htmlspecialchars_uni($thread['subject']).'" target="_blank"><img src="styles/'.$page->style.'/images/icons/warning.gif" alt="[warning]" style="vertical-align:middle;" /></a>',$highlight);
						$lock=$poll['pid'];
					}
					else
					{
						$itable->construct_cell('<a href="'.$mybb->settings['bburl'].'/'.get_thread_link($thread['tid']).'" title="'.htmlspecialchars_uni($thread['subject']).'" target="_blank"><img src="styles/'.$page->style.'/images/icons/world.gif" alt="[availabe]" style="vertical-align:middle;" /></a>',$highlight);
					}
				}
				elseif($db->num_rows($db->simple_select(BACKUPTABLE_PREFIX.'threads','tid','tid='.$poll['tid']))==1)
				{
					$itable->construct_cell('<a href="'.$sub_tabs['undodelete_threads']['link'].'&amp;highlight='.$poll['tid'].'" title="'.$poll['tid'].'"><img src="styles/'.$page->style.'/images/icons/custom.gif" alt="[deleted]" style="vertical-align:middle;" /></a>',$highlight);
					$lock=$poll['pid'];
				}
				else
				{
					$itable->construct_cell('<img src="styles/'.$page->style.'/images/icons/cross.gif" alt="[unavailabe]" title="'.$poll['tid'].'" style="vertical-align:middle;" />',$highlight);
					$lock=$poll['pid'];
				}
				$itable->construct_cell('<strong>'.htmlspecialchars_uni($poll['question']).'</strong>',$highlight);
				$itable->construct_cell($lang->sprintf($lang->undodelete_dateline,my_date($mybb->settings['dateformat'],$poll['dateline']),my_date($mybb->settings['timeformat'],$poll['dateline'])),$highlight);
				$popup=new PopupMenu('poll_'.$poll['pid'],$lang->options);
				if($lock!=$poll['pid'])
				{
					$popup->add_item($lang->undodelete_restore_backup,$sub_tabs['undodelete_polls']['link'].'&amp;restore='.$poll['pid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_restore_backup_question.'\')');
				}
				$popup->add_item($lang->undodelete_delete_backup,$sub_tabs['undodelete_polls']['link'].'&amp;delete='.$poll['pid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_delete_backup_question.'\')');
				$itable->construct_cell($popup->fetch(),$highlight);
				$itable->construct_row();
			}
		}
		else
		{
			$itable->construct_cell($lang->undodelete_no_backups,array('colspan'=>5));
			$itable->construct_row();
		}
		$itable->output($lang->undodelete_polls_table);
		echo <<<LEGEND
<fieldset>
<legend>$lang->legend</legend>
<img src="styles/$page->style/images/icons/world.gif" alt="[availabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_thread_available<br />
<img src="styles/$page->style/images/icons/custom.gif" alt="[deleted]" style="vertical-align:middle;" /> $lang->undodelete_legend_backup_available<br />
<img src="styles/$page->style/images/icons/warning.gif" alt="[warning]" style="vertical-align:middle;" /> $lang->undodelete_legend_poll_new<br />
<img src="styles/$page->style/images/icons/cross.gif" alt="[unavailabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_thread_unavailable<br />
</fieldset>
LEGEND;
		$page->output_footer();
	}
	if($mybb->input['action']=='attachments')
	{
		if($errors)
		{
			flash_message($lang->undodelete_update_error,'error');
			admin_redirect($sub_tabs['undodelete_update']['link']);
		}
		if($mybb->input['restore'])
		{
			if(undodelete_restore_attachment(intval($mybb->input['restore'])))
			{
				flash_message($lang->undodelete_restore_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_restore_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_attachments']['link']);
		}
		if($mybb->input['delete'])
		{
			if(undodelete_trash_attachment(intval($mybb->input['delete'])))
			{
				flash_message($lang->undodelete_delete_success,'success');
			}
			else
			{
				flash_message($lang->undodelete_delete_error,'error');
			}
			admin_redirect($sub_tabs['undodelete_attachments']['link']);
		}
		if($mybb->input['view'])
		{
			$query=$db->simple_select(BACKUPTABLE_PREFIX.'attachments','filename,filesize,attachname','aid='.intval($mybb->input['view']));
			if($db->num_rows($query)==1)
			{
				$attachment=$db->fetch_array($query);
				$attachment['filename']=ltrim(basename(' '.$attachment['filename']));
				header('Content-type: application/force-download');
				header('Content-disposition: attachment; filename="'.$attachment['filename'].'"');
				header('Content-length: '.$attachment['filesize']);
				echo file_get_contents('../'.$mybb->settings['uploadspath'].'/'.$attachment['attachname'].'.backup');
				exit();
			}
		}
		$page->add_breadcrumb_item($lang->undodelete_info_name,$sub_tabs['undodelete']['link']);
		$page->add_breadcrumb_item($sub_tabs['undodelete_attachments']['title']);
		$page->output_header($lang->undodelete_info_name.' - '.$sub_tabs['undodelete_attachments']['title']);
		$page->output_nav_tabs($sub_tabs,'undodelete_attachments');
		$itable=new Table;
		$itable->construct_header($lang->undodelete_attachments_table_id);
		$itable->construct_header($lang->undodelete_attachments_table_post);
		$itable->construct_header($lang->undodelete_attachments_table_filename);
		$itable->construct_header($lang->undodelete_attachments_table_author);
		$itable->construct_header($lang->undodelete_attachments_table_date);
		$itable->construct_header($lang->controls);
		$query=$db->simple_select(BACKUPTABLE_PREFIX.'attachments','*','',array('order_by'=>'pid','order_dir'=>'desc'));
		if($db->num_rows($query)>0)
		{
			while($attachment=$db->fetch_array($query))
			{
				if($mybb->input['highlight']==$attachment['aid'])
				{
					$highlight=array('style'=>'background-color:#fffbd9');
				}
				else
				{
					$highlight='';
				}
				$itable->construct_cell($attachment['aid'],$highlight);
				$post=get_post($attachment['pid']);
				if($post)
				{
					$itable->construct_cell('<a href="'.$mybb->settings['bburl'].'/'.get_post_link($post['pid'],$post['tid']).'#pid'.$post['pid'].'" title="'.htmlspecialchars_uni($post['subject']).'" target="_blank"><img src="styles/'.$page->style.'/images/icons/world.gif" alt="[available]" style="vertical-align:middle;" /></a>',$highlight);
				}
				elseif($db->num_rows($db->simple_select(BACKUPTABLE_PREFIX.'posts','pid','pid='.$attachment['pid']))==1)
				{
					$itable->construct_cell('<a href="'.$sub_tabs['undodelete_posts']['link'].'&amp;highlight='.$attachment['pid'].'" title="'.$attachment['pid'].'"><img src="styles/'.$page->style.'/images/icons/custom.gif" alt="[deleted]" style="vertical-align:middle;" /></a>',$highlight);
					$lock=$attachment['aid'];
				}
				else
				{
					$itable->construct_cell('<img src="styles/'.$page->style.'/images/icons/cross.gif" alt="[unavailabe]" title="'.$attachment['pid'].'" style="vertical-align:middle;" />',$highlight);
					$lock=$attachment['aid'];
				}
				$itable->construct_cell('<strong>'.htmlspecialchars_uni($attachment['filename']).'</strong>',$highlight);
				$user=get_user($attachment['uid']);
				$itable->construct_cell(build_profile_link(format_name($user['username'],$user['usergroup'],$user['displaygroup']),$attachment['uid'],'_blank'),$highlight);
				$itable->construct_cell($lang->sprintf($lang->undodelete_dateline,my_date($mybb->settings['dateformat'],$attachment['dateuploaded']),my_date($mybb->settings['timeformat'],$attachment['dateuploaded'])),$highlight);
				$popup=new PopupMenu('attachment_'.$attachment['aid'],$lang->options);
				if($lock!=$attachment['aid'])
				{
					$popup->add_item($lang->undodelete_restore_backup,$sub_tabs['undodelete_attachments']['link'].'&amp;restore='.$attachment['aid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_restore_backup_question.'\')');
				}
				$popup->add_item($lang->undodelete_attachments_control_view,$sub_tabs['undodelete_attachments']['link'].'&amp;view='.$attachment['aid']);
				$popup->add_item($lang->undodelete_delete_backup,$sub_tabs['undodelete_attachments']['link'].'&amp;delete='.$attachment['aid'].'&amp;my_post_key='.$mybb->post_code,'return AdminCP.deleteConfirmation(this,\''.$lang->undodelete_delete_backup_question.'\')');
				$itable->construct_cell($popup->fetch(),$highlight);
				$itable->construct_row();
			}
		}
		else
		{
			$itable->construct_cell($lang->undodelete_no_backups,array('colspan'=>6));
			$itable->construct_row();
		}
		$itable->output($lang->undodelete_attachments_table);
		echo <<<LEGEND
<fieldset>
<legend>$lang->legend</legend>
<img src="styles/$page->style/images/icons/world.gif" alt="[availabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_post_available<br />
<img src="styles/$page->style/images/icons/custom.gif" alt="[deleted]" style="vertical-align:middle;" /> $lang->undodelete_legend_backup_available<br />
<img src="styles/$page->style/images/icons/cross.gif" alt="[unavailabe]" style="vertical-align:middle;" /> $lang->undodelete_legend_post_unavailable<br />
</fieldset>
LEGEND;
		$page->output_footer();
	}
	if($mybb->input['action']=='update')
	{
		if(!$errors)
		{
			flash_message($lang->undodelete_update_success,'success');
			admin_redirect($sub_tabs['undodelete']['link']);
		}
		$page->add_breadcrumb_item($lang->undodelete_info_name,$sub_tabs['undodelete']['link']);
		$page->add_breadcrumb_item($sub_tabs['undodelete_update']['title']);
		$page->output_header($lang->undodelete_info_name.' - '.$sub_tabs['undodelete_update']['title']);
		$page->output_nav_tabs($sub_tabs,'undodelete_update');
		foreach($errors as $error)
		{
			undodelete_compare_table($error['0']);
		}
		$page->output_footer();
	}
	exit;
}

function undodelete_backup_afile($attachname,$thumbnail)
{
	global $mybb;
	@copy($mybb->settings['uploadspath'].'/'.$attachname,$mybb->settings['uploadspath'].'/'.$attachname.'.backup');
	if(!empty($thumbnail))
	{
		@copy($mybb->settings['uploadspath'].'/'.$thumbnail,$mybb->settings['uploadspath'].'/'.$thumbnail.'.backup');
	}
}

function undodelete_backup_attachment($aid)
{
	if(defined('IN_ADMINCP'))
	{
		return false;
	}
	global $db;
	if(!undodelete_check_table('attachments'))
	{
		$query=$db->simple_select('attachments','*','aid='.$aid['aid']);
		$result=$db->fetch_array($query);
		array_walk($result,'undodelete_clean_query');
		$db->insert_query(BACKUPTABLE_PREFIX.'attachments',$result);
		undodelete_backup_afile($aid['attachname'],$aid['thumbnail']);
	}
}

function undodelete_backup_poll($pid)
{
	global $db;
	if(empty($pid))
	{
		return false;
	}
	if(!undodelete_check_table('polls')&&!undodelete_check_table('pollvotes'))
	{
		$query=$db->simple_select('polls','*','pid='.$pid);
		$result=$db->fetch_array($query);
		array_walk($result,'undodelete_clean_query');
		$db->insert_query(BACKUPTABLE_PREFIX.'polls',$result);
		$query=$db->simple_select('pollvotes','*','pid='.$pid);
		while($vote=$db->fetch_array($query))
		{
			array_walk($vote,'undodelete_clean_query');
			$db->insert_query(BACKUPTABLE_PREFIX.'pollvotes',$vote);
		}
	}
}

function undodelete_backup_post($pid)
{
	global $db;
	if(!undodelete_check_table('posts'))
	{
		$query=$db->simple_select('posts','*','pid='.$pid);
		$result=$db->fetch_array($query);
		array_walk($result,'undodelete_clean_query');
		$db->insert_query(BACKUPTABLE_PREFIX.'posts',$result);
	}
}

function undodelete_backup_thread($tid)
{
	global $db;
	if(!undodelete_check_table('threads')&&!undodelete_check_table('threadsubscriptions'))
	{
		$query=$db->simple_select('threads','*','tid='.$tid);
		$result=$db->fetch_array($query);
		array_walk($result,'undodelete_clean_query');
		$db->insert_query(BACKUPTABLE_PREFIX.'threads',$result);
		$query=$db->simple_select('threadsubscriptions','*','tid='.$tid);
		while($subscription=$db->fetch_array($query))
		{
			array_walk($subscription,'undodelete_clean_query');
			$db->insert_query(BACKUPTABLE_PREFIX.'threadsubscriptions',$subscription);
		}
	}
	$query=$db->simple_select('posts','pid','tid='.$tid);
	while($post=$db->fetch_array($query))
	{
		undodelete_backup_post($post['pid']);
	}
	$poll=$db->fetch_array($query=$db->simple_select('polls','pid','tid='.$tid));
	undodelete_backup_poll($poll['pid']);
}

function undodelete_restore_thread($tid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'threads','*','tid='.$tid);
	if($db->num_rows($query)==1)
	{
		$thread=$db->fetch_array($query);
		array_walk($thread,'undodelete_clean_query');
		$db->insert_query('threads',$thread);
		$db->delete_query(BACKUPTABLE_PREFIX.'threads','tid='.$thread['tid']);
		$query=$db->simple_select(BACKUPTABLE_PREFIX.'threadsubscriptions','*','tid='.$thread['tid']);
		while($subscription=$db->fetch_array($query))
		{
			array_walk($subscription,'undodelete_clean_query');
			$db->insert_query('threadsubscriptions',$subscription);
		}
		$db->delete_query(BACKUPTABLE_PREFIX.'threadsubscriptions','tid='.$thread['tid']);
		$db->update_query('threads',array('poll'=>0),'tid='.$thread['tid']);
		rebuild_thread_counters($thread['tid']);
		rebuild_forum_counters($thread['fid']);
		return true;
	}
	return false;
}

function undodelete_trash_thread($tid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'threads','*','tid='.$tid);
	if($db->num_rows($query)==1)
	{
		$thread=$db->fetch_array($query);
		$db->delete_query(BACKUPTABLE_PREFIX.'threads','tid='.$thread['tid']);
		$db->delete_query(BACKUPTABLE_PREFIX.'threadsubscriptions','tid='.$thread['tid']);
		return true;
	}
	return false;
}

function undodelete_restore_post($pid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'posts','*','pid='.$pid);
	if($db->num_rows($query)==1)
	{
		$post=$db->fetch_array($query);
		array_walk($post,'undodelete_clean_query');
		$db->insert_query('posts',$post);
		$db->delete_query(BACKUPTABLE_PREFIX.'posts','pid='.$post['pid']);
		rebuild_thread_counters($post['tid']);
		$thread=get_thread($post['tid']);
		rebuild_forum_counters($thread['fid']);
		undelete_recount_user_posts($post['uid']);
		return true;
	}
	return false;
}

function undodelete_trash_post($pid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'posts','*','pid='.$pid);
	if($db->num_rows($query)==1)
	{
		$post=$db->fetch_array($query);
		$db->delete_query(BACKUPTABLE_PREFIX.'posts','pid='.$post['pid']);
		return true;
	}
	return false;
}

function undodelete_restore_poll($pid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'polls','*','pid='.$pid);
	if($db->num_rows($query)==1)
	{
		$poll=$db->fetch_array($query);
		array_walk($poll,'undodelete_clean_query');
		$db->insert_query('polls',$poll);
		$db->delete_query(BACKUPTABLE_PREFIX.'polls','pid='.$poll['pid']);
		$query=$db->simple_select(BACKUPTABLE_PREFIX.'pollvotes','*','pid='.$poll['pid']);
		while($vote=$db->fetch_array($query))
		{
			array_walk($vote,'undodelete_clean_query');
			$db->insert_query('pollvotes',$vote);
		}
		$db->delete_query(BACKUPTABLE_PREFIX.'pollvotes','pid='.$poll['pid']);
		$db->update_query('threads',array('poll'=>$poll['pid']),'tid='.$poll['tid']);
		return true;
	}
	return false;
}

function undodelete_trash_poll($pid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'polls','*','pid='.$pid);
	if($db->num_rows($query)==1)
	{
		$poll=$db->fetch_array($query);
		$db->delete_query(BACKUPTABLE_PREFIX.'polls','pid='.$poll['pid']);
		$db->delete_query(BACKUPTABLE_PREFIX.'pollvotes','pid='.$poll['pid']);
		return true;
	}
	return false;
}

function undodelete_restore_attachment($aid)
{
	global $mybb,$db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'attachments','*','aid='.$aid);
	if($db->num_rows($query)==1)
	{
		$attachment=$db->fetch_array($query);
		array_walk($attachment,'undodelete_clean_query');
		$db->insert_query('attachments',$attachment);
		$db->delete_query(BACKUPTABLE_PREFIX.'attachments','aid='.$attachment['aid']);
		@rename('../'.$mybb->settings['uploadspath'].'/'.$attachment['attachname'].'.backup','../'.$mybb->settings['uploadspath'].'/'.$attachment['attachname']);
		if(!empty($attachment['thumbnail']))
		{
			@rename('../'.$mybb->settings['uploadspath'].'/'.$attachment['thumbnail'].'.backup','../'.$mybb->settings['uploadspath'].'/'.$attachment['thumbnail']);
		}
		$post=get_post($attachment['pid']);
		rebuild_thread_counters($post['tid']);
		return true;
	}
	return false;
}

function undodelete_trash_attachment($aid)
{
	global $mybb,$db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'attachments','*','aid='.$aid);
	if($db->num_rows($query)==1)
	{
		$attachment=$db->fetch_array($query);
		$db->delete_query(BACKUPTABLE_PREFIX.'attachments','aid='.$attachment['aid']);
		@unlink('../'.$mybb->settings['uploadspath'].'/'.$attachment['attachname'].'.backup');
		if($attachment['thumbnail'])
		{
			@unlink('../'.$mybb->settings['uploadspath'].'/'.$attachment['thumbnail'].'.backup');
		}
		$date_directory=explode('/',$attachment['attachname']);
		if(@is_dir('../'.$mybb->settings['uploadspath'].'/'.$date_directory[0]))
		{
			@rmdir('../'.$mybb->settings['uploadspath'].'/'.$date_directory[0]);
		}
		return true;
	}
	return false;
}

function undodelete_restore_all($tid)
{
	global $db;
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'polls','*','tid='.$tid);
	if(!undodelete_restore_thread($tid))
	{
		return false;
	}
	if($db->num_rows($query)==1)
	{
		$poll=$db->fetch_array($query);
		if(!undodelete_restore_poll($poll['pid']))
		{
			return false;
		}
	}
	$query=$db->simple_select(BACKUPTABLE_PREFIX.'posts','*','tid='.$tid);
	while($post=$db->fetch_array($query))
	{
		if(!undodelete_restore_post($post['pid']))
		{
			return false;
		}
		$query2=$db->simple_select(BACKUPTABLE_PREFIX.'attachments','*','pid='.$post['pid']);
		while($attachment=$db->fetch_array($query2))
		{
			if(!undodelete_restore_attachment($attachment['aid']))
			{
				return false;
			}
		}
	}
	return true;
}

function undelete_recount_user_posts($uid)
{
	global $db;
	$query=$db->simple_select('forums','fid','usepostcounts=0');
	while($forum=$db->fetch_array($query))
	{
		$fids[]=$forum['fid'];
	}
	if(is_array($fids))
	{
		$fids=implode(',',$fids);
	}
	if($fids)
	{
		$fids=' AND fid NOT IN('.$fids.')';
	}
	else
	{
		$fids='';
	}
	$query=$db->simple_select('posts','COUNT(pid) AS post_count','uid='.$uid.' AND visible>0'.$fids);
	$num_posts=$db->fetch_field($query,'post_count');
	$db->update_query('users',array('postnum'=>$num_posts),'uid='.$uid);
}

?>