<?php
 /**
 * Magic CMS 内容管理
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Date:2014/12/31
**/
class IndexModule extends CommonModule{
	private $module,$db;
	public function __construct(){
        parent::__construct();
    }

	public function index(){

		$list = M('class')
				->field('catid,pid,name,attribute,status,sorter,ismenu,model')
				->order('sorter asc')
				->all();

		$this->assign('list',$list);
		$this->display();
	}

	public function arclist(){
		$act       = Q('get.act');
		$catid     = Q('get.catid','','intval');
		$flag      = Q('get.flag');
		$model     = Q('get.param','');
		$keywords  = Q('get.keywords');

		$condition = "FROM_UNIXTIME(pubtime,'%Y-%m-%d') <=  FROM_UNIXTIME(sortrank,'%Y-%m-%d') ";

		if ($act==2){$condition .= ' AND arcrank=-1 ';}
		if (!empty($model)){$condition .= ' AND model="'.$model.'" ';}
		if (!empty($flag)) {$condition .= ' AND FIND_IN_SET("'.$flag.'",flag)';} //Flag搜索时执行
		if (!empty($catid)){$condition .= ' AND catid='.$catid;} //栏目搜索时执行
		if (!empty($keywords)){	$condition .= ' AND title like "%'. $keywords . '%"';}  //关键字搜索时执行

		$db = M('art_library');

		$count = $db ->where($condition)->field('id')->count();
		$page  = new Page($count,20);
		$list1 = $db ->where($condition)->field('id')->limit($page->limit())->order('id desc')->all();
		if (!empty($list1)){
			foreach ($list1 as $lv){$strid .=$lv['id'].',';}
			$strid=substr($strid,0,strlen($strid)-1);
			$list=M()
				 ->join('__art_library__ a LEFT JOIN __class__ b ON a.catid=b.catid LEFT JOIN __model__ c ON a.model=c.value')
				 ->field('a.id,a.catid,a.title,a.pubtime,a.status,a.flag,a.image,b.name,c.model,c.value')
				 ->where('a.id in ('.$strid.')')
				 ->order('a.weight asc,a.sortrank desc,a.id desc')
				 ->all();
		}


		$flag = M('flag')->where('status=1')->all(); //文章属性
		$channeltree=$this->channeltree($model);//栏目列表

		$this->assign('flag', $flag);
		$this->assign('channeltree', $channeltree);
		$this->assign('page',$page->show());
		$this->assign('user',$user);
		$this->assign('list',$list);
		$tpl = TPL_PATH.'Archives/'.$model.'.html';
		if (file_exists($tpl)){
			$this->display('Archives/'.$model);
		}else{
			$this->display();
		}
	}



	public function edit(){
		$id            = Q('get.id','','intval');
		$data['model'] = Q('get.param') ? Q('get.param') : 'article';

		if (!empty($id)){
			$data = M()->join('__art_'.$data['model'].'__ a JOIN __art_library__ b ON a.pid=b.id')->where('id='.$id)->find();
			if (empty($data)){$this->alert('对不起，该文档结构已损坏，无法进行编辑。');}
		}

		//获取选项卡
		$model   = M('model')->where("value='".$data['model']."'")->find();
		$tabs    = empty($model['tabs']) ? '' : explode('~',$model['tabs']);

		//载入功能函数
		require FUNCTION_PATH.'/Form.php';

		//读取栏目字段
		$fields = M('fields')->where(array('status'=>1,'model'=>$data['model']))->order('sorter asc')->all();

		foreach ($fields as $k=>$v){
			//调用自定义函数
			if (function_exists('_'.$v['field'])){
				$fucname = '_'.$v['field'];
			}else{
				$fucname = $v['formtype'];
			}
			$v['attribute'] = unserialize($v['attribute']);

			$forminfos[$k]['tabs']      = $v['tabs'];
			$forminfos[$k]['name']     = $v['name'];
			$forminfos[$k]['field']    = $v['field'];
			$forminfos[$k]['layout']   = $v['layout'];
			$forminfos[$k]['formhtml'] = $fucname($v,$data);

		}

		$this->assign('tabs', $tabs);
		$this->assign('forminfos', $forminfos);
		$this->assign('data', $data);
		$this->display(Q('get.tpl',''));
	}


