<?php
/*
	SupeSite 7.5 GBK 文章发布接口
*/

/********密码验证***********/
$password='123456';				                   //这个密码是登陆验证用的.您需要在模块里设置和这里一样的密码....注意一定需要修改.
if($password!=$_GET['pw']) exit('验证密码错误');   //安全检测,密码不符则退出


/****以下代码非专业人员不建议修改***************/
include_once('./common.php');
include_once(S_ROOT.'./function/html.func.php');
include_once(S_ROOT.'./function/admin.func.php');
include_once(S_ROOT.'./function/cache.func.php');

@define('IN_SUPESITE_ADMINCP', TRUE);
define('IMG_DIR', S_URL.'/admin/images');
define('CPURL', S_URL.'/admincp.php');

$cquery=$_SGLOBAL['db']->query("Select catid as cid,upid as pid,name as cname from {$tablepre}categories  where  type='news' order by displayorder");//先获取分类信息
while($crs=$_SGLOBAL['db']->fetch_array($cquery))
{
	$cates[]=$crs;
}
//print_r($cates);exit;
if($_SERVER['REQUEST_METHOD'] == 'GET')
{
	echo "<select name='list'>";
	echo maketree($cates,0,'');
	echo '</select>';
	exit();
}


//语言包
include_once(S_ROOT.'./language/admincp.lang.php');

//模块
$_SGLOBAL['allblocktype'] = array('category', 'spacenews', 'postitem', 'poll', 'model', 'tag', 'spacetag', 'spacecomment', 'announcement','friendlink');
if (discuz_exists()) array_push($_SGLOBAL['allblocktype'], 'bbsthread', 'bbsannouncement', 'bbsforum', 'bbslink', 'bbsmember', 'bbsattachment', 'bbspost');
if (uchome_exists()) array_push($_SGLOBAL['allblocktype'], 'uchblog', 'uchphoto', 'uchspace');

$cacheinfo = array();
@include_once(S_ROOT.'./function/model.func.php');
$models = getuserspacemid();

@include_once(S_ROOT.'./data/system/group.cache.php');
$menus = array();
//include_once template('admin/tpl/header.htm', 1);

include_once(S_ROOT.'./function/news.func.php');
include_once(S_ROOT.'./function/tag.func.php');

//这里进行用户检查
$username=$_SGLOBAL['supe_username']=postget('username');
$uquery=$_SGLOBAL['db']->query("Select uid as uid from {$tablepre}members where username='$username'");
if(!$uquery) exit("不存在用户名$username");
$userinfo=$_SGLOBAL['db']->fetch_array($uquery);
$_SGLOBAL['supe_uid']=$userinfo['uid'];

//权限
$type = postget('type');
$type = $channel = empty($type) ? 'news' : trim($type);
$_SGET['folder'] = intval(postget('folder'));
$_SGET['folder'] = empty($_SGET['folder']) ? 0 : intval($_SGET['folder']);
if($_SGET['folder'] == 1 && !(checkperm('managefolder') || checkperm('managemodpost'))) {
	showmessage('spacenews_no_popedom_check');
}

$allowmax = 100;		//最大上传数量
$catarr = array();
$perpage = empty($_GET['perpage']) ? 0 : intval($_GET['perpage']);			//默认每页显示列表数目
if(!$perpage) $perpage = 20;
$hashstr = smd5($_SGLOBAL['supe_uid'].'/'.$_SGLOBAL['timestamp'].random(6));	//附件识别码

