<?php
/**
 * @version $Id: attachment.inc.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

/**
 * 删除附件
 * 
 * @param Array $condition 附件查询条件 array('字段'=>值)
 */
function delAttachment($condition = 0)
{
	global $DB, $db_prefix;
	$DB->db_query("SELECT filepath FROM {$db_prefix}attachments WHERE {$condition}");
	while ($attachment = $DB->db_fetch_array())
	{
		PDel(PBDIGG_ROOT.'attachments/'.$attachment['filepath']);
	}
	$DB->db_query("DELETE FROM {$db_prefix}attachments WHERE {$condition}");
	return TRUE;
}

/**
 * 修改附件所属分类
 */
function updateAttFID($ncid, $ocid) {
	global $oDB, $db_prefix;
	$querySQL = "UPDATE `".$db_prefix."attachments` SET `cid` = '".intval($ncid)."' WHERE `cid` = '".intval($ocid)."'";
	if ($oDB->db_query($querySQL, 0) !== false) {
		return true;
	}
	return false;
}

/**
 * 附件类型图片
 */
function attachtype($type)
{
	global $_PBENV;
	if(preg_match("/^torrent$/", $type))
	{
		$attachicon = 'torrent';
	}
	elseif (preg_match("/^pdf$/", $type))
	{
		$attachicon = 'pdf';
	}
	elseif (preg_match("/^(jpg|jpeg|gif|png|bmp)$/", $type))
	{
		$attachicon = 'img';
	}
	elseif (preg_match("/^(swf|fla|swi)$/", $type))
	{
		$attachicon = 'flash';
	}
	elseif (preg_match("/^(wav|mid|mp3|m3u|wma|asf|asx|vqf|mpg|mpeg|avi|wmv)$/", $type))
	{
		$attachicon = 'wmv';
	}
	elseif (preg_match("/^(ra|rmvb|rm|rv)$/", $type))
	{
		$attachicon = 'rm';
	}
	elseif (preg_match("/^(txt|rtf|wri|chm)$/", $type))
	{
		$attachicon = 'txt';
	}
	elseif (preg_match("/^doc$/", $type))
	{
		$attachicon = 'doc';
	}
	elseif (preg_match("/^xls$/", $type))
	{
		$attachicon = 'xls';
	}
	elseif (preg_match("/^(rar|zip|arj|arc|cab|lzh|lha|tar|gz)$/", $type))
	{
		$attachicon = 'zip';
	}
	else
	{
		$attachicon = 'unknow';
	}
	return '<img src="'.$_PBENV['PB_URL'].'images/file/'.$attachicon.'.gif" border="0" class="attachicon" alt="'.$attachicon.'" />';
}

/**
 * 图片混排
 */
function attachment($content)
{
	return preg_replace('/\[attachment=(\d+?)\]/ie', "repatta('\\1')", $content);
}
function repatta($id)
{
	global $ainfo, $_PBENV, $onload;
	if ($ainfo[$id])
	{
		$atta = &$ainfo[$id];
		$url = $_PBENV['PB_URL'].($atta['filesize'] > 8388608 ? 'attachment/'.$atta['filepath'] : 'attachments.php?aid='.$atta['aid']);
		$extension = strtolower(Fext($atta['filename']));
		if ($atta['isimg'] && in_array($extension, array('jpg', 'jpeg', 'gif', 'png', 'bmp')))
		{
			$attachimg = '<a href="'.$url.'" title="'.htmlspecialchars($atta['filename']).'" rel="gallery" class="thickbox attachimg"><img src="'.$url.'"'.$onload.' class="previewimg" /></a>';
		}
		else
		{
			$attachimg = '<span class="attachother">'.attachtype($extension).' <a href="'.$url.'" target="_blank" title="'.$atta['filename'].'">'.$atta['filename'].'</a></span>';
		}
		unset($GLOBALS['ainfo'][$id]);
		return $attachimg;
	}
}
?>