	/**
	 * 保存编辑文档
	 */
	public function save(){
		if(IS_POST){

			$id    = Q('post.id','','intval');
			$opid  = Q('post.opid','','intval');
			$model = Q('post.param','goods');

			//读取模型下所有的字段
			$fields   = M('fields')->where("model='".$model."'")->all();

			foreach ($fields  as $key=>$field) {
				$datas[$field['field']]  = $_POST[$field['field']];

				//检测是否是数组
				if (is_array($datas[$field['field']])  && $field['formtype']!=='datetime'){
					$datas[$field['field']] = serialize($datas[$field['field']]);
				}

				//检测是否为时间
				if ($field['formtype']=='datetime') {
					if (is_array($datas[$field['field']])) {
						foreach ($datas[$field['field']]  as $time) {
							$times[] = strtotime($time);
						}
						$datas[$field['field']] = implode('.',$times);
					}else{
						$datas[$field['field']] = strtotime($datas[$field['field']]);
					}
				}

				//格式货币
				if ($field['formtype']=='currency') {
					$datas[$field['field']] = str_replace(',','',$datas[$field['field']]);
				}
			}

			$datas['model']   = $model;
			$datas['comment'] = Q('post.comment') ? 1 : 0;
			$datas['flag']    = implode(',',Q('post.formsysflag'));
			$datas['sortrank'] = $datas['pubtime'] + ((int)$datas['sortrank'] * 3600 * 24);

			if (Q('post.jump')==1){
				$datas['linkurl'] = $_POST['linkurl'];
				$datas['target']  = Q('post.target','_blank');
			}else{
				$datas['linkurl'] = '';
				$datas['target']  = '';
			}

			if (Q('post.isinter')==1 && empty($datas['abstract'])){
				$datas['abstract'] = str_replace(PHP_EOL, '',String::msubstr(strip_tags($datas['content']),Q('post.internum','200','intval'),0));
			}

			foreach ($fields as $key=>$field){
				if ($field['errortips']!=='' && $_POST[$field['field']]=='' ){
					$this->error($field['errortips']);
				}
			}


			$class= M('class')->field('model,attribute')->where('catid='.$datas['catid'])->find();

			if ($class['model']!=$model){
				$this->error('对不起，你所选择的栏目与当前内容模型不相符');
			}else if ($class['attribute']==2){
				$this->error('对不起，专题或封面不允许发布文档');
			}

			$db = M('art_library');

			//首先插入或更新文档
			if (empty($id)){
				$arcid = $db->data($datas)->add();
				$datas['pid']     = $arcid;
				$arcmd = M('art_'.$model)->data($datas)->add();
			}else{
				$arcid = $db->data($datas)->where('id='.$id)->save();
				$arcmd = M('art_'.$model)->data($datas)->where('pid='.$id)->save();
			}

			$arcid = empty($id) ? $arcid : $id;

			//返回提示信息
			if ($arcid){
				$this->success('文档保存成功',$_POST['reurl']);
			}else{
				$this->error('文档保存失败');
			}

		}else{
			$this->error('非法请求');
		}
	}

	function page(){
		$catid=Q('get.catid','','intval');

		if(!empty($catid)){
			$class= M()->join('__class__ a LEFT JOIN __model__ b ON a.model=b.value')->field('a.name,a.catid,a.content,b.model')->where('a.catid='.$catid)->find();
		}
		$this->assign('model', $model);
		$this->assign('class', $class);
		$this->display('Archives/page');
	}


