<?php
# -- BEGIN LICENSE BLOCK ----------------------------------
#
# This file is part of Dotclear 2.
#
# Copyright (c) 2003-2008 Olivier Meunier and contributors
# Licensed under the GPL version 2.0 license.
# See LICENSE file or
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
#
# -- END LICENSE BLOCK ------------------------------------
if (!defined('DC_CONTEXT_ADMIN')) { return; }

require dirname(__FILE__).'/class.backupFile.php';
require dirname(__FILE__).'/class.dc.import.php';
require dirname(__FILE__).'/class.db.export.php';

# Export all content
if (!empty($_POST['export_all']) && $core->auth->isSuperAdmin())
{
	ob_end_clean();
	header('Content-Disposition: attachment;filename=blog-backup.txt');
	header('Content-Type: text/plain; charset=UTF-8');
	
	$exp = new dbExport($core->con,'php://output',$core->prefix);
	
	fwrite($exp->fp,'///DOTCLEAR|'.DC_VERSION."|full\n");
	$exp->exportTable('blog');
	$exp->exportTable('category');
	$exp->exportTable('link');
	$exp->exportTable('setting');
	$exp->exportTable('user');
	$exp->exportTable('permissions');
	$exp->exportTable('post');
	$exp->exportTable('media');
	$exp->exportTable('post_media');
	$exp->exportTable('log');
	$exp->exportTable('ping');
	$exp->exportTable('comment');
	$exp->exportTable('spamrule');
	$exp->exportTable('version');
	
	# --BEHAVIOR-- exportFull
	$core->callBehavior('exportFull',$core,$exp);
	
	exit;
}

# Export a blog
if (!empty($_POST['blog_export']) && $core->auth->check('admin',$_POST['blog_export']))
{
	ob_end_clean();
	
	$blog_id = $_POST['blog_export'];
	
	if (!in_array($blog_id,array_keys($core->blogs))) {
		exit;
	}
	
	$core->setBlog($blog_id);
	$blog_id = $core->con->escape($blog_id);
	
	header('Content-Disposition: attachment;filename='.$core->blog->id.'-backup.txt');
	header('Content-Type: text/plain; charset=UTF-8');
	
	$exp = new dbExport($core->con,'php://output',$core->prefix);
	fwrite($exp->fp,'///DOTCLEAR|'.DC_VERSION."|single\n");
	
	$exp->export('category',
		'SELECT * FROM '.$core->prefix.'category '.
		"WHERE blog_id = '".$blog_id."'"
	);
	$exp->export('link',
		'SELECT * FROM '.$core->prefix.'link '.
		"WHERE blog_id = '".$blog_id."'"
	);
	$exp->export('setting',
		'SELECT * FROM '.$core->prefix.'setting '.
		"WHERE blog_id = '".$blog_id."'"
	);
	$exp->export('post',
		'SELECT * FROM '.$core->prefix.'post '.
		"WHERE blog_id = '".$blog_id."'"
	);
	$exp->export('media',
		'SELECT * FROM '.$core->prefix."media WHERE media_path = '".
		$core->con->escape($core->blog->settings->public_path)."'"
	);
	$exp->export('post_media',
		'SELECT media_id, M.post_id '.
		'FROM '.$core->prefix.'post_media M, '.$core->prefix.'post P '.
		'WHERE P.post_id = M.post_id '.
		"AND P.blog_id = '".$blog_id."'"
	);
	$exp->export('ping',
		'SELECT ping.post_id, ping_url, ping_dt '.
		'FROM '.$core->prefix.'ping ping, '.$core->prefix.'post P '.
		'WHERE P.post_id = ping.post_id '.
		"AND P.blog_id = '".$blog_id."'"
	);
	$exp->export('comment',
		'SELECT C.* '.
		'FROM '.$core->prefix.'comment C, '.$core->prefix.'post P '.
		'WHERE P.post_id = C.post_id '.
		"AND P.blog_id = '".$blog_id."'"
	);
	
	# --BEHAVIOR-- exportSingle
	$core->callBehavior('exportSingle',$core,$exp,$blog_id);
	exit;
}

