<?php
/*
转换附件
pre_forum_attachment
pre_forum_attachmentfield
*/

if($start <= 1) {
	truncatetable('forum_attachment');
	for($i = 0; $i < 10; $i ++) {
		truncatetable('forum_attachment_'.$i);
	}
	validid('aid', 'attachments');
}

$query = $xc->db['source']->query("SELECT * FROM {$source_tablepre}attachments WHERE (aid BETWEEN $start AND $end)") or die("检索数据表 '{$source_tablepre}attachments' 错误！请将表 '{$source_tablepre}attachments' 字段类型为 nText 的改为 Text 类型。");

while ($a = $xc->db['source']->fetch_assoc($query)) {
	
	$a				= daddslashes(array_change_key_case($a));

	$aid			= $a['aid'];
	$tid			= $a['tid'];
	$pid			= $a['pid'];
	$uid			= $a['uid'];
	$downloads		= $a['downloads'];
	$atid			=	(string)$tid;
	$tableid		=	$atid{strlen($atid)-1};

	
	$filetype		= $a['filetype'];
	$dateline		= timetounix($a['postdatetime']);
	$filename		= $a['attachment'];
	$filesize		= $a['filesize'];
	$attachment		= str_replace('\\\\', '/', $a['filename']);
	$remote			= 0;
	$description	= $a['description'];
	$readperm		= $a['readperm'];
	$price			= $a['attachprice'];
	$isimage		= in_array($filetype, array('image/pjpeg', 'image/gif', 'image/bmp', 'image/png')) ? 1 : 0;
	$width			= $a['width'];
	$thumb			= 0;
	

	$field1			=	array('aid','tid','pid','uid','tableid','downloads');
	$query1			=	getinsertsql("{$discuz_tablepre}forum_attachment", $field1);

	$query2			=	"UPDATE {$discuz_tablepre}forum_thread SET attachment=1 WHERE tid='$tid'";
	
	$field3			=	array('aid','tid','pid','uid','dateline','filename','filesize','attachment','remote','description','readperm','price','isimage','width','thumb');
	$query3			=	getinsertsql("{$discuz_tablepre}forum_attachment_{$tableid}", $field3);

	if($xc->db['discuz']->query($query1)) {
		$xc->db['discuz']->query($query2);
		if($xc->db['discuz']->query($query3)){
			$convertedrows ++;
		} else {
			$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}forum_attachment WHERE aid='$aid'");
			$xc->db['discuz']->query("UPDATE {$discuz_tablepre}forum_thread SET attachment=0 WHERE tid='$tid'");
			reportlog("无法转换附件扩展表 $filename ");
		}
	} else {
		reportlog("无法转换附件 $filename ");
	}
	$converted = 1;
	$totalrows ++;
	$url = 'index.php?mod=dealdata&step='.$step.'&start='.($a['aid']+1).'&stay='.$stay.'&totalrows='.$totalrows.'&convertedrows='.$convertedrows.'&sqlfilenum='.$sqlfilenum;
	file_put_contents(XCONVERT_ROOT.'./cache/lock/progress_'.$step.".txt", $url);
}

if($converted || $end < $maxid) {
	altertable('forum_attachment', 'aid');
	altertable('forum_attachmentfield', 'aid');
}

?>