<?php
@$vercode='';	//此处取值请自行修改

if(isset($_POST['vercode'])){
if ($_POST['vercode']!=$vercode){
	echo("[err]invalid vercode[/err]");
	exit();
}
}

define('IN_ADMIN', TRUE);
require dirname(__FILE__).'/include/admin/global.func.php';
//require dirname(__FILE__).'/include/common.inc.php';
//include/common.inc.php开始

//define('PHPCMS_ROOT', str_replace("\\", '/', substr(dirname(__FILE__), 0, -7)));
define('PHPCMS_ROOT', str_replace("\\", '/', dirname(__FILE__).'/'));
define('MICROTIME_START', microtime());
define('IN_PHPCMS', TRUE);
define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
define('TIME', time());
set_include_path(PHPCMS_ROOT.'include/');
set_magic_quotes_runtime(0);
unset($LANG, $HTTP_ENV_VARS, $HTTP_POST_VARS, $HTTP_GET_VARS, $HTTP_POST_FILES, $HTTP_COOKIE_VARS);

require 'config.inc.php';
require 'global.func.php';
require 'dir.func.php';
require 'url.func.php';
require 'output.class.php';
require 'priv_group.class.php';
require 'times.class.php';
require PHPCMS_ROOT.'languages/'.LANG.'/phpcms.lang.php';

ERRORLOG ? set_error_handler('phpcms_error') : error_reporting(E_ERROR | E_WARNING | E_PARSE);