# Getting files in public directory
$public_files = array('-' => '');
$dir = @dir($core->blog->public_path);
if ($dir)
{
	while (($entry = $dir->read()) !== false) {
		$entry_path = $dir->path.'/'.$entry;
		
		if (is_file($entry_path) && is_readable($entry_path))
		{
			$fp = fopen($entry_path,'rb');
			if (strpos(fgets($fp),'///DOTCLEAR|') === 0) {
				$public_files[$entry] = $entry_path;
			}
			fclose($fp);
		}
	}
}


# Loading a single blog
$single_upl = null;

if (!empty($_POST['public_single_file']) && in_array($_POST['public_single_file'],$public_files)) {
	$single_upl = false;
}
elseif(!empty($_FILES['up_single_file'])) {
	$single_upl = true;
}

if ($single_upl !== null)
{
	try
	{
		if ($single_upl) {
			files::uploadStatus($_FILES['up_single_file']);
			$file = $_FILES['up_single_file']['tmp_name'];
		} else {
			$file = $_POST['public_single_file'];
		}
		
		$bk = new dcImport($core,$file);
		$bk->importSingle();
		http::redirect($p_url.'&imported=1');
	}
	catch (Exception $e)
	{
		$core->error->add($e->getMessage());
	}
}


# Loading a full export file
$full_upl = null;

if (!empty($_POST['public_full_file']) && in_array($_POST['public_full_file'],$public_files)) {
	$full_upl = false;
}
elseif(!empty($_FILES['up_full_file'])) {
	$full_upl = true;
}

if ($full_upl !== null && $core->auth->isSuperAdmin())
{
	try
	{
		if (empty($_POST['your_pwd']) || !$core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY,$_POST['your_pwd']))) {
			throw new Exception(__('Password verification failed'));
		}
		
		if ($full_upl) {
			files::uploadStatus($_FILES['up_full_file']);
			$file = $_FILES['up_full_file']['tmp_name'];
		} else {
			$file = $_POST['public_full_file'];
		}
		
		$bk = new dcImport($core,$file);
		$bk->importFull();
		http::redirect($p_url.'&imported=1');
	}
	catch (Exception $e)
	{
		$core->error->add($e->getMessage());
	}
}

# Loading a feed
$feed_url = !empty($_POST['feed_url']) ? $_POST['feed_url'] : '';

if ($feed_url)
{
	try
	{
		$feed = feedReader::quickParse($feed_url);
		if ($feed === false) {
			throw new Exception(__('Cannot retrieve feed URL.'));
		}
		if (count($feed->items) == 0) {
			throw new Exception(__('No items in feed.'));
		}
		
		if ($core->plugins->moduleExists('metadata')) {
			$meta = new dcMeta($core);
		}
		
		$cur = $core->con->openCursor($core->prefix.'post');
		$core->con->begin();
		foreach ($feed->items as $item)
		{
			$cur->clean();
			$cur->user_id = $core->auth->userID();
			$cur->post_content = $item->content ? $item->content : $item->description;
			$cur->post_title = $item->title ? $item->title : text::cutString(html::clean($cur->post_content),60);
			$cur->post_format = 'xhtml';
			$cur->post_status = -2;
			$cur->post_dt = strftime('%Y-%m-%d %H:%M:%S',$item->TS);
			
			try {
				$post_id = $core->blog->addPost($cur);
			} catch (Exception $e) {
				$core->con->rollback();
				throw $e;
			}
			
			if (isset($meta))
			{
				foreach ($item->subject as $subject) {
					$meta->setPostMeta($post_id,'tag',dcMeta::sanitizeMetaID($subject));
				}
			}
		}
		
		$core->con->commit();
		http::redirect($p_url.'&imported=1');
	}
	catch (Exception $e)
	{
		$core->error->add($e->getMessage());
	}
}

?>
<html>
<head>
  <title><?php echo __('Import/Export'); ?></title>
  <script type="text/javascript">
  //<![CDATA[
  <?php echo dcPage::jsVar('dotclear.msg.confirm_full_import',
  			__('Are you sure you want to import a full backup file?')); ?>
  $(function() {
	  $('#up_single_file').change(function() {
		  if (this.value != '') { $('#public_single_file').val(''); }
	  });
	  $('#public_single_file').change(function() {
		  if (this.value != '') { $('#up_single_file').val(''); }
	  });
	  
	  $('#up_full_file').change(function() {
		  if (this.value != '') { $('#public_full_file').val(''); }
	  });
	  $('#public_full_file').change(function() {
		  if (this.value != '') { $('#up_full_file').val(''); }
	  });
	  $('#formfull').submit(function() {
		  return window.confirm(dotclear.msg.confirm_full_import);
	  });
  });
  //]]>
  </script>
  <?php echo dcPage::jsPageTabs(); ?>
