<?php 
/*******************************************************************
 * 版权协议：2009-2019
 * 版权所有: PHP-北京金南曦网络技术有限公司旗下PHPWMS，PHP商城系统技术支持中心http://www.php188.net，并保留所有权利。 
* PHP商城系统网址: http://www.php188.com
 * PHPWMS系统网址：http://www.phpwms.com
 * 销售电话：010-87875088
 * 销售电话：010-87875188 
*------------------------------------------------------------------
 * 这不是一个完全免费软件！您只能在不用于商业目的的前提下对程序代码进
 * 行修改和使用；不允许对程序代码以任何形式任何目的的再发布。
 *------------------------------------------------------------------
 * 文件名称：admin_model_operate.php
 * 摘    要：处理文章下载等模型的逻辑处理
 * 适用范围：PHPWMS 1.0
 * 版    本：1.0
 *------------------------------------------------------------------
 * Script Written By phpwms项目组
 * 最后更新： 2009-09-24 phpwms 由PHP金南曦网络技术有限公司整理发布
 *******************************************************************/
if(!defined('IN_SYS'))exit('access die');
$do = $_GET['task'];
/*权限判断*/
$task = $_REQUEST['task'];
$channel_type = to_int($_REQUEST['channel_type']);//所属模型
if($task == 'add'){
	switch ($channel_type){
		case '1':
			if (!getAdminPri('3103')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '2':
			if (!getAdminPri('3203')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '3':
			if (!getAdminPri('3303')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '4':
			if (!getAdminPri('4403')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
	}
}elseif ($task == 'list'){
	switch ($channel_type){
		case '1':
			if (!getAdminPri('3104')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '2':
			if (!getAdminPri('3204')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '3':
			if (!getAdminPri('3304')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '4':
			if (!getAdminPri('4404')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
	}
}elseif ($task == 'recycle'){
	switch ($channel_type){
		case '1':
			if (!getAdminPri('3105')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '2':
			if (!getAdminPri('3205')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '3':
			if (!getAdminPri('3305')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
		case '4':
			if (!getAdminPri('4405')) {
		   		exit(NO_AUTH_LOGIN);
			}
			break;
	}
}

function insert_attr_extend_data($id,$type_id,$extend_value){
		global $db;
		if(empty($id) || empty($type_id) || !is_array($extend_value))return ;
		foreach ($extend_value as $k=>$e){
			$extend_data_temp[] = array(
				'article_id'=>to_int($id),
				'type_id'=>to_int($type_id),
				'value'=>$e,
				'attr_id'=>to_int($k),
			);
		}
		//写扩展属性
	$db->insert($extend_data_temp,'extend_type_attr_bind');
}
function update_category_total($do_ids){
	global $db;
	$cate_data  = $db->fetch("SELECT `category_id` FROM ##__contents WHERE `c_id` IN ($do_ids) ;");
	foreach ($cate_data as $c){
		$totals = $db->fetch("SELECT COUNT(*) AS T FROM ##__contents WHERE `category_id` = '$c[category_id]' AND `is_recycle` = '0'",TRUE);
		$total = $totals['T'];
		$db->update(array('total'=>$total),'category',array('category_id'=>$c['category_id']));
	}
}
if(is_post()){
	$task = $_POST['task'];
	$model = $_POST['model'];
	switch ($task){
		case 'operation':
			$ids = $_POST['ids'];
			if(empty($ids)|| !is_array($ids))exit($sp->bgmsg('请选择要操作的数据.'));
			foreach ($ids as &$i)$i = to_int($i);
			$ids = array_filter($ids);
			if(empty($ids))exit($sp->bgmsg('请选择要操作的数据'));
			$do_ids = join(',',$ids);
			$opt_name = $_POST['mo_opt'];
			switch ($opt_name){
				case 'delete'://到回收站
					$db->query("UPDATE ##__contents SET `is_recycle` = '1' WHERE `c_id` in ($do_ids);");
					//先把分类T出来
					update_category_total($do_ids);
					//全部删除缓存
					$q = delete_cache();
					exit($sp->bgmsg('操作成功,页面将跳转.'));
					//删扩展属性
					break;
				case 'to_hot':
					$sql = "UPDATE ##__contents SET `is_hot` = '1' WHERE `c_id` in ($do_ids);";
					remove_pub_cache(FALSE,$model,'hot');
					break;
				case 'to_unhot':
						$sql = "UPDATE ##__contents SET `is_hot` = '0' WHERE `c_id` in ($do_ids);";
						remove_pub_cache(FALSE,$model,'hot');
					break;
				case 'to_cat_top'://设置分类置顶 
					$sql = "UPDATE ##__contents SET `is_top` = '1' WHERE `c_id` in ($do_ids);";
					remove_pub_cache(FALSE,$model,'top');
					break;
				case 'to_all_top'://总置顶 全局总置顶to_all_top
					$sql = "UPDATE ##__contents SET `is_top` = '2' WHERE `c_id` in ($do_ids);";
					remove_pub_cache(FALSE,$model,'top_all');
					break;
				case 'set_pass'://设置通过 审核通过
					$sql = "UPDATE  ##__contents SET `is_show` = '1' WHERE `c_id` in ($do_ids);";
					delete_cache();
					break;
				case 'set_unpass'://设置取消即不显示文章
					$sql = "UPDATE  ##__contents SET `is_show` = '0'  WHERE `c_id` in ($do_ids);";
					delete_cache();
					break;
				case 'set_new'://设置为最新
					$sql = "UPDATE ##__contents SET `is_new` = '1' WHERE `c_id` in ($do_ids);";
					remove_pub_cache(FALSE,$model,'new');
					break;
				case 'set_unnew'://取消最新
					$sql = "UPDATE ##__contents SET `is_new` = '0' WHERE `c_id` in ($do_ids);";
					remove_pub_cache(FALSE,$model,'new');
					break;
				case 'delete_f'://彻底删除
					$db->query("DELETE FROM ##__extend_type_attr_bind WHERE `article_id` in ($do_ids);");
					$db->query("DELETE FROM ##__contents WHERE `c_id` in ($do_ids);");
					delete_cache();
					//删扩展属性
					$sp->bgmsg('删除文章成功.');
					exit();
					break;
				case 'to_common'://返回正常模式
					$sql = "UPDATE ##__contents SET `is_recycle` = '0' WHERE `c_id` in ($do_ids);";
					$db->query($sql);
					update_category_total($do_ids);
					delete_cache();
					exit($sp->bgmsg('操作成功,页面将跳转.'));
					break;
				default:dump($_POST);exit($sp->bgmsg('参数错误'));
			}
			$msg = '操作成功,页面将跳转.';
			$db->query($sql);
			exit($sp->bgmsg($msg));
			break;
		case 'add':
		case 'edit':
			$edit = $task=='edit'?TRUE:FALSE;
			$post = $_POST;
			$_SESSION['post_data'] = $post;
			$title = $post['long_title'];
			if(empty($title))exit($sp->bgmsg('请写上标题'));
			$content = $post['content'];
			if(empty($content))exit($sp->bgmsg('请写上内容'));
			$category_id = to_int($_POST['category_id']);
			if(empty($category_id))exit($sp->bgmsg('请选择分类'));
			$channel_types = to_int($_POST['channel_type']);
			$channel_id  = to_int($post['channel_id']);
			if(empty($channel_types))exit($sp->bgmsg('参数错误'));
			if($edit){
				$id = to_int($_POST['id']);
				if(empty($id) || empty($channel_id))exit($sp->bgmsg('参数错误'));
				$old_data = $db->fetch("SELECT * FROM ##__contents WHERE `c_id` = '$id' LIMIT 0,1",TRUE);
				if(empty($old_data))exit($sp->bgmsg('无可用数据'));
				$check_data = $db->fetch("SELECT `c_id` FROM ##__contents WHERE `long_title` = '$title'
					 AND `channel_model` = '$channel_types' AND `c_id` <> '$id' LIMIT 0,1;",TRUE);
					if(!empty($check_data))exit($sp->bgmsg('已存在相同的标题,请重新填写.'));
			}else{
				$check = $db->fetch("SELECT `c_id` FROM ##__contents WHERE `long_title` = '$title'
					 AND `channel_model` = '$channel_types' LIMIT 0,1; ",TRUE);
					if(!empty($check))exit($sp->bgmsg('已存在相同的标题.请重新填写'));
			}
			//扩展属性处理
			$extend_type_id = to_int($_POST['type_id']);
			$is_show  = to_int($post['is_show']);
			
			$short_content = $post['short_content'];
			
			if($model=='product'){
				$product_price = abs(floatval($_POST['product_price']));
			}
			$product_price = empty($product_price)?0:$product_price;
			$insert_data = array(
				'passwords'=>$post['passwords'],
				'short_title'=>$post['short_title'],
				'long_title'=>$post['long_title'],
				'is_show'=>to_int($post['is_show']),
				'is_hot'=>to_int($post['is_hot']),
				'is_top'=>to_int($post['is_top']),
				'is_new'=>to_int($post['is_new']),
				'short_content'=>filter_site_url_encode($short_content),
				'content'=>filter_site_url_encode($post['content']),
				'thumb'=>filter_site_url_encode($post['thumb']),
				'is_pic'=>to_int($post['is_pic']),
				'is_index_slide'=>!empty($post['is_index_slide'])?1:0,
				'is_show'=>$is_show,
				'post_time'=>time(),
				'edit_time'=>time(),
				'big_pic'=>filter_site_url_encode($post['big_pic']),
				'post_user'=>empty($post['post_user'])?$_SESSION['admin_user']:$post['post_user'],
				'hits'=>to_int($post['hits']),
				'out_link'=>$post['out_link'],
				'channel_model'=>$channel_types,
				'category_id'=>$category_id,
				'source'=>$post['source'],
				'type_id'=>$extend_type_id,/*扩展属性ID*/
				'channel_id'=>$channel_id,
				'ip'=>get_ip(),
				'product_price'=>$product_price,
				'attach_size'=>$_POST['attach_size'],
				'attach_link_1'=>filter_site_url_encode($_POST['attach_link_1']),
				'attach_link_2'=>filter_site_url_encode($_POST['attach_link_2']),
				'attach_link_3'=>filter_site_url_encode($_POST['attach_link_3']),
				'seo'=>serialize_deep($_POST['seo']),
			);
			if($edit){
				unset($insert_data['post_time']);
			}
			$extend_value = $_POST['extend_val'];
			if(!$edit){
				$db->insert($insert_data,'contents');
				$in_last = $last_insert_id = $db->get_last_insert_id();
				$cc_id = get_category('','',$category_id);
				if(empty($cc_id)){
					$sp->bgmsg('参数错误');
					$db->query("DELETE FROM ##__contents WHERE `c_id` = '$in_last'");
				}
				$db->update(array('channel_id'=>$cc_id['channel_id']),'contents',array('c_id'=>$in_last));
				if($last_insert_id && !empty($extend_type_id))insert_attr_extend_data($last_insert_id,$extend_type_id,$extend_value);
				$msg = '添加成功,您还可以继续添加.';
				$url = 'admincp.php?action=model_operate&task=add&channel_type='.$channel_types;
			}else{
				$db->update($insert_data,'contents',array('c_id'=>$id));
				/*先检查这个文章有扩展属性没有*/
				$check_exist = $db->fetch("SELECT `type_id` FROM `##__extend_type_attr_bind` WHERE `article_id` = '$id' limit 0,1",true);
				/*如果存在扩展属性*/
				if(!empty($check_exist)){
					/*如果对应的类型不同*/
					$old_data_type_id = $old_data['type_id'];
					$curent_type_id = $extend_type_id;
					if($old_data_type_id!=$curent_type_id){
						$db->query("DELETE FROM ##__extend_type_attr_bind WHERE `article_id` = '$id';");
						/*删了后重新写入*/
						insert_attr_extend_data($id,$extend_type_id,$extend_value);
					}else{/*更新扩展属性*/
						foreach ($extend_value as $k=>$v){
							$db->update(array('value'=>$v),'extend_type_attr_bind',array('article_id'=>$id,'attr_id'=>$k,'type_id'=>$extend_type_id));
						}	
					}
				}else{/*没有则直接写入*/
					insert_attr_extend_data($id,$extend_type_id,$extend_value);
				}
				$msg = '编辑成功';
				$url = 'admincp.php?action=model_operate&task=list&channel_type='.$channel_types;
			}
			//缓存分类下的文章索引ID
			//php188StaticCache::getInstance()->remove('phpwms_category_content_cache_'.$category_id);
			$cate_content_data = $db->fetch("SELECT `c_id` FROM ##__contents WHERE `category_id` in($category_id) AND `is_show` = '1' AND `is_recycle` = '0'  ORDER BY 'c_id' ;");
			$total_all = count($cate_content_data);
			$db->update(array('total'=>$total_all),'category',array('category_id'=>$category_id));
			if($category_id!=$old_data['category_id']){//如果跟换了分类
				$o_category_id = $old_data['category_id'];
				$o_category_id = empty($o_category_id)?$category_id:$o_category_id;
				$sq = "SELECT `c_id` FROM ##__contents WHERE `category_id` IN($o_category_id) AND `is_show` = '1' AND `is_recycle` = '0'  ORDER BY 'c_id';";
				$c = $db->fetch($sq);
				$totals = count($c);
				$db->query("UPDATE ##__category SET `total`='$totals' WHERE `category_id`='$o_category_id'");
				//php188StaticCache::getInstance()->remove('phpwms_category_content_cache_'.$old_data['category_id']);
			}
			//php188StaticCache::getInstance()->remove('phpwms_channel_categorys');
			remove_pub_cache();
			//delete_cache();
			$_SESSION['post_data'] = '';
			exit($sp->bgmsg($msg,$url));
			break;
		default:exit('invaild post data;');
	}
	
}
$channel_id = to_int($_REQUEST['channel_id']);//频道ID
$channel_type = to_int($_REQUEST['channel_type']);//所属模型
if(empty($channel_type))exit($sp->bgmsg('缺少模型'));
$id = to_int($_REQUEST['id']);//操作ID
$category_id = to_int($_GET['category_id']);
$model_list = get_models($channel_type);
$tpl->assign('channel_type',$channel_type);
$tpl->assign('channel_id',$channel_id);
$tpl->assign('task',$do);
$tpl->assign('model',get_action('',$channel_type));
switch ($do){
	case 'search':
		$key = $_GET['key'];
		$channel = to_int($_GET['channel_type']);
		$sql = "SELECT COUNT(1) AS T FROM ##__contents AS CT ,##__category AS CAT
			WHERE CT.`category_id` = CAT.`category_id` AND 
			CAT.`channel_model` = '$channel_type' AND 
			 (`long_title` like '%$key%' or `short_title` like '%$key%' OR `content` like '%$key%')
			 GROUP BY CT.`c_id` ORDER BY CT.`c_id` ";
		$data = $db->fetch($sql,TRUE);
		$total = $data['T'];
		$navs .=  $model_list['cn_name'].'搜索';
		$se_sql = "SELECT * FROM ##__contents AS CT ,##__category AS CAT
			WHERE CT.`category_id` = CAT.`category_id` AND 
			CAT.`channel_model` = '$channel_type' AND 
			 (`long_title` like '%$key%' or `short_title` like '%$key%' OR `content` like '%$key%')
			 GROUP BY CT.`c_id` ORDER BY CT.`c_id` ";
		$e_data = page_for_db_extend($total,$se_sql,"admincp.php?action=model_operate&task=search&channel_type=$channel&key=$key",20);
		$tpl->assign('data',$e_data);
		$tpl->assign('task','search');
		break;
	case 'ajax_call_types':
		$type_id = to_int($_GET['type_id']);
		if(empty($type_id))exit('参数错误');
		$id = to_int($_GET['id']);
		$data = $db->fetch("SELECT * FROM ##__extend_attr WHERE `attr_type_id` = '$type_id';");
		$attrs = array();
		if(!empty($id)){
			$attrs = $db->fetch("SELECT * FROM ##__extend_type_attr_bind  WHERE `article_id` = '$id' limit 0,1; ");
			$attrs = array_group_by($attrs,'attr_id');
		}
		$attr_keys = array_keys($attrs);
		foreach ($data as &$d){
			if(in_array($d['attr_id'],$attr_keys))$d = array_merge($d,$attrs[$d['attr_id']][0]);
			if(!empty($d['attr_value'])){
				$d['attr_extend_val'] = array_filter(array_map("trim",explode("\n",$d['attr_value'])));
			}
		}
		$tpl->assign('extend_data',$data);
		break;
	case 'add':
	case 'edit':
		if($task=='edit'){
			$id = to_int($_GET['id']);
			$channel_id = to_int($_GET['channel_id']);
			if(empty($id) || empty($channel_id))$sp->bgmsg('参数错误.');
			$tpl->assign('id',$id);
			$data = $db->fetch("SELECT * FROM ##__contents WHERE `c_id`  = '$id' limit 0,1;",TRUE);
			if(empty($data))$sp->bgmsg('无可用数据,请检查.');
			$data['seo'] = unserialize_deep($data['seo']);
			$data = filter_site_url_decode($data);
		}
		if($task!='edit' && $_SESSION['post_data']){
			$data = $_SESSION['post_data'];
		}
		//获得模型
		$curent_model = array();
		foreach ($model_list as $list){
			if($list['id']==$channel_type){
				$curent_model = $list;
				break;
			}
		}
		//通过指定模型获得该模型下的频道
		$channels = get_channels($channel_type);
		$cat = get_category($channel_type);
		if(!class_exists('WMSTree'))require_once  PUB_CLASS.'phpwms.tree.class.php';
		$t = new WMSTree();
		$cat = $t->building_tree($cat);
		$categories = array_group_by($cat,'channel_name');
		require PUB_CLASS.'phpwms.kineditor.php';
		$editor = new editor();
		$editor->instanceName = 'content';
		$editor->value = filter_site_url_decode($data['content']);
		$simple_editor = new editor();
		$simple_editor->instanceName = 'short_content';
		$simple_editor->value = filter_site_url_decode($data['short_content']);
		$simple_editor->model = 'basic';
		$simple_editor->height = '200';
		assign(array(
			'channel_id'=>$channel_id,
			'simple_content'=>$simple_editor->create(),
			'categories'=>$categories,
			'editor'=>$editor->create(),
			'extend_type'=>get_types(),
		));
		$tpl->assign('data',$data);
		$type_name = $do=='add'?'添加':'编辑';
		$navs  = '<a href="admincp.php?action=model_operate&channel_type='.$channel_type.'">'.$model_list['cn_name'].'管理</a>&nbsp;&raquo;&nbsp;'.$type_name.$model_list['cn_name'];
		break;
	case 'recycle':
	default://默认列表
		$recycles = $task=='recycle'?"  AND CT.`is_recycle` = '1' ":" AND CT.`is_recycle` = '0' ";// AND CT.`is_recycle` = '0'
		$get_type = $_GET['type'];
		$types = '';
		switch ($get_type){
			case 'top_all'://全局置顶
					$append_sql = " AND CT.`is_top` = '2' ";
					$order = "  CT.`is_top` ";
				break;
			case 'top_part':
				$append_sql = " AND  CT.`is_top` = '1'";
				$order = "  CT.`is_top` ";
				break;
			case 'new'://最新
				$append_sql = " AND  CT.`is_new` = '1'";
				$order = "  CT.`is_new` ";
				break;
			case 'hot'://最新
				$append_sql = " AND  CT.`is_hot` = '1'";
				$order = "  CT.`is_hot` ";
				break;
			case 'pic'://最新
				$append_sql = " AND  CT.`is_pic` = '1' AND CT.`thumb` <> ''";
					$order = "  CT.`is_pic`  ";
				break;
			case 'passed':
				$append_sql  = " AND  CT.`is_show` = '1'";
					$order = "  CT.`is_show` ";
				break;
			case 'need_check':
				$append_sql  = " AND  CT.`is_show` = '0'";
				$order = "  CT.`is_show` ";
				break;
			default:$append_sql = '';	
			$order = "  CT.`c_id` DESC  ";
		}
		$channel_id = to_int($_GET['channel_id']);
		$channel_sql = !empty($channel_id)?" AND CT.`channel_id` = '$channel_id' ":'';
		if(!empty($channel_id)){
			$order = " CT.`channel_id` ";
		}
		$category_id = to_int($_GET['category_id']);
		$category_sql = !empty($category_id)?" AND CT.`category_id`='$category_id' ":' ';
		if(!empty($category_id)){
			$order  = " CT.`category_id`  ";
		}
		$total_sql = "SELECT COUNT(1) AS T FROM ##__contents AS CT WHERE
		 CT.`channel_model` = '$channel_type' $recycles $append_sql $category_sql $channel_sql
			ORDER BY CT.`c_id` LIMIT 0,1;
		";
		$F = $db->fetch($total_sql,TRUE);
		$total = $F['T'];
		if($total>0){
			$sql = "SELECT CT.`c_id` FROM 
				##__contents AS CT
				WHERE 
				CT.`channel_model` in($channel_type) $recycles $append_sql $category_sql $channel_sql 
				 ORDER BY CT.`c_id` DESC ";
					
			$data = page_for_db_extend($total,$sql,"admincp.php?action=model_operate&task=$task&channel_type=$channel_type&type=$get_type&category_id=$category_id&channel_id=$channel_id",20);
			$ids =  join(',',mulitarray_to_array($data['data'],FALSE));
			$se = "SELECT * FROM ##__contents AS CT WHERE CT.`c_id` in ($ids) ORDER BY c_id DESC ";
			$d =  $db->fetch($se);
			foreach ($d as &$q){
				$cat = get_category('','',$q['category_id']);
				$ch = get_channels('',$q['channel_id']);
				$q['channel_name'] = $ch['channel_name'];
				$q['category_name'] = $cat['category_name'];
				$q['privew_link'] = building_url('content','',array($q['c_id']));
			}
			$data['data'] = filter_site_url_decode($d);
		}else{
			$data['total'] = 0;
			$data['data'] = array();
		}
		$tpl->assign('data',$data);
		$tpl->assign('task','list');
		$recycle_name = $task=='recycle'?'回收站':'列表';
		$tpl->assign('is_recycle',$task);
		$tpl->assign(array(
			'model'=>get_action('',$channel_type),
		));
		$navs  = '<a href="admincp.php?action=model_operate&task=list&channel_type='.$channel_type.'">管理'.$model_list['cn_name'].'</a>&nbsp;&raquo;&nbsp;'.$model_list['cn_name'].$recycle_name;
}
$tpl->assign('admin_nav',shownav($navs));
$tpl->display('model_oprator.tpl');
?>