//获取的变量初始化
$_SGET['page'] = intval(postget('page'));
$_SGET['catid'] = intval(postget('catid'));
$_SGET['itemtypeid'] = intval(postget('itemtypeid'));
$_SGET['digest'] = intval(postget('digest'));
$_SGET['fromtype'] = postget('fromtype');
$_SGET['order'] = postget('order');
$_SGET['sc'] = postget('sc');
$_SGET['searchid'] = intval(postget('searchid'))==0 ? '' : intval(postget('searchid'));
$_SGET['searchkey'] = stripsearchkey(postget('searchkey'));
$_GET['op'] = 'add';
if(empty($_SGET['subtype'])) $_SGET['subtype'] = '';
($_SGET['page'] < 1) ? $_SGET['page'] = 1 : '';
if(!in_array($_SGET['order'], array('dateline', 'lastpost', 'uid', 'viewnum', 'replynum'))) {
	$_SGET['order'] = '';
}
if(!in_array($_SGET['sc'], array('ASC', 'DESC'))) {
	$_SGET['sc'] = 'DESC';
}
$theurl = CPURL.'?action=spacenews';
$urlplus = '&type='.$type.'&catid='.$_SGET['catid'].'&itemtypeid='.$_SGET['itemtypeid'].'&folder='.$_SGET['folder'].'&digest='.$_SGET['digest'].'&order='.$_SGET['order'].'&sc='.$_SGET['sc'].'&subtype='.$_SGET['subtype'].'&perpage='.$perpage.'&searchkey='.rawurlencode($_SGET['searchkey']).'&fromtype='.$_SGET['fromtype'];
$newurl = $theurl.$urlplus.'&page='.$_SGET['page'];

$gradearr = array(
	'0' => $alang['general_state'],
	'1' => $alang['check_grade_1'],
	'2' => $alang['check_grade_2'],
	'3' => $alang['check_grade_3'],
	'4' => $alang['check_grade_4'],
	'5' => $alang['check_grade_5']
);
if(!empty($_SCONFIG['checkgrade'])) {
	$newgradearr = explode("\t", $_SCONFIG['checkgrade']);
	for($i=0; $i<5; $i++) {
		if(!empty($newgradearr[$i])) $gradearr[$i+1] = $newgradearr[$i];
	}
}

//INIT RESULT VAR
$showurlarr = $thevalue = $dellistarr = $listarr = array();

if(empty($_POST['page'])) $_POST['page'] = 1;
$page = intval($_POST['page']); 
if($page < 1) $page = 1;

$_POST['pitemid'] = intval($_POST['pitemid']);
$itemid = intval($_POST['itemid']);

//权限
if($itemid && !(checkperm('manageditpost') || checkperm('managemodpost'))) {
	showmessage('no_authority_management_operation');
}

//初始化用户的分页
if(submitcheck('makepageorder')) { 
	$query = $_SGLOBAL['db']->query('SELECT pageorder,nid FROM '.tname('spacenews').' WHERE itemid=\''.$itemid.'\' ORDER BY pageorder ASC, nid ASC '); 
	$newpageorder = 1;
	while ($row = $_SGLOBAL['db']->fetch_array($query)) {
		updatetable('spacenews', array('pageorder'=>$newpageorder), array('nid'=>$row['nid']));
		$newpageorder++;
	}
}
//更新用户的分页
$_POST['nid'] = empty($_POST['nid'])?0:intval($_POST['nid']);
$pageorder = intval($_POST['pageorder']);
if($pageorder < $page) {  //判断用户修改了页面顺序
	$_SGLOBAL['db']->query('UPDATE '.tname('spacenews').' SET pageorder = pageorder+1 WHERE itemid = '.$itemid.' AND pageorder >='.$pageorder.' AND pageorder < '.$page);
}elseif($pageorder > $page) {
	$_SGLOBAL['db']->query('UPDATE '.tname('spacenews').' SET pageorder = pageorder-1 WHERE itemid = '.$itemid.' AND pageorder <='.$pageorder.' AND pageorder > '.$page);
}

//更新用户最新更新时间
if(empty($itemid)) {
	updatetable('members', array('updatetime'=>$_SGLOBAL['timestamp']), array('uid'=>$_SGLOBAL['supe_uid']));
}

