<?php
/**
 *    attachment
 */

if($start <= 1 && $tableid == 0) {
	truncatetable('forum_attachment');
	for($i = 0; $i < 10; $i ++) {
		truncatetable('forum_attachment_'.$i);
	}
	$sqlfilenum = 0;
	$extrastr = '';
}

$sqlfilenum ++;
$extrastr = '&sqlfilenum='.$sqlfilenum;

$maxaid = $xc->db['source']->result($xc->db['source']->query("SELECT max(aid) FROM {$source_tablepre}attachs"), 0);
if($start < $maxaid){
	$converted = 1;
}

$query = $xc->db['source']->query("SELECT * FROM {$source_tablepre}attachs WHERE aid >= $start AND aid < $start + $rpp") or dexit();
while ($attach = $xc->db['source']->fetch_array($query)) {
	$attach			=	daddslashes($attach);
	
	//pre_forum_attachment
	$aid			=	$attach['aid'];
	$tid			=	$attach['tid'];
	$pid			=	$attach['pid'];
	$uid			=	$attach['uid'];
	$downloads		=	$attach['hits'];
	$atid			=	(string)$tid;
	$tableid		=	$atid{strlen($atid)-1};

	//pre_forum_attachment_X
	$dateline		=	$attach['uploadtime'];
	$filename		=	daddslashes(cutstr(htmlspecialchars(trim($attach['name'])), 100));
	$filesize		=	intval($attach['size']) * 1024;
	$attachment		=	'pw/'.$attach['attachurl'];
	$remote			=	0;
	$description	=	daddslashes(cutstr(htmlspecialchars(trim($attach['descrip'])), 100));
	$readperm		=	0;
	$price			=	0;
	$filetype		=	getfiletype($attach['name']);
	$isimage		=	in_array($filetype, array('image/pjpeg', 'image/gif', 'image/bmp', 'image/png')) ? 1 : 0;
	$width			=	0;
	$thumb			=	0;
	
	$field1			=	array('aid','tid','pid','uid','tableid','downloads');
	$query1			=	getinsertsql("{$discuz_tablepre}forum_attachment", $field1);
	$field2			=	array('aid','tid','pid','uid','dateline','filename','filesize','attachment','remote','description','readperm','price','isimage','width','thumb');
	$query2			=	getinsertsql("{$discuz_tablepre}forum_attachment_{$tableid}", $field2);
	
	if($xc->config['info']['convert_type'] == 'file') {
		writesql('forum_attachment', $sqlfilenum, $query1);
		writesql("forum_attachment_{$tableid}", $sqlfilenum, $query2);
		$convertedrows ++;
	} else {
		if($xc->db['discuz']->query($query1)) {
			if($xc->db['discuz']->query($query2)) {
				$convertedrows++;
			} else {
				$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}forum_attachment WHERE aid='$aid'");
				reportlog("无法转换附件内容 aid = $aid filename = '$filename'");
			}
		} else {
			reportlog("无法转换附件 aid = $aid filename = '$filename'");
		}
	}
	$converted = 1;
	$totalrows ++;
}
?>