define('IP', ip());
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
define('SCRIPT_NAME', isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : preg_replace("/(.*)\.php(.*)/i", "\\1.php", $_SERVER['PHP_SELF']));
define('QUERY_STRING', safe_replace($_SERVER['QUERY_STRING']));
define('PATH_INFO', isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '');
define('DOMAIN', isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : preg_replace("/([^:]*)[:0-9]*/i", "\\1", $_SERVER['HTTP_HOST']));
define('SCHEME', $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://');
define('SITE_URL', SCHEME.$_SERVER['HTTP_HOST'].PHPCMS_PATH);
define('RELATE_URL', isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : SCRIPT_NAME.(QUERY_STRING ? '?'.QUERY_STRING : PATH_INFO));
define('URL', SCHEME.$_SERVER['HTTP_HOST'].RELATE_URL);
define('RELATE_REFERER',urlencode(RELATE_URL));
define('CACHE_FORM', PHPCMS_ROOT.'data/formguide/');

if(function_exists('date_default_timezone_set')) date_default_timezone_set(TIMEZONE);
//header('Content-type: text/html; charset='.CHARSET);

if(CACHE_PAGE && !defined('IN_ADMIN')) cache_page_start();
if(GZIP && function_exists('ob_gzhandler'))
{
	ob_start('ob_gzhandler');
}
else
{
	ob_start();
}

$dbclass = 'db_'.DB_DATABASE;
require $dbclass.'.class.php';

$db = new $dbclass;
$db->connect(DB_HOST, DB_USER, DB_PW, DB_NAME, DB_PCONNECT, DB_CHARSET);

require 'session_'.SESSION_STORAGE.'.class.php';
$session = new session();
session_set_cookie_params(0, COOKIE_PATH, COOKIE_DOMAIN);

if($_REQUEST)
{
	if(MAGIC_QUOTES_GPC)
	{
		$_REQUEST = new_stripslashes($_REQUEST);
		if($_COOKIE) $_COOKIE = new_stripslashes($_COOKIE);
	}
	else
	{
		$_POST = new_addslashes($_POST);
		$_GET = new_addslashes($_GET);
		$_COOKIE = new_addslashes($_COOKIE);
		@extract($_POST);
		@extract($_GET);
		@extract($_COOKIE);
	}
	if(!defined('IN_ADMIN')) $_REQUEST = filter_xss($_REQUEST, ALLOWED_HTMLTAGS);
	extract($db->escape($_REQUEST), EXTR_SKIP);
	if($_COOKIE) $db->escape($_COOKIE);
}
if(QUERY_STRING && strpos(QUERY_STRING, '=') === false && preg_match("/^(.*)\.(htm|html|shtm|shtml)$/", QUERY_STRING, $urlvar))
{
	parse_str(str_replace(array('/', '-', ' '), array('&', '=', ''), $urlvar[1]));
}

$CACHE = cache_read('common.php');
if(!$CACHE)
{
	require_once 'cache.func.php';
	cache_all();
	$CACHE = cache_read('common.php');
}
extract($CACHE);
unset($CACHE);

if($PHPCMS['enable_ipbanned'] && ip_banned(IP)) showmessage($LANG['administrator_banned_this_IP']);
if(!defined('IN_ADMIN'))
{
	if(FILTER_ENABLE && filter_word()) showmessage('The content including illegal information: '.ILLEGAL_WORD.' .');
    if($PHPCMS['minrefreshtime'])
	{
		$cc = new times();
		$cc->set('cc', $PHPCMS['minrefreshtime'], 1);
		if($cc->check()) showmessage('Do not refresh the page in '.$PHPCMS['minrefreshtime'].' seconds!');
		$cc->add();
		unset($cc);
	}
    if(!isset($forward)) $forward = HTTP_REFERER;
}

$M = $TEMP = array();
if(!isset($mod)) $mod = 'phpcms';
if($mod != 'phpcms')
{
	isset($MODULE[$mod]) or exit($LANG['module_not_exists']);
	$langfile = defined('IN_ADMIN') ? $mod.'_admin' : $mod;
	@include PHPCMS_ROOT.'languages/'.LANG.'/'.$langfile.'.lang.php';
	$M = cache_read('module_'.$mod.'.php');
}

$_userid = 0;
$_username = '';
$_groupid = 3;
//$phpcms_auth = get_cookie('auth');
$action='add';
$dosubmit=true;
//ET增加登录验证

	require PHPCMS_ROOT.'languages/'.LANG.'/member.lang.php';
	require PHPCMS_ROOT.'member/include/member.class.php';
	$member = new member();
	$result = $member->login($username, $password);
	if(!$result)
	{
		exit("[err]invalid username or password[/err]");
	}
	@extract($result, EXTR_PREFIX_ALL, '');
	
	if($_groupid > 1)
	{
		exit("[err]you are not admin[/err]");
	}
	$_SESSION['is_admin'] = 1;
/*
if($phpcms_auth)
{
	$auth_key = md5(AUTH_KEY.$_SERVER['HTTP_USER_AGENT']);
	list($_userid, $_password) = explode("\t", phpcms_auth($phpcms_auth, 'DECODE', $auth_key));
	$_userid = intval($_userid);
	$sql_member = "SELECT * FROM `".DB_PRE."member_cache` WHERE `userid`=$_userid";
	$r = $db->get_one($sql_member);
	if(!$r && cache_member())
	{
		$r = $db->get_one($sql_member);
	}
	if($r && $r['password'] === $_password)
	{
		if($r['groupid'] == 2)
		{
			set_cookie('auth', '');
			showmessage($LANG['userid_banned_by_administrator']);
		}
		@extract($r, EXTR_PREFIX_ALL, '');
	}
	else
	{
		$_userid = 0;
		$_username = '';
		$_groupid = 3;
		set_cookie('auth', '');
	}
	unset($r, $phpcms_auth, $phpcms_auth_key, $_password, $sql_member);
}*/
$G = cache_read('member_group_'.$_groupid.'.php');
$priv_group = new priv_group();
define('SKIN_PATH', 'templates/'.TPL_NAME.'/skins/'.TPL_CSS.'/');
define('PASSPORT_ENABLE', ($PHPCMS['uc'] || $PHPCMS['enablepassport'] || $PHPCMS['enableserverpassport']) ? 1 : 0);
//include/common.inc.php结束


require 'log.class.php';
require 'form.class.php';
require 'priv_role.class.php';
require_once 'cache.func.php';
require_once 'version.inc.php';
require PHPCMS_ROOT.'languages/'.LANG.'/phpcms_admin.lang.php';

if(!isset($file)) $file = 'index';
preg_match("/^[0-9A-Za-z_-]+$/", $file) or showmessage('Invalid Request.');
$action = isset($action) ? $action : '';
$catid = isset($catid) ? intval($catid) : 0;
$specialid = isset($specialid) ? intval($specialid) : 0;
if(!isset($forward) && str_exists(HTTP_REFERER, '?')) $forward = HTTP_REFERER;

session_start();

if($_userid && $_groupid == 1 && $_SESSION['is_admin'] == 1)
{
	$ROLE = cache_read('role.php');
	$GROUP = cache_read('member_group.php');
	$POS = cache_read('position.php');
	$STATUS = cache_read('status.php');
//	$_roleid = cache_read('admin_role_'.$_userid.'.php');
//	if(!$_roleid) showmessage('您没有任何角色权限！');
//	$priv_role = new priv_role();
//	if(!$priv_role->module()) showmessage('您没有操作权限！');
}
/*elseif($file != 'login')
{
	showmessage('请登录！', '?mod=phpcms&file=login&forward='.urlencode(URL),1,1);
}
*/
$log = new log();
if(ADMIN_LOG && $file != 'database' && !in_array($action, array('get_menu_list', 'menu_pos')))
{
	$log->set('admin', 0);
	$log->add();
}
//if($mod != 'phpcms' && !@include PHPCMS_ROOT.$M['path'].'admin/admin.inc.php') showmessage('The file ./'.$M['path'].'admin.inc.php is not exists!');
if($mod != 'phpcms' && !@include PHPCMS_ROOT.$M['path'].'admin/admin.inc.php') exit('[err]The file ./'.$M['path'].'admin.inc.php is not exists! [/err]');
//if(!@include PHPCMS_ROOT.(isset($M['path']) ? $M['path'] : '').'admin/'.$file.'.inc.php') exit("[err]The file ./{$M['path']}admin/{$file}.inc.php is not exists![/err]");

defined('IN_PHPCMS') or exit("Access Denied");

require_once 'admin/process.class.php';
require_once 'admin/content.class.php';
//替换require_once 'attachment.class.php';开始
 
class attachment
{
	var $db;
	var $table;
	var $contentid;
	var $module;
	var $catid;
	var $attachments;
	var $field;
	var $imageexts = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
	var $uploadedfiles = array();
	var $downloadedfiles = array();
	var $error;

	function attachment($module = 'phpcms', $catid = 0)
	{
		global $db;
		$this->db = &$db;
		$this->table = DB_PRE.'attachment';
		$this->module = $module;
		$this->catid = intval($catid);
	}

	function get($aid, $fields = '*')
	{
		$aid = intval($aid);
		return $this->db->get_one("SELECT $fields FROM `$this->table` WHERE `aid`=$aid");
	}

	function upload($field, $alowexts = 'jpg|jpeg|gif|bmp|png|doc|docx|xls|ppt|pdf|txt|rar|zip', $maxsize = 0, $overwrite = 0)
	{
		global $_groupid;
		if((!UPLOAD_FRONT && $_groupid != 1) || !isset($_FILES[$field])) return false;
		$this->field = $field;
		$this->savepath = UPLOAD_ROOT.date('Y/md/');

		/*判断上传附件方式是否为ftp方式*/
		if(UPLOAD_FTP_ENABLE && extension_loaded('ftp'))
		{
			if(!is_object($upload_ftp)) {
				require_once 'ftp.class.php';
				$upload_ftp = new ftp(UPLOAD_FTP_HOST, UPLOAD_FTP_PORT, UPLOAD_FTP_USER, UPLOAD_FTP_PW, UPLOAD_FTP_PATH);
				if($upload_ftp->error) showmessage($upload_ftp->error);
			}
			$upload_ftp_enable = 1;
			$this->savepath = UPLOAD_FTP_ROOT.date('Y/md/');
		}

		$this->alowexts = $alowexts;
		$this->maxsize = $maxsize;
		$this->overwrite = $overwrite;
		$uploadfiles = array();
		$description = isset($GLOBALS[$field.'_description']) ? $GLOBALS[$field.'_description'] : array();
		if(is_array($_FILES[$field]['error']))
		{
			$this->uploads = count($_FILES[$field]['error']);
			foreach($_FILES[$field]['error'] as $key => $error)
			{
				if($error === UPLOAD_ERR_NO_FILE) continue;
				if($error !== UPLOAD_ERR_OK)
				{
					$this->error = $error;
					return false;
				}
				$uploadfiles[$key] = array('tmp_name' => $_FILES[$field]['tmp_name'][$key], 'name' => $_FILES[$field]['name'][$key], 'type' => $_FILES[$field]['type'][$key], 'size' => $_FILES[$field]['size'][$key], 'error' => $_FILES[$field]['error'][$key], 'description'=>$description[$key]);
			}
		}
		else
		{
			$this->uploads = 1;
			if(!$description) $description = '';
			$uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description'=>$description);
		}

		if($upload_ftp_enable) {
			if(!ftp_dir_create($this->savepath))
			{
				echo '1243';
				$this->error = '8';
				return false;
			}
			if(!$upload_ftp->chdir($this->savepath))
			{
				$this->error = '8';
				return false;
			}
			@$upload_ftp->chmod(0777, $this->savepath);

			if(!$this->is_allow_upload())
			{
				$this->error = '13';
				return false;
			}
		} else {
			if(!dir_create($this->savepath))
			{
				$this->error = '8';
				return false;
			}
			if(!is_dir($this->savepath))
			{
				$this->error = '8';
				return false;
			}
			@chmod($this->savepath, 0777);
			if(!is_writeable($this->savepath))
			{
				$this->error = '9';
				return false;
			}

			if(!$this->is_allow_upload())
			{
				$this->error = '13';
				return false;
			}
		}

		$aids = array();
		foreach($uploadfiles as $k=>$file)
		{
			$fileext = fileext($file['name']);
			if(!preg_match("/^(".$this->alowexts.")$/", $fileext))
			{
				$this->error = '10';
				return false;
			}
			if($this->maxsize && $file['size'] > $this->maxsize)
			{
				$this->error = '11';
				return false;
			}
			if(!$this->isuploadedfile($file['tmp_name']))
			{
				$this->error = '12';
				return false;
			}
			$temp_filename = $this->getname($fileext);
			$savefile = $this->savepath.$temp_filename;
			$savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);
			$filepath = preg_replace("|^".UPLOAD_ROOT."|", "", $savefile);

			if($upload_ftp_enable) {
				if(!$this->overwrite && ($upload_ftp->size($savefile)>0)) continue;
				if($upload_ftp->put($temp_filename, $file['tmp_name']))
				{
					$this->uploadeds++;
					@$upload_ftp->chmod($savefile, 0644);
					@unlink($file['tmp_name']);
					$uploadedfile = array('filename'=>$file['name'], 'filepath'=>UPLOAD_FTP_DOMAIN.$filepath, 'filetype'=>$file['type'], 'filesize'=>$file['size'], 'fileext'=>$fileext, 'description'=>$file['description']);
					$aids[] = $this->add($uploadedfile);
				}
			} else {
				if(!$this->overwrite && file_exists($savefile)) continue;
				$upload_func = UPLOAD_FUNC;
				if(@$upload_func($file['tmp_name'], $savefile))
				{
					$this->uploadeds++;
					@chmod($savefile, 0644);
					@unlink($file['tmp_name']);
					$uploadedfile = array('filename'=>$file['name'], 'filepath'=>$filepath, 'filetype'=>$file['type'], 'filesize'=>$file['size'], 'fileext'=>$fileext, 'description'=>$file['description']);
					$aids[] = $this->add($uploadedfile);
				}
			}
		}
		return $aids;
	}

	function update_intr($contentid, $value = '', $length = 200)
	{
		$length = min(intval($length), 255);
		$value = trim($value);
		if($value)
		{
			$des = $this->db->get_one("SELECT `description` FROM ".DB_PRE."content WHERE `contentid`='$contentid'");
			if(trim($des['description'])) return TRUE;
			if(strpos($value, '<p>')!==false)
			{
				$sen_occ = strpos($value, '</p>');
				$value = substr($value, 0, $sen_occ+3);
			}
			elseif(strpos($value, '<br'))
			{
				$sen_occ = strpos($value, '<br');
				$value = substr($value, 0, $sen_occ);
			}
			$description = str_cut(str_replace("\n", '', strip_tags($value)), $length, '');
			$this->db->query("UPDATE ".DB_PRE."content SET `description`='$description' WHERE `contentid`='$contentid'");
		}
		return TRUE;
	}

	function update_thumb($contentid, $aid = 1)
	{
		$aid = max(intval($aid), 1);
		$id = $this->db->get_one("SELECT `thumb` FROM ".DB_PRE."content WHERE `contentid`=$contentid");
		if($id['thumb']) return true;
		$aid--; 
		$info = $this->db->get_one("SELECT `filepath` FROM `$this->table` WHERE `contentid`='$contentid' ORDER BY `aid` ASC LIMIT $aid, 1");
		if($info['filepath'])
		{
			if(strpos($info['filepath'], '://') === false) $path = UPLOAD_URL.$info['filepath'];
			$this->db->query("UPDATE ".DB_PRE."content SET `thumb`='$path' WHERE `contentid`='$contentid'");
		}
		return true;
	}

	function download($field, $value, $ext = 'gif|jpg|jpeg|bmp|png', $absurl = '', $basehref = '')
	{
		global $contentid;

		$this->field = $field;
		$dir = date('Y/md/', TIME);
		$uploadpath = PHPCMS_PATH.UPLOAD_URL.$dir;
		$uploaddir = UPLOAD_ROOT.$dir;
		dir_create($uploaddir);
		$string = stripslashes($value);
		if(!preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $string, $matches)) return $value;
		$remotefileurls = array();
		foreach($matches[3] as $matche)
		{
			if(strpos($matche, '://') === false) continue;
			$remotefileurls[$matche] = $this->fillurl($matche, $absurl, $basehref);
		}
		unset($matches, $string);
		$attachments = get_cookie('attachments');	
		$attachments = $attachments==false ? array() : $attachments; //zzcity add
		$remotefileurls = array_unique($remotefileurls);
		$oldpath = $newpath = array();
		$attachments = array_map('basename', $attachments);
		foreach($remotefileurls as $k=>$file)
		{
			if(strpos($file, '://') === false) continue;
			$filename = fileext($file);
			$file_name = basename($file);
			if($contentid)
			{
				$r = $this->db->get_one("SELECT `aid` FROM `".DB_PRE."attachment` WHERE `contentid`=$contentid AND `filename`='$file_name'");
				if($r['aid']) continue;
			}
			if(in_array($file_name, $attachments))
			{
				$aid = array_search($file_name, $attachments);
				$this->attachments[$this->field][$aid] = $file;
				continue;
			}
			$filename = $this->getname($filename);
			$newfile = $uploaddir.$filename;
			$upload_func = UPLOAD_FUNC;
			if(@$upload_func($file, $newfile))
			{
				$oldpath[] = $k;
				$newpath[] = $uploadpath.$filename;
				@chmod($newfile, 0777);
				$fileext = fileext($filename);
				$filetype = '';
				$image_type = 'IMAGETYPE_'.strtoupper($fileext);
				if(defined($image_type) && function_exists('image_type_to_mime_type'))
				{
					$filetype = image_type_to_mime_type(constant($image_type));
				}
				$filepath = $dir.$filename;
				$downloadedfile = array('filename'=>$filename, 'filepath'=>$filepath, 'filetype'=>$filetype, 'filesize'=>filesize($newfile), 'fileext'=>$fileext);
				$aid = $this->add($downloadedfile);
				$this->downloadedfiles[$aid] = $filepath;
			}
		}
		return str_replace($oldpath, $newpath, $value);
	}

	function listinfo($where, $fields = '*', $order = 'listorder,aid', $page = 0, $pagesize = 20)
	{
		if($where) $where = " WHERE $where";
		if($order) $order = " ORDER BY $order";
		$limit = '';
		if($page !== 0)
		{
			$page = max(intval($page), 1);
			$offset = $pagesize*($page-1);
			$limit = " LIMIT $offset, $pagesize";
			$r = $this->db->get_one("SELECT count(*) as number FROM $this->table $where");
			$number = $r['number'];
			$this->pages = pages($number, $page, $pagesize);
		}
		$i = 1;
		$array = array();
		$result = $this->db->query("SELECT $fields FROM `$this->table` $where $order $limit");
		while($r = $this->db->fetch_array($result))
		{
			if(strstr($r['filepath'], 'http://')) {
				unset($r['isthumb']);
			} else {
				$r['filepath'] = UPLOAD_URL.$r['filepath'];
				$r['thumb'] = $this->get_thumb($r['filepath']);
			}
			$array[$i] = $r;
			$i++;
		}
		$this->number = $this->db->num_rows($result);
		$this->db->free_result($result);
		return $array;
	}

	function add($uploadedfile)
	{
		global $_userid;
		$uploadedfile['field'] = $this->field;
		$uploadedfile['module'] = $this->module;
		$uploadedfile['catid'] = $this->catid;
		$uploadedfile['userid'] = $_userid;
		$uploadedfile['uploadtime'] = TIME;
		$uploadedfile['uploadip'] = IP;
		$uploadedfile['isimage'] = in_array($uploadedfile['fileext'], $this->imageexts) ? 1 : 0;
		$uploadedfile = new_addslashes($uploadedfile);
		$this->db->insert($this->table, $uploadedfile);
		$aid = $this->db->insert_id();
		$uploadedfile['aid'] = $aid;
		$this->uploadedfiles[] = $uploadedfile;
		$this->attachments[$this->field][$aid] = $uploadedfile['filepath'];
		$attachments = get_cookie('attachments');
		$attachments[$aid] = $uploadedfile['filepath'];
		set_cookie('attachments', $attachments);
		return $aid;
	}

	function delete($where)
	{
		$result = $this->db->query("SELECT `filepath`,`isthumb` FROM `$this->table` WHERE $where ORDER BY `aid`");
		while($r = $this->db->fetch_array($result))
		{
			$image = UPLOAD_ROOT.$r['filepath'];
			@unlink($image);
			$thumbs = glob(dirname($image).'/*'.basename($image));
			if($thumbs) foreach($thumbs as $thumb) @unlink($thumb);
			if($r['isthumb'])
			{
				$thumb = $this->get_thumb($image);
				@unlink($thumb);
			}
		}
		$this->db->free_result($result);
		return $this->db->query("DELETE FROM `$this->table` WHERE $where");
	}

	function listorder($aid, $listorder)
	{
		$aid = intval($aid);
		$listorder = min(intval($listorder), 255);
		return $this->db->query("UPDATE `$this->table` SET `listorder`=$listorder WHERE `aid`=$aid");
	}

	function description($aid, $description)
	{
		$aid = intval($aid);
		return $this->db->query("UPDATE `$this->table` SET `description`='$description' WHERE `aid`=$aid");
	}

	function get_thumb($image)
	{
		return str_replace('.', '_thumb.', $image);
	}

	function set_thumb($aid)
	{
		$aid = intval($aid);
		return $this->db->query("UPDATE `$this->table` SET `isthumb`=1 WHERE `aid`=$aid");
	}

	function is_allow_upload()
	{
		global $_groupid;
        if($_groupid == 1) return true;
		$starttime = TIME-86400;
		$uploads = cache_count("SELECT COUNT(*) AS `count` FROM `$this->table` WHERE `uploadip`='".IP."' AND `uploadtime`>$starttime");
		return ($uploads < UPLOAD_MAXUPLOADS);
	}

	function update($contentid, $field, $html = '')
	{
		if(!isset($this->attachments[$field]) && $html == '') return 0;
		$contentid = intval($contentid);
		$aids = '';
		$attachments = get_cookie('attachments');
		if($html && !empty($attachments) && empty($_SESSION['downfiles']) && empty($_SESSION['field_images']) && empty($_SESSION['field_image']))
		{
			$aids_del = array();
			foreach($attachments as $aid => $url)
			{
				if(!isset($this->downloadedfiles[$aid]) && strpos($html, $url) === false)
				{
					$aids_del[] = $aid;
				}
				else
				{
					$aids[] = $aid;
				}
			}
		}
		else
		{
			if(is_array($this->attachments[$field])) $aids = array_keys($this->attachments[$field]);
		}
		$aids = implodeids($aids);
		if($aids) $this->db->query("UPDATE `$this->table` SET `catid`='$this->catid',`contentid`=$contentid,`field`='$field' WHERE `aid` IN($aids)");
		if(is_array($attachments) && !empty($attachments))
		{
			foreach($attachments as $k=>$v)
			{
				$attachments[$k] = '';
			}
		}
		set_cookie('attachments', $attachments);
		unset($attachments,$_SESSION['downfiles'],$_SESSION['field_images']);		
		return $aids ? 1 : 0;
	}

	function getname($fileext)
	{
		return date('Ymdhis').rand(100, 999).'.'.$fileext;
	}

	function size($filesize)
	{
		if($filesize >= 1073741824)
		{
			$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
		}
		elseif($filesize >= 1048576)
		{
			$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
		}
		elseif($filesize >= 1024)
		{
			$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
		}
		else
		{
			$filesize = $filesize . ' Bytes';
		}
		return $filesize;
	}

	function isuploadedfile($file)
	{
		return is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file));
	}

	function fillurl($surl, $absurl, $basehref = '')
	{
		if($basehref != '')
		{
			$preurl = strtolower(substr($surl,0,6));
			if($preurl=='http://' || $preurl=='ftp://' ||$preurl=='mms://' || $preurl=='rtsp://' || $preurl=='thunde' || $preurl=='emule://'|| $preurl=='ed2k://')
			return  $surl;
			else
			return $basehref.'/'.$surl;
		}
		$i = 0;
		$dstr = '';
		$pstr = '';
		$okurl = '';
		$pathStep = 0;
		$surl = trim($surl);
		if($surl=='') return '';
		//判断文档相对于当前的路径
		$urls = @parse_url(SITE_URL);
		$HomeUrl = $urls['host'];
		$BaseUrlPath = $HomeUrl.$urls['path'];
		$BaseUrlPath = preg_replace("/\/([^\/]*)\.(.*)$/",'/',$BaseUrlPath);
		$BaseUrlPath = preg_replace("/\/$/",'',$BaseUrlPath);
		$pos = strpos($surl,'#');
		if($pos>0) $surl = substr($surl,0,$pos);
		if($surl[0]=='/')
		{
			$okurl = 'http://'.$HomeUrl.'/'.$surl;
		}
		elseif($surl[0] == '.')
		{
			if(strlen($surl)<=2) return '';
			elseif($surl[0]=='/')
			{
				$okurl = 'http://'.$BaseUrlPath.'/'.substr($surl,2,strlen($surl)-2);
			}
			else
			{
				$urls = explode('/',$surl);
				foreach($urls as $u)
				{
					if($u=="..") $pathStep++;
					else if($i<count($urls)-1) $dstr .= $urls[$i].'/';
					else $dstr .= $urls[$i];
					$i++;
				}
				$urls = explode('/', $BaseUrlPath);
				if(count($urls) <= $pathStep)
				return '';
				else
				{
					$pstr = 'http://';
					for($i=0;$i<count($urls)-$pathStep;$i++)
					{
						$pstr .= $urls[$i].'/';
					}
					$okurl = $pstr.$dstr;
				}
			}
		}
		else
		{
			$preurl = strtolower(substr($surl,0,6));
			if(strlen($surl)<7)
			$okurl = 'http://'.$BaseUrlPath.'/'.$surl;
			elseif($preurl=="http:/"||$preurl=='ftp://' ||$preurl=='mms://' || $preurl=="rtsp://" || $preurl=='thunde' || $preurl=='emule:'|| $preurl=='ed2k:/')
			$okurl = $surl;
			else
			$okurl = 'http://'.$BaseUrlPath.'/'.$surl;
		}
		$preurl = strtolower(substr($okurl,0,6));
		if($preurl=='ftp://' || $preurl=='mms://' || $preurl=='rtsp://' || $preurl=='thunde' || $preurl=='emule:'|| $preurl=='ed2k:/')
		{
			return $okurl;
		}
		else
		{
			$okurl = eregi_replace("^(http://)",'',$okurl);
			$okurl = eregi_replace("/{1,}",'/',$okurl);
			return 'http://'.$okurl;
		}
	}

	function error()
	{
		$UPLOAD_ERROR = array(
		0 => '文件上传成功',
		1 => '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值',
		2 => '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值',
		3 => '文件只有部分被上传',
		4 => '没有文件被上传',
		5 => '',
		6 => '找不到临时文件夹。',
		7 => '文件写入临时文件夹失败',
		8 => '附件目录创建不成功',
		9 => '附件目录没有写入权限',
		10 => '不允许上传该类型文件',
		11 => '文件超过了管理员限定的大小',
		12 => '非法上传文件',
		13 => '24小时内上传附件个数超出了系统限制',
		);
		return $UPLOAD_ERROR[$this->error];
	}
}