</head>

<body>
<?php
if (!empty($_GET['imported'])) {
	echo '<p class="message">'.__('Content successfully imported.').'</p>';
}

echo '<h2>'.__('Import/Export').'</h2>';

echo '<div class="multi-part" title="'.__('Import').'">';

echo
'<h3>'.__('Import a single blog').'</h3>'.
'<p>'.sprintf(__('This will import a single blog backup as new content in the current blog: %s.'),
'<strong>'.html::escapeHTML($core->blog->name).'</strong>').'</p>'.
'<form action="'.$p_url.'" method="post" enctype="multipart/form-data">'.

'<fieldset>'.
$core->formNonce().
form::hidden(array('MAX_FILE_SIZE'),DC_MAX_UPLOAD_SIZE).
'<p><label>'.__('Upload a backup file').' '.
'<input type="file" id="up_single_file" name="up_single_file" size="20" />'.
'</label></p>'.

'<p><label>'.__('or pick up a local file in your public directory').' '.
form::combo('public_single_file',$public_files).
'</label></p>'.
'<p><input type="submit" value="'.__('Send').'" /></p>'.
'</fieldset>'.
'</form>';

if ($core->auth->isSuperAdmin())
{
	echo
	'<h3>'.__('Import a full backup file').'</h3>'.
	'<form action="'.$p_url.'" method="post" enctype="multipart/form-data" id="formfull">'.
	'<div>'.form::hidden(array('MAX_FILE_SIZE'),DC_MAX_UPLOAD_SIZE).'</div>'.
	
	'<fieldset>'.
	$core->formNonce().
	form::hidden(array('MAX_FILE_SIZE'),DC_MAX_UPLOAD_SIZE).
	'<p><label>'.__('Upload a backup file').' '.
	'<input type="file" id="up_full_file" name="up_full_file" size="20" />'.
	'</label></p>'.
	
	'<p><label>'.__('or pick up a local file in your public directory').' '.
	form::combo('public_full_file',$public_files).
	'</label></p>'.
	
	'<p><strong>'.__('Warning: This will reset all the content of your database, except users.').'</strong></p>'.
	
	'<p><label>'.__('Your password:').
	form::password('your_pwd',20,255).'</label></p>'.
	
	'<p><input type="submit" value="'.__('Send').'" /></p>'.
	'</fieldset>'.
	'</form>';
}

echo
'<h3>'.__('Import from a feed').'</h3>'.
'<p>'.sprintf(__('This will import a feed (RSS or Atom) a as new content in the current blog: %s.'),
'<strong>'.html::escapeHTML($core->blog->name).'</strong>').'</p>'.
'<form action="'.$p_url.'" method="post">'.

'<fieldset>'.
$core->formNonce().
'<p><label>'.__('Feed URL:').' '.
form::field('feed_url',40,300,html::escapeHTML($feed_url)).'</label></p>'.
'<p><input type="submit" value="'.__('Send').'" /></p>'.
'</fieldset>'.
'</form>';

echo '</div>';

echo '<div class="multi-part" title="'.__('Export').'">';

if ($core->auth->isSuperAdmin())
{
	echo
	'<h3>'.__('Export all content').'</h3>'.
	'<form action="'.$p_url.'" method="post">'.
	'<p><input name="export_all" type="submit" value="'.__('Export all content').'" />'.
	$core->formNonce().'</p>'.
	'</form>';
}

echo '<h3>'.__('Export a blog').'</h3>';
$blogs_list = array();
foreach ($core->blogs as $k=>$v) {
	if ($core->auth->check('admin',$k)) {
		$blogs_list[html::escapeHTML($v['name']).' ('.$k.')'] = $k;
	}
}

echo
'<form action="'.$p_url.'" method="post">'.
'<p><label class="classic">'.__('Blog to export:').' '.
form::combo('blog_export',$blogs_list,$core->blog->id).'</label> '.
'<input type="submit" value="'.__('Export').'" />'.
$core->formNonce().'</p>'.
'</form>';

echo '</div>';
?>
</body>
</html>