//第一个页面处理
if(empty($itemid) || $page == 1) {

	//输入检查
	$_POST['catid'] = intval($_POST['catid']);
	$_POST['customfieldid'] = intval($_POST['customfieldid']);
	$_POST['picid'] = empty($_POST['picid'])?0:intval($_POST['picid']);	//图文资讯标志
			
	//检查输入
	$_POST['subject'] = shtmlspecialchars(trim($_POST['subject']));//标题支持html
	if(strlen($_POST['subject']) < 2 || strlen($_POST['subject']) > 80) {
		showmessage('space_suject_length_error');
	}
	if(empty($_POST['catid'])) {
		showmessage('admin_func_catid_error');
	}

	//自定义信息
	$setcustomfieldtext = empty($_POST['customfieldtext'][$_POST['customfieldid']])?serialize(array()):addslashes(serialize(shtmlspecialchars(sstripslashes($_POST['customfieldtext'][$_POST['customfieldid']]))));

	//TAG处理
	if(empty($_POST['tagname'])) $_POST['tagname'] = '';
	$tagarr = posttag($_POST['tagname']);
	
	//构建数据
	$setsqlarr = array(
		'catid' => $_POST['catid'],
		'subject' => scensor($_POST['subject'], 1),
		'hash' => $_POST['hash'],
		'picid' => $_POST['picid']
	);
	
	$_SGET['folder'] = checkperm('allowdirectpost') ? 1 : (isset($_SGET['folder']) && intval($_SGET['folder']) == 0 ? 0 : 1);

	//标题样式
	empty($_POST['strong'])?$_POST['strong']='':$_POST['strong']=1;
	empty($_POST['underline'])?$_POST['underline']='':$_POST['underline']=1;
	empty($_POST['em'])?$_POST['em']='':$_POST['em']=1;
	empty($_POST['fontcolor'])?$_POST['fontcolor']='':$_POST['fontcolor']=$_POST['fontcolor'];
	empty($_POST['fontsize'])?$_POST['fontsize']='':$_POST['fontsize']=$_POST['fontsize'];
	$setsqlarr['styletitle'] = sprintf("%6s%2s%1s%1s%1s",substr($_POST['fontcolor'], -6),substr($_POST['fontsize'],-4,2),$_POST['em'],$_POST['strong'],$_POST['underline']);

	if($setsqlarr['styletitle'] === '           ') {
		$setsqlarr['styletitle']  = '';
	}

	$setsqlarr['digest'] = intval($_POST['digest']);
	$setsqlarr['top'] = intval($_POST['top']);
	$setsqlarr['allowreply'] = intval($_POST['allowreply']);
	$setsqlarr['grade'] = intval($_POST['grade']);
	
	//附件
	if(!empty($_POST['divupload']) && is_array($_POST['divupload'])) {
		$setsqlarr['haveattach'] = 1;
		$picflag = 1;
	} else {
		$setsqlarr['haveattach'] = 0;
	}		
	
	//发布时间
	if(empty($_POST['dateline'])) {
		$setsqlarr['dateline'] = $_SGLOBAL['timestamp'];
	} else {
		$setsqlarr['dateline'] = sstrtotime($_POST['dateline']);
		if($setsqlarr['dateline'] > $_SGLOBAL['timestamp']) {
			$setsqlarr['dateline'] = $_SGLOBAL['timestamp'];
		}
	}

	if(empty($itemid)) {
		//添加数据
		$op = 'add';
		$setsqlarr['tid'] = empty($_POST['tid'])?0:intval($_POST['tid']);
		$setsqlarr['type'] = $type;
		$setsqlarr['uid'] = $_SGLOBAL['supe_uid'];
		$setsqlarr['username'] = $_SGLOBAL['supe_username'];	
		$setsqlarr['lastpost'] = $setsqlarr['dateline'];
		$setsqlarr['fromtype'] = 'adminpost';
		if(!$_SGET['folder']) {

			//插入数据
			$itemid = inserttable('spaceitems', $setsqlarr, 1);	
			getreward('postinfo');
			//feed
			if(allowfeed() && $_POST['addfeed']) {
				$feed['icon'] = 'comment';
				$feed['title_template'] = 'feed_news_title';
				$feed['body_template'] = 'feed_news_message';
				$subjecturl = geturl('action/viewnews/itemid/'.$itemid);
				
				if(empty($_SCONFIG['siteurl'])) {
					$siteurl = getsiteurl();
					$subjecturl = $siteurl.$subjecturl; 
				}
				$feed['body_data'] = array(
					'subject' => '<a href="'.$subjecturl.'">'.$_POST['subject'].'</a>',
					'message' => cutstr(strip_tags(preg_replace("/\[.+?\]/is", '', $_POST['message'])), 150)
				);
				$picurl = getmessagepic(stripslashes($_POST['message']));

				if($picurl && (strpos($picurl, '://') === false)) {
					$picurl = $siteurl.'/'.$picurl;
				}
				if(!empty($picurl)) {
					
					$feed['images'][] = array('url'=>$picurl, 'link'=>$subjecturl);
				}
				
				postfeed($feed);
			}	

			//信息与tag关联处理
			postspacetag('add', $type, $itemid, $tagarr,1);
			
		} else {

			unset($setsqlarr ['styletitle']);
			unset($setsqlarr ['digest']);
			unset($setsqlarr ['top']);
			unset($setsqlarr ['grade']);
			unset($setsqlarr ['tid']);
			
			$setsqlarr ['folder'] = 1;	//待审箱
			$itemid = inserttable('postitems', $setsqlarr, 1);
			postspacetag('add', $type, $itemid, $tagarr, 0);
		}

	} else {
		//更新
		$op = 'update';
		
		if(!$_SGET['folder']) {
			updatetable('spaceitems', $setsqlarr, array('itemid'=>$itemid));
		} else {
			unset($setsqlarr ['styletitle']);
			unset($setsqlarr ['digest']);
			unset($setsqlarr ['top']);
			unset($setsqlarr ['grade']);
			unset($setsqlarr ['tid']);

			$setsqlarr ['folder'] = 1;	//待审箱

			updatetable('postitems', $setsqlarr, array('itemid'=>$itemid));
			
		}
		
		//信息与tag关联处理
		$itemid = empty($_POST['oitemid']) ? $itemid : $_POST['oitemid'];
		postspacetag('update', $type, $itemid, $tagarr, $status);
	}
	
	//附件
	if($setsqlarr['haveattach']) {
		$_SGLOBAL['db']->query('UPDATE '.tname('attachments').' SET isavailable=1, type=\''.$type.'\', itemid='.$itemid.', catid=\''.$_POST['catid'].'\' WHERE hash=\''.$_POST['hash'].'\'');
	}
	
	//内容 图片路径和附件路径处理
	$_POST['message'] = preg_replace_callback("/src\=(.{2})([^\>\s]{10,105})\.(jpg|gif|png)/i", 'addurlhttp', $_POST['message']);
	$_POST['message'] = str_replace('href=\"batch.download.php', 'href=\"'.S_URL.'/batch.download.php', $_POST['message']);
	
	$setsqlarr = array(
		'message' => scensor($_POST['message'], 1),
		'postip' => $_SGLOBAL['onlineip'],
		'customfieldid' => $_POST['customfieldid'],
		'customfieldtext' => $setcustomfieldtext
	);
			
	//相关TAG
	$tagnamearr = array_merge($tagarr['existsname'], $tagarr['nonename']);
	$setsqlarr['relativetags'] = addslashes(serialize($tagnamearr));

	//包含tag
	$setsqlarr['includetags'] = postgetincludetags($_POST['message'], $tagnamearr);

	//相关阅读
	$setsqlarr['relativeitemids'] = getrelativeitemids($itemid, array('news'));

	//额外信息
	$setsqlarr['newsauthor'] = shtmlspecialchars(trim($_POST['newsauthor']));
	$setsqlarr['newsfrom'] = shtmlspecialchars(trim($_POST['newsfrom']));
	$setsqlarr['newsurl'] = shtmlspecialchars(trim($_POST['newsurl']));
	$setsqlarr['newsfromurl'] = shtmlspecialchars(trim($_POST['newsfromurl']));
	$setsqlarr['pageorder'] = $pageorder;
	$setsqlarr['itemid'] = $itemid;
	
	if($op == 'add') {
		
		//添加内容
		$arraymessage = array();
		if(!$_SGET['folder']) {
			$arraymessage = explode('###NextPage###', $setsqlarr['message']);
		} else {
			$arraymessage[] = $setsqlarr['message'];
		}
		
		$firstmessage = 0;
		$insertarr = array();

		foreach($arraymessage as $message) {
			$message = trim($message);
			if($firstmessage == 1){
				unset($setsqlarr['customfieldid']);
				unset($setsqlarr['relativetags']);
				unset($setsqlarr['relativeitemids']);
				unset($setsqlarr['includetags']);
				unset($setsqlarr['customfieldtext']);
			}
			$firstmessage++;
			$setsqlarr['message'] = $message;
			$setsqlarr['pageorder'] = $firstmessage;
			if($firstmessage == 1){
				
				if(!$_SGET['folder']) {
					inserttable('spacenews', $setsqlarr);
				} else {
					inserttable('postmessages', $setsqlarr);
				}
				
			} else {
				$insertarr[] = $setsqlarr;
			}
		}
		if(!empty($insertarr)) {
			$insertkeys = array_keys($insertarr[0]);
			$insertarr_str = array();
			foreach($insertarr as $_index=>$_value) {
				$insertarr_str[] = "('".implode("','",$_value)."')";
			}
			$_SGLOBAL['db']->query("INSERT INTO ".tname('spacenews')." (`".implode('`,`',$insertkeys)."`) VALUES ".implode(',',$insertarr_str));
		}
		ssetcookie('newsauthor', $setsqlarr['newsauthor'], 86400);
		ssetcookie('newsfrom', $setsqlarr['newsfrom'], 86400);
	} else {

		//更新内容
		$insertarr = array();
		$firstmessage = $page;
		if(!$_SGET['folder']) {
			$arraymessage = explode('###NextPage###', $setsqlarr['message']);
		} else{
			$arraymessage[] = $setsqlarr['message'];
		}
		
		foreach($arraymessage as $message) {
			$message = trim($message);
			$setsqlarr['message'] = $message;
			$setsqlarr['pageorder'] = $pageorder;
			if($firstmessage == $_SGET['page']) {
				if(!$_SGET['folder']) {
					updatetable('spacenews', $setsqlarr, array('nid'=>$_POST['nid'], 'itemid'=>$itemid));
				} else {
					updatetable('postmessages', $setsqlarr, array('nid'=>$_POST['nid'], 'itemid'=>$itemid));
				}					
			} else {
				$insertarr[] = $setsqlarr;
			}
			$firstmessage++;
			$pageorder++;
		}
		if(!empty($insertarr)) {

			$insertkeys = array_keys($insertarr[0]);
			$insertarrnow = count($insertarr);
			$_SGLOBAL['db']->query("UPDATE ".tname('spacenews')." SET pageorder = pageorder+".$insertarrnow." WHERE itemid = ".$itemid." AND pageorder >".$_SGET['page']);
			$insertarr_str = array();
			foreach($insertarr as $_index=>$_value) {
				$insertarr_str[] = "('".implode("','",$_value)."')";
			}
			$_SGLOBAL['db']->query("INSERT INTO ".tname('spacenews')." (`".implode('`,`',$insertkeys)."`) VALUES ".implode(',',$insertarr_str));

		}			
	}
	
	if(!$_SGET['folder']) {
		$showurlarr[] = array(geturl('action/viewnews/itemid/'.$itemid.'/php/1'), $alang['spacenews_newspage']);
		$showurlarr[] = array(geturl('action/category/catid/'.$_POST['catid'].'/php/1'), $alang['spacenews_typepage']);
	} else {
		$showurlarr[] = array(CPURL.'?action=spacenews&op=view&itemid='.$itemid, $alang['spacenews_newspage']);
		$showurlarr[] = array(geturl('action/category/catid/'.$_POST['catid'].'/php/1'), $alang['spacenews_typepage']);
	}
	
} else {
	//额外信息
	$_POST['newsauthor'] = shtmlspecialchars(trim($_POST['newsauthor']));
	$_POST['newsfrom'] = shtmlspecialchars(trim($_POST['newsfrom']));
	$_POST['newsurl'] = isset($_POST['newurl']) ? shtmlspecialchars(trim($_POST['newsurl'])) : '';
	$_POST['newsfromurl'] = shtmlspecialchars(trim($_POST['newsfromurl']));

	//其余分页处理
	$setsqlarr = array(
		'postip' => $_SGLOBAL['onlineip'],
		'itemid' => $itemid,
		'newsauthor' => $_POST['newsauthor'],
		'newsfrom' => $_POST['newsfrom'],
		'newsfromurl' => $_POST['newsfromurl'],
		'newsurl' => $_POST['newsurl'],
	);
	$insertarr = array();
	$arraymessage = explode('###NextPage###', scensor($_POST['message'], 1));
	$firstmessage = $page;
	foreach($arraymessage as $message) {
		$message = trim($message);
		$setsqlarr['message'] = $message;
		$setsqlarr['pageorder'] = $pageorder;
		if($firstmessage == $_SGET['page']) {
			updatetable('spacenews', $setsqlarr, array('nid'=>$_POST['nid'], 'itemid'=>$itemid));
		} else {
			$insertarr[] = $setsqlarr;
		}
		$firstmessage++;
		$pageorder++;
	}
	if(!empty($insertarr)) {
		$insertkeys = array_keys($insertarr[0]);
		$insertarrnow = count($insertarr);
		$_SGLOBAL['db']->query("UPDATE ".tname('spacenews')." SET pageorder = pageorder+".$insertarrnow." WHERE itemid = ".$itemid." AND pageorder >".$_SGET['page']);
		$insertarr_str = array();
		foreach($insertarr as $_index=>$_value) {
			$insertarr_str[] = "('".implode("','",$_value)."')";
		}
		$_SGLOBAL['db']->query("INSERT INTO ".tname('spacenews')." (`".implode('`,`',$insertkeys)."`) VALUES ".implode(',',$insertarr_str));

	}

	$showurlarr[] = array(geturl('action/viewnews/itemid/'.$itemid.'/php/1'), $alang['spacenews_newspage']);
	$showurlarr[] = array(geturl('action/category/catid/'.$_POST['catid'].'/php/1'), $alang['spacenews_typepage']);
}