//替换结束
$c = new content();

if(is_numeric($contentid) && $contentid>0)
{
	
	$data = $c->get($contentid);
	$catid = $data['catid'];
	$modelid = $CATEGORY[$catid]['modelid'];
}
$catid=$info['catid']; //ET增加

$info['islink']=(empty($info['islink']))?99:$info['islink'];//ET增加


if(!isset($catid) || !isset($CATEGORY[$catid])) showmessage('缺少 catid 参数!');
extract(cache_read('category_'.$catid.'.php'));

if($type == 2)
{
	if($action == 'manage') $action = 'link';
}
elseif($type == 1)
{
	if($action == 'manage') $action = 'block';
}
else
{
/*
	$allow_manage = $priv_role->check('catid', $catid, 'manage');
	$allow_add = $allow_manage ? true : $priv_role->check('catid', $catid, 'add');
	$allow_check = $allow_manage ? true : $priv_role->check('catid', $catid, 'check');
	$allow_view = $allow_manage ? true : $priv_role->check('catid', $catid, 'view');
*/
	$allow_manage = true;
	$allow_add =  true ;
	$allow_check =false;
	$allow_view = false;


	$attachment = new attachment($mod, $catid);
	$p = new process($workflowid);
	$PROCESS = cache_read('process_'.$workflowid.'.php');
/*
	$submenu = $allowprocessids = array();
	if($allow_add)
	{
		$submenu[] = array('<font color="red">发布信息</font>', '?mod='.$mod.'&file='.$file.'&action=add&catid='.$catid);
		$submenu[] = array('我发布的信息', '?mod='.$mod.'&file='.$file.'&action=my&catid='.$catid);
	}
	if($allow_check)
	{
		foreach($PROCESS as $pid=>$processname)
		{
			if($priv_role->check('processid', $pid))
			{
				$allow_processids[] = $pid;
				if($pid==1) $add_status = '&status=3';
				$submenu[] = array($processname, '?mod='.$mod.'&file='.$file.'&action=check&catid='.$catid.'&processid='.$pid.$add_status);
			}
		}
	}
	if($allow_manage)
	{
		$submenu[] = array('管理', '?mod='.$mod.'&file='.$file.'&action=manage&catid='.$catid);
		$submenu[] = array('回收站', '?mod='.$mod.'&file='.$file.'&action=recycle&catid='.$catid);
		$submenu[] = array('碎片', '?mod='.$mod.'&file='.$file.'&action=block&catid='.$catid);
	}
	elseif($allow_view)
	{
		$submenu[] = array('浏览', '?mod='.$mod.'&file='.$file.'&action=browse&catid='.$catid);
	}
	$submenu[] = array('搜索', '?mod='.$mod.'&file='.$file.'&action=search&catid='.$catid);
	$menu = admin_menu($CATEGORY[$catid]['catname'].' 栏目管理', $submenu);
*/
	if(!isset($processid) || !in_array($processid, $allow_processids)) $processid = $allow_processids[0];
}