	function show_page(){

		if(IS_POST){
			$catid = Q('post.catid','','intval');

			$content = $_POST['content'];

			$result = M('class')->data(array('content'=>$content))->where('catid='.$catid)->save();
			if ($result){
				$this->success('保存成功');
			}else{
				$this->error('文档保存失败');
			}
		}else{
			$this->error('非法请求');
		}

	}

	public function del(){
		$id    = Q('get.id','','intval');
		$model = Q('get.param');
		if(empty($id)) $this->error('对不起，参数错误');

		$db = R('art_library');
		$db ->relation = array(
			'art_'.$model => array(
					'type' => HAS_ONE,
					'parent_key'  => 'id',
					'foreign_key' => 'pid',
					'field' => array(),
				)
		 );

		$result = $db->select($id);

		//检测是否存在批量上文件，如果存在则删除上传文件
		foreach ($result[0] as $field){
			if (is_serialized($field) && !empty($field)){
				foreach ($field as $mv){
					$path = str_replace('../','',$mv['path']);
					if (file_exists('../'.$path)){
						unlink('../'.$path);
						unlink(thumb('../'.$path));
					}
				}
			}
		}

		//删除缩略图
		if (file_exists(ROOT_PATH.$result[0]['image'])){
			unlink(ROOT_PATH.$result[0]['image']);
			unlink(thumb(ROOT_PATH.$result[0]['image']));
		}

		//删除文档
		$status = $db->delete($id);

		if($status){
			$this->success('删除成功',$_SERVER['HTTP_REFERER']);
		}else{
			$this->error('对不起，该文档不存在无法删除');
		}
	}

	/**
	 * 批量操作
	 */
	public function batch(){
		$idarr = Q('post.id');
		$act   = Q('get.act');
		$model = Q('get.model');

		if (!Q('post.id')){$this->error('请先选择内容！',$_SERVER['HTTP_REFERER']);}
		if ($act=='sh'){
			foreach ($idarr as $key => $id) {
				$result = M('art_library')->data(array('arcrank'=>0))->where('id='.$id)->save();
			}
		}elseif ($act=='ws'){
			foreach ($idarr as $key => $id) {
				$result = M('art_library')->data(array('arcrank'=>-1))->where('id='.$id)->save();
			}
		}elseif ($act=='del'){
			$db = R('art_library');
			$db ->relation = array(
					'art_'.$model => array(// 关联表
							'type' => HAS_ONE, // 包含一条主表记录
							'parent_key'  => 'id', //扩展数据库表字段
							'foreign_key' => 'pid', //art_library 表字段
							'field' => array(), // 关联表检索的字段
						)
				 );
			foreach ($idarr as $key => $id) {

				$result = $db->select($id);

				//删除缩略图
				if (!empty($result['image']) && file_exists('..'.$result['image'])){
					unlink('..'.$result['image']);
					unlink(thumb('..'.$result['image']));
				}

				foreach ($result as $key=>$field){

					//检测是否存在批量上传文件，如果存在则删除上传文件
					if (is_serialized($field) && !empty($field)){
						foreach ($field as $mv){
							$path = str_replace('../','',$mv['path']);
							if (file_exists('../'.$path)){
								unlink('../'.$path);
								unlink(thumb('../'.$path));
							}
						}
					}

					//检测字段中是否存在图片，如果存在则删除

					$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.".implode("|\.",C('UPLOAD_ALLOW_TYPE.image'))."]))[\'|\"].*?[\/]?>/";
					preg_match_all($pattern,$field,$match);
					if (is_array($match[1])){
						foreach ($match[1] as $mv){
							if (file_exists($mv)){
								unlink($mv);
								unlink(thumb($mv));
							}
						}
					}
				}
				$result = $db->del($id);
			}
		}
		if ($result) {
			$this->success('操作成功',$_SERVER['HTTP_REFERER']);
		}else{
			$this->error('操作失败！');
		}
	}

}