//MENU
$active[] = array(0=>'', 1=>'', 2=>'', 'add'=>'', 'edit'=>'');

//view
include template('admin/tpl/spacenews.htm', 1);
//完成后的url

if(is_array($showurlarr) && $showurlarr) {
	echo label(array('type'=>'div-start'));
	echo label(array('type'=>'table-start'));
	foreach ($showurlarr as $url) {
		$turl = $url[0];
		echo '<tr><td><a href="'.$turl.'" target="_blank"><strong>'.$url[1].'</strong> '.$alang['spaceblog_viewpage_success'].'</a></td></tr>';
	}
	echo label(array('type'=>'table-end'));
	echo label(array('type'=>'div-end'));
	
	echo '
	<div class="buttons">
	<input type="button" name="continuesubmit4" value="'.$alang['spacenews_op_add'].'" onclick="window.location.href=\''.$theurl.'&type='.$type.'&op=add\'"> 
	<input type="button" name="continuesubmit3" value="'.$alang['spacenews_title_message_op_add'].'" onclick="window.location.href=\''.$theurl.'&type='.$type.'&op=addpage&itemid='.$itemid.'\'"> 
	<input type="button" name="continuesubmit2" value="'.$alang['continue_the_current_editorial_page'].'" onclick="window.location.href=\''.$theurl.'&op=edit&folder='.$_SGET['folder'].'&itemid='.$itemid.'&page='.$page.'\'"> 
	<input type="button" name="continuesubmit1" value="'.$alang['common_continue_list_edit'].'" onclick="window.location.href=\''.$theurl.'&type='.$type.'\'"> 
	</div>';
}



//include_once template('admin/tpl/footer.htm', 1);


/***生成目录的一个遍历算法***/
function maketree($ar,$id,$pre)
{
	$ids='';
	foreach($ar as $k=>$v){
		$pid=$v['pid'];
		$cname=$v['cname'];
		$cid=$v['cid'];
		if($pid==$id)
		{
			$ids.="<option value='$cid'>{$pre}{$cname}</option>";
			foreach($ar as $kk=>$vv)
			{
				$pp=$vv['pid'];
				if($pp==$cid)
				{ 
					$ids.=maketree($ar,$cid,$pre."&nbsp;&nbsp;");
					break;
				}
			}
		}
	}
	return $ids;
}
?>