switch($action)
{
    case 'add':
		//if(!$priv_role->check('catid', $catid, 'add') && !$allow_manage) showmessage('无发布权限！');
		
		if($dosubmit)
		{
			$info['status'] = ($status == 2 || $status == 3) ? $status : ($allow_manage ? 99 : 3);
			if(isset($info['inputtime'])) $info['updatetime'] = $info['inputtime'];
			$contentid = $c->add($info,$cat_selected);
			//if($contentid) showmessage('发布成功！', '?mod=phpcms&file=content&action=add&catid='.$catid);
			if($contentid){
				exit("[ok]");}
			else{
				exit("[err]post failed[/err]");
			}

		}
		else
		{
			$data['catid'] = $catid;
			$data['template'] = isset($template_show) ? $template_show :$MODEL[$modelid]['template_show'];

			require CACHE_MODEL_PATH.'content_form.class.php';
			$content_form = new content_form($modelid);
			$forminfos = $content_form->get($data);
            require_once 'tree.class.php';
            foreach($CATEGORY as $cid=>$c)
            {
				if($c['module'] != $mod || $c['type'] > 0) continue;
				$checkbox = $c['child'] ? '' : '<input type="checkbox" name="cat_selected[]" value="'.$cid.'">';
				$cats[$cid] = array('id'=>$cid, 'parentid'=>$c['parentid'], 'name'=>$c['catname'], 'checkbox'=>$checkbox);
            }
			$str = "<tr><td style='height:22px;padding:0 0 0 10px;'>\$spacer\$name</td><td>\$checkbox</td></tr>";
			$tree = new tree($cats);
			$categorys = $tree->get_tree(0, $str);
            $pagetitle = $CATEGORY[$catid]['catname'].'-发布';
			header("Cache-control: private");
			include admin_tpl('content_add');
		}
		break;
/*
    case 'edit':

		if($dosubmit)
		{
			$c->edit($contentid, $info);

			showmessage('修改成功！', $forward);
		}
		else
		{
			require CACHE_MODEL_PATH.'content_form.class.php';
			$content_form = new content_form($modelid);
			$forminfos = $content_form->get($data);

			include admin_tpl('content_edit');
		}
		break;

	case 'view':
		if(!$priv_role->check('catid', $catid, 'view') && !$allow_manage) showmessage('无查看权限！');

		require_once CACHE_MODEL_PATH.'content_output.class.php';
		$coutput = new content_output();
		$info = $coutput->get($data);

		include admin_tpl('content_view');
		break;

	case 'log_list':
		$ACTION = array('add'=>'发布', 'edit'=>'修改', 'delete'=>'删除');
	    $content = $c->get($contentid);
		extract($content);
	    $log->set('contentid', $contentid);
		$data = $log->listinfo($where, $page, 20);
		include admin_tpl('content_log');
	    break;

    case 'my':
		if(!$allow_add) showmessage('无发布权限！');
		$c->set_userid($_userid);
	    $status = isset($status) ? intval($status) : -1;
		$where = "`catid`=$catid ";
	    if($status != -1) $where .= " AND `status`='$status'";
        $infos = $c->listinfo($where, 'listorder DESC,contentid DESC', $page, 20);
		$pagetitle = '我的信息-管理';
		include admin_tpl('content_my');
		break;

    case 'my_contribute':
		$c->set_userid($_userid);
	    $contentid = $c->contentid($contentid, array(0, 1, 2));
		$c->status($contentid, 3);
		showmessage('操作成功！', $forward);
		break;

    case 'my_cancelcontribute':
		$c->set_userid($_userid);
	    $contentid = $c->contentid($contentid, array(3));
		$c->status($contentid, 2);
		showmessage('操作成功！', $forward);
		break;

    case 'my_edit':
		$c->set_userid($_userid);
	    $contentid = $c->contentid($contentid, array(0, 1, 2, 3));

		if($dosubmit)
		{
			$c->edit($contentid, $info);
			showmessage('修改成功！', $forward);
		}
		else
		{
			require CACHE_MODEL_PATH.'content_form.class.php';
			$content_form = new content_form($modelid);
			$forminfos = $content_form->get($data);

			include admin_tpl('content_edit');
		}
		break;

    case 'my_delete':
		$c->set_userid($_userid);
	    $contentid = $c->contentid($contentid, array(0, 1, 2, 3));
		$c->delete($contentid);
		showmessage('操作成功！', $forward);
		break;

	case 'my_view':
		$c->set_userid($_userid);
	    $contentid = $c->contentid($contentid, array(0, 1, 2, 3));

		require_once CACHE_MODEL_PATH.'content_output.class.php';
		$coutput = new content_output();
		$info = $coutput->get($data);

		include admin_tpl('content_view');
		break;

	case 'check':
		$allow_status = $p->get_process_status($processid);
		if(!isset($status) || !in_array($status, $allow_status)) $status = -1;
		$where = "`catid`=$catid ";
		$where .= $status == -1 ? " AND `status` IN(".implode(',', $allow_status).")" : " AND `status`='$status'";
        $infos = $c->listinfo($where, 'listorder DESC,contentid DESC', $page, 20);
		$process = $p->get($processid, 'passname,passstatus,rejectname,rejectstatus');
		extract($process);

        $pagetitle = $CATEGORY[$catid]['catname'].'-审核';
		include admin_tpl('content_check');
		break;

    case 'browse':
		$where = "`catid`=$catid AND `status`=99";
        $infos = $c->listinfo($where, 'listorder DESC,contentid DESC', $page, 20);
		include admin_tpl('content_browse');
		break;

    case 'search':
		if($dosubmit)
		{
			require CACHE_MODEL_PATH.'content_search.class.php';
			$content_search = new content_search();
			$infos = $content_search->data($page, 20);
			include admin_tpl('content_search_list');
		}
		else
		{
			require CACHE_MODEL_PATH.'content_search_form.class.php';
			$content_search_form = new content_search_form();
			$forminfos = $content_search_form->get_where();
			$orderfields = $content_search_form->get_order();

            $pagetitle = $CATEGORY[$catid]['catname'].'-搜索';
			include admin_tpl('content_search');
		}
		break;

    case 'recycle':
		if(!$allow_manage) showmessage('无管理权限！');
        $infos = $c->listinfo("catid=$catid AND status=0", 'listorder DESC,contentid DESC', $page, 20);

        $pagetitle = $CATEGORY[$catid]['catname'].'-回收站';
		include admin_tpl('content_recycle');
		break;

    case 'pass':
		if(!$priv_role->check('catid', $catid, 'check') && !$allow_manage) showmessage('无审核权限！');
		$allow_status = $p->get_process_status($processid);
		if($contentid=='') showmessage('请选择要批准的内容');
	    $contentid = $c->contentid($contentid, 0, $allow_status);
		$process = $p->get($processid, 'passstatus');
		$c->status($contentid, $process['passstatus']);
		showmessage('操作成功！', $forward);
		break;

    case 'reject':
		if(!$priv_role->check('catid', $catid, 'check') && !$allow_manage) showmessage('无审核权限！');
		$allow_status = $p->get_process_status($processid);
		if($contentid=='') showmessage('请选择要批准的内容');
	    $contentid = $c->contentid($contentid, 0, $allow_status);
		$process = $p->get($processid, 'rejectstatus');
		$c->status($contentid, $process['rejectstatus']);
		showmessage('操作成功！', $forward);
		break;

	case 'cancel':
		if(!$allow_manage) showmessage('无管理权限！');
		$c->status($contentid, 0);
		showmessage('操作成功！', $forward);
		break;

    case 'delete':
		if(!$allow_manage) showmessage('无管理权限！');
		$c->delete($contentid);
		showmessage('操作成功！', $forward);
		break;

    case 'clear':
		if(!$allow_manage) showmessage('无管理权限！');
		$c->clear();
		showmessage('操作成功！', $forward);
		break;

    case 'restore':
		if(!$allow_manage) showmessage('无管理权限！');
		$c->restore($contentid);
		showmessage('操作成功！', $forward);
		break;

    case 'restoreall':
		if(!$allow_manage) showmessage('无管理权限！');
		$c->restoreall();
		showmessage('操作成功！', $forward);
		break;

    case 'listorder':
		$result = $c->listorder($listorders);
		if($result)
		{
			showmessage('操作成功！', $forward);
		}
		else
		{
			showmessage('操作失败！');
		}
		break;

	case 'link':
		if($dosubmit)
		{
			require_once 'admin/category.class.php';
			$cat = new category($mod);
			$cat->link($catid, $category);

			showmessage('操作成功！', $forward);
		}
		else
		{
			include admin_tpl('content_link');
        }
		break;

	case 'block':
		if($type == 0)
		{
			$page = max(intval($page), 1);
			if($tpl == 'category')
			{
				if($child == 1)
				{
					$arrchildid = subcat('phpcms', $catid);
					$template = $template_category;
				}
				else
				{
					$template = $template_list;
				}
			}
			elseif($tpl == 'show')
			{
				$template = $MODEL[$modelid]['template_show'];
			}
			else
			{
				$template = $template_list;
			}
		}
		elseif($type == 2)
		{
			header('location:'.$url);
		}

		$catlist = submodelcat($modelid);
		$arrparentid = explode(',', $arrparentid);
		$parentid = $arrparentid[1];

		$head['title'] = $catname;
		$head['keywords'] = $meta_keywords;
		$head['description'] = $meta_description;
		include admin_template('phpcms', $template);
        include admin_tpl('block_ajax', 'phpcms');
		break;

	case 'category':
		$catid = intval($catid);
		if(!isset($CATEGORY[$catid])) showmessage('访问的栏目不存在！');
		$C = cache_read('category_'.$catid.'.php');
		extract($C);
		if($type == 1)
		{
			$template = $C['template'];
		}
		elseif($type == 2)
		{
			header('location:'.$url);
		}
		else
		{
			$page = max(intval($page), 0);
			if($page == 0)
			{
				$template = $C['template_category'];
				$categorys = $child ? subcat('phpcms', $catid, 0) : array();
			}
			else
			{
				$template = $C['template_list'];
			}
		}
		$head['title'] = $catname;
		$head['keywords'] = $meta_keywords;
		$head['description'] = $meta_description;

		define('BLOCK_EDIT', 1);
		include template('phpcms', $template);
		break;

	default:
		require_once 'admin/model_field.class.php';
        $model_field = new model_field($modelid);

	    $where = "`catid`=$catid AND `status`=99 ";
	    if($typeid) $where .= " AND `typeid`='$typeid' ";
	    if($areaid) $where .= " AND `areaid`='$areaid' ";
	    if($inputdate_start) $where .= " AND `inputtime`>='".strtotime($inputdate_start.' 00:00:00')."'"; else $inputdate_start = date('Y-m-01');
	    if($inputdate_end) $where .= " AND `inputtime`<='".strtotime($inputdate_end.' 23:59:59')."'"; else $inputdate_end = date('Y-m-d');
		if($q)
	    {
			if($field == 'title')
			{
				$where .= " AND `title` LIKE '%$q%'";
			}
			elseif($field == 'userid')
			{
				$userid = intval($q);
				if($userid)	$where .= " AND `userid`=$userid";
			}
			elseif($field == 'username')
			{
				$userid = userid($q);
				if($userid)	$where .= " AND `userid`=$userid";
			}
			elseif($field == 'contentid')
			{
				$contentid = intval($q);
				if($contentid) $where .= " AND `contentid`=$contentid";
			}
		}
        $infos = $c->listinfo($where, '`listorder` DESC,`contentid` DESC', $page, 20);

        $pagetitle = $CATEGORY[$catid]['catname'].'-管理';
		$POS[0] = '不限推荐位';

		include admin_tpl('content_manage');
		*/
}

?>