<?php

class SoftAction extends CommonContentAction {
	
	public function index() {

		$pid = I('pid', 0, 'intval');//類別ID
		$keyword = I('keyword', '', 'htmlspecialchars,trim');//關鍵字

		//所有子欄目列表
		import('Class.Category', APP_PATH);
		$cate = getCategory();
		$this->subcate = Category::clearCate(Category::getChilds($cate, $pid),'type');
		$this->poscate = Category::getParents($cate, $pid);
		
		
		if ($pid) {
			$idarr = Category::getChildsId($cate, $pid, 1);//所有子類ID
			//$where = array('soft.status' => 0, 'cid' => $pid);
			$where = array('soft.status' => 0, 'cid' => array('in', $idarr));
		}else {
			$where = array('soft.status' => 0);
		}
		
		if (!empty($keyword)) {
			$where['soft.title'] = array('LIKE', "%{$keyword}%");
		}
		
		//分頁
		import('Class.Page', APP_PATH);
		$count = D2('ArcView','soft')->where($where)->count();

		$page = new Page($count, 10);
		$page->rollPage = 7;
		$page->setConfig('theme','%totalRow% %header%  %first% %upPage% %linkPage% %downPage% %end% %nowPage%/%totalPage% 頁');
		$limit = $page->firstRow. ',' .$page->listRows;
		$art = D2('ArcView','soft')->nofield('content,pictureurls,updatelog,downlink')->where($where)->order('soft.id DESC')->limit($limit)->select();

		$this->pid = $pid;
		$this->keyword = $keyword;
		$this->page = $page->show();
		$this->vlist = $art;
		$this->type = '軟件下載列表';

		$this->display();
	}
	//添加
	public function add() {

		
		//當前控制器名稱		
		$actionName = strtolower($this->getActionName());
		$this->pid = I('pid', 0, 'intval');

		if (IS_POST) {
			$this->addPost();
			exit();
		}


		$cate = getCategory(2);
		import('Class.Category', APP_PATH);
		$cate = Category::toLevel($cate);
		$this->softtypelist = getArrayOfItem('softtype');
		$this->softlanguage = getArrayOfItem('softlanguage');
		$this->type = "添加軟件下載";
		$this->cate = Category::getLevelOfModel($cate, $actionName);
		$this->flagtypelist = getArrayOfItem('flagtype');//文檔屬性
		$this->display();
	}

	//
	public function addPost() {

		$pid = I('pid', 0, 'intval');
		$cid = I('cid', 0, 'intval');
		$title = I('title', '', 'htmlspecialchars,rtrim');
		$flags = I('flags', array(),'intval');
		$jumpurl = I('jumpurl', '');
		$description = I('description', '');
		$downlink = I('downlink', '');
		$content = I('content', '', '');			
		$updatelog = I('updatelog', '', '');
		$updatelog = str_replace("\n", '<br />', $updatelog);
		$pic = I('litpic', '', 'htmlspecialchars,trim');
		$updatetime = I('updatetime', time(), 'strtotime');
		if (empty($title)) {
			$this->error('名稱不能為空');
		}
		if (!$cid) {
			$this->error('請選擇欄目');
		}
		$pid = $cid;//轉到自己的欄目		

		if (empty($description)) {			
			$description = str2sub(strip_tags($content), 120);
		}

		//圖片標誌
		if (!empty($pic) && !in_array(B_PIC, $flags)) {
			$flags[] = B_PIC;
		}
		$flag = 0;
		foreach ($flags as $v) {
			$flag += $v;
		}

		$downlink = str_replace("\n", '|||', $downlink);
		$os = I('os', array());
		$os = implode(' ', $os);


		//獲取屬於分類信息,得到modelid
		import('Class.Category', APP_PATH);			
		$selfCate = Category::getSelf(getCategory(0), $cid);//當前欄目信息
		$modelid = $selfCate['modelid'];

		
		$data =array(
			'title' => $title,
			'color' => I('color', 'htmlspecialchars,trim'),
			'version' => I('version', '', 'htmlspecialchars,trim'),
			'filesize' => I('filesize', '', 'htmlspecialchars,trim'),
			'downlink' => $downlink,
			'softtype' => I('softtype', 0, 'intval'),
			'language' => I('language', 0, 'intval'),
			'os' => $os,
			'cid'	=> $cid,
			'litpic'	=> $pic,
			'keywords' => I('keywords','','htmlspecialchars,trim'),
			'description' => $description,
			'content' => $content,
			'updatelog' => $updatelog,			
			'publishtime' => I('publishtime', time(),'strtotime'),
			'updatetime' => $updatetime,
			'click' => rand(10,95),
			'status' => 0,
			'commentflag' => I('commentflag', 0,'intval'),			
			'flag'	=> $flag,
			'jumpurl' => $jumpurl,
			'aid'	=> $_SESSION[C('USER_AUTH_KEY')]

		);
		
		if($id = M('soft')->add($data)) {

			//內容中的圖片
			$img_arr = array();
			$pic_first = array();
			$reg = "/<img[^>]*src=\"((.+)\/(.+)\.(jpg|gif|bmp|png))\"/isU";		
			preg_match_all($reg, $data['content'], $img_arr, PREG_PATTERN_ORDER);
			// 匹配出來的不重複圖片
			$img_arr = array_unique($img_arr[1]);
			$attid_arr = array();
			
			if (!empty($img_arr)) {

				if(!empty($_SERVER['HTTP_HOST']))
			        $baseurl = 'http://'.$_SERVER['HTTP_HOST'];
			    else
			        $baseurl = rtrim("http://".$_SERVER['SERVER_NAME'],'/');
			    foreach ($img_arr as $k => $v) {
			    	$img_arr[$k] = str_replace($baseurl, '', $v);//清除域名前綴			    	
			    }

				$attid = M('attachment')->field('id,filepath')->where(array('filepath' => array('in', $img_arr)))->select();
				
				if ($attid) {

					//只有縮略圖為空時,才提取第一張圖片
					if (empty($pic)) {
						//取出本站內的第一張圖
						foreach ($img_arr as $v) {
							foreach ($attid as $v2) {
								if ($v == $v2['filepath']) {
									$pic_first = $v2;
									break 2;
								}
							}
						}
					}
					//attid 數組
					foreach ($attid as $v) {
						$attid_arr[] = $v['id'];
					}
				}
				
			}	

			//更新上傳附件表
			if (!empty($pic)) {

				$pic = preg_replace('/!(\d+)X(\d+)\.jpg$/i', '', $pic);//清除縮略圖的!200X200.jpg後綴
				$attid = M('attachment')->where(array('filepath' => $pic))->getField('id');
				if($attid){
					$attid_arr[] = $attid;
				}
			}else if (!empty($pic_first)) {
				//更新表字段
				$imgtbSize = explode(',', C('cfg_imgthumb_size'));//配置縮略圖第一個參數
                $imgTSize = explode('X', $imgtbSize[0]);
                $updata = array('id' => $id, 'litpic' => get_picture($pic_first['filepath'], $imgTSize[0], $imgTSize[1]));
                if (!in_array(B_PIC, $flags)) {
					$updata['flag'] = array('exp','flag+'.B_PIC);
				}                
				M('soft')->save($updata);
			}

			//attachmentindex入庫
			if (!empty($attid_arr)) {
				$attid_arr = array_unique($attid_arr);
				$dataAtt = array();
				foreach ($attid_arr as $v) {
					$dataAtt[] = array('attid' => $v,'arcid' => $id, 'modelid' => $modelid);
				}
				M('attachmentindex')->addAll($dataAtt);
			}

			
			//更新靜態緩存
			delCacheHtml('List/index_'.$cid, false, 'list:index');	
			delCacheHtml('Index_index', false, 'index:index');

			$this->success('添加成功',U(GROUP_NAME. '/Soft/index', array('pid' => $pid)));
		}else {
			$this->error('添加失敗');
		}
	}

	//編輯文章
	public function edit() {
		//當前控制器名稱
		$id = I('id', 0, 'intval');
		$actionName = strtolower($this->getActionName());
		$this->pid = I('pid', 0, 'intval');

		if (IS_POST) {
			$this->editPost();
			exit();
		}

		$cate = getCategory(2);
		import('Class.Category', APP_PATH);
		$cate = Category::toLevel($cate);
		$this->cate = Category::getLevelOfModel($cate, $actionName);

		$this->softtypelist = getArrayOfItem('softtype');
		$this->softlanguage = getArrayOfItem('softlanguage');
		$vo = M($actionName)->find($id);
		$vo['downlink'] = str_replace('|||', "\n", $vo['downlink']);		
		$vo['updatelog'] = htmlspecialchars(str_replace('<br />', "\n", $vo['updatelog']));
		$vo['content'] = htmlspecialchars($vo['content']);
		$vo['os'] = explode(' ', $vo['os']);
		
		$this->vo = $vo;
		$this->flagtypelist = getArrayOfItem('flagtype');//文檔屬性
		$this->type = '修改軟件下載';
		$this->display();
	}


	//修改文章處理
	public function editPost() {

		$data =array(
			'id'	=> I('id', 0, 'intval'),
			'title' => I('title','','htmlspecialchars,rtrim'),			
			'color' => I('color', 'htmlspecialchars,trim'),
			'version' => I('version', '', 'htmlspecialchars,trim'),
			'filesize' => I('filesize', '', 'htmlspecialchars,trim'),
			'downlink' => I('downlink', ''),
			'softtype' => I('softtype', 0, 'intval'),
			'language' => I('language', 0, 'intval'),
			'cid'	=> I('cid', 0, 'intval'),
			'litpic'	=> I('litpic', ''),
			'keywords' => I('keywords','','htmlspecialchars,trim'),
			'description' => I('description','','htmlspecialchars,trim'),
			'content' => I('content', '', ''),
			'updatelog' => str_replace("\n", '<br />', I('updatelog', '', '')),
			'publishtime' => I('publishtime', time(),'strtotime'),
			'updatetime' => I('updatetime', time(), 'strtotime'),
			'commentflag' => I('commentflag', 0,'intval'),
			'jumpurl' => I('jumpurl', ''),

		);

		$id = $data['id'];
		$pid = I('pid', 0, 'intval');
		$flags = I('flags', array(),'intval');
		$pic = $data['litpic'];

		if (empty($data['title'])) {
			$this->error('標題不能為空');
		}
		if (!$data['cid']) {
			$this->error('請選擇欄目');
		}		
		$pid = $data['cid'];//轉到自己的欄目

		if (empty($data['description'])) {			
			$data['description'] = str2sub(strip_tags($data['content']), 120);
		}


		//圖片標誌
		if (!empty($pic) && !in_array(B_PIC, $flags)) {
			$flags[] = B_PIC;
		}
		$data['flag'] = 0;
		foreach ($flags as $v) {
			$data['flag'] += $v;
		}


		$data['downlink'] = str_replace("\n", '|||', $data['downlink']);
		$os = I('os', array());
		$data['os'] = implode(' ', $os);
		


		//獲取屬於分類信息,得到modelid
		import('Class.Category', APP_PATH);			
		$selfCate = Category::getSelf(getCategory(0), $data['cid']);//當前欄目信息
		$modelid = $selfCate['modelid'];


		if (false !== M('soft')->save($data)) {
			//del
			M('attachmentindex')->where(array('arcid' => $id, 'modelid' => $modelid))->delete();
			
			//內容中的圖片
			$img_arr = array();
			$pic_first = array();
			$reg = "/<img[^>]*src=\"((.+)\/(.+)\.(jpg|gif|bmp|png))\"/isU";		
			preg_match_all($reg, $data['content'], $img_arr, PREG_PATTERN_ORDER);
			// 匹配出來的不重複圖片
			$img_arr = array_unique($img_arr[1]);
			$attid_arr = array();
			
			if (!empty($img_arr)) {

				if(!empty($_SERVER['HTTP_HOST']))
			        $baseurl = 'http://'.$_SERVER['HTTP_HOST'];
			    else
			        $baseurl = rtrim("http://".$_SERVER['SERVER_NAME'],'/');
			    foreach ($img_arr as $k => $v) {
			    	$img_arr[$k] = str_replace($baseurl, '', $v);//清除域名前綴			    	
			    }

				$attid = M('attachment')->field('id,filepath')->where(array('filepath' => array('in', $img_arr)))->select();
				
				if ($attid) {

					//只有縮略圖為空時,才提取第一張圖片
					if (empty($pic)) {
						//取出本站內的第一張圖
						foreach ($img_arr as $v) {
							foreach ($attid as $v2) {
								if ($v == $v2['filepath']) {
									$pic_first = $v2;
									break 2;
								}
							}
						}
					}
					//attid 數組
					foreach ($attid as $v) {
						$attid_arr[] = $v['id'];
					}
				}
				
			}	

			//更新上傳附件表
			if (!empty($pic)) {

				$pic = preg_replace('/!(\d+)X(\d+)\.jpg$/i', '', $pic);//清除縮略圖的!200X200.jpg後綴
				$attid = M('attachment')->where(array('filepath' => $pic))->getField('id');
				if($attid){
					$attid_arr[] = $attid;
				}
			}else if (!empty($pic_first)) {
				//更新表字段
				$imgtbSize = explode(',', C('cfg_imgthumb_size'));//配置縮略圖第一個參數
                $imgTSize = explode('X', $imgtbSize[0]);
                $updata = array('id' => $id, 'litpic' => get_picture($pic_first['filepath'], $imgTSize[0], $imgTSize[1]));
                if (!in_array(B_PIC, $flags)) {
					$updata['flag'] = array('exp','flag+'.B_PIC);
				}                
				M('soft')->save($updata);
			}

			//attachmentindex入庫
			if (!empty($attid_arr)) {
				$attid_arr = array_unique($attid_arr);
				$dataAtt = array();
				foreach ($attid_arr as $v) {
					$dataAtt[] = array('attid' => $v,'arcid' => $id, 'modelid' => $modelid);
				}
				M('attachmentindex')->addAll($dataAtt);
			}


			//更新靜態緩存
			delCacheHtml('List/index_'.$data['cid'].'_', false, 'list:index');
			delCacheHtml('List/index_'.$selfCate['ename'], false, 'list:index');//還有只有名稱
			delCacheHtml('Show/index_*_'. $id, false, 'show:index');//不太精確，會刪除其他模塊同id文檔		

			$this->success('修改成功', U(GROUP_NAME. '/Soft/index', array('pid' => $pid)));
		}else {

			$this->error('修改失敗');
		}
		
	}

	//移動
	public function move() {
		//當前控制器名稱
		$id = I('key', 0);
		$actionName = strtolower($this->getActionName());
		$pid = I('pid', 0, 'intval');

		if (IS_POST) {
			$id = I('id', 0);
			$cid = I('cid', 0, 'intval');
			if (empty($id)) {
				$this->error('請選擇要移動的文檔');
			}

			if (!$cid) {
				$this->error('請選擇欄目');
			}

			if (false !== M($actionName)->where(array('id'=> array('in', $id)))->setField('cid',$cid)) {
				$this->success('移動成功', U(GROUP_NAME. '/Soft/index', array('pid' => $pid)));
			}else {
				$this->error('移動失敗');
			}			
			exit();
		}

		if (empty($id)) {
			$this->error('請選擇要移動的文檔');
		}
	
		$cate = getCategory(2);
		import('Class.Category', APP_PATH);
		$cate = Category::toLevel($cate);
		$this->cate = Category::getLevelOfModel($cate, $actionName);

		
		$this->id = $id;
		$this->pid = $pid;
		$this->type = '移動文檔';
		$this->display();
	}


	//回收站文章列表
	public function trach() {
		import('Class.Page', APP_PATH);
		$where = array('soft.status' => 1);
		$count = D2('ArcView','soft')->where($where)->count();

		$page = new Page($count, 10);
		$page->rollPage = 7;
		$page->setConfig('theme','%totalRow% %header%  %first% %upPage% %linkPage% %downPage% %end% %nowPage%/%totalPage% 頁');
		$limit = $page->firstRow. ',' .$page->listRows;
		$art = D2('ArcView','soft')->nofield('content,pictureurls,updatelog,downlink')->where($where)->limit($limit)->select();

		$this->pid = I('pid', 0, 'intval');
		$this->page = $page->show();
		$this->vlist = $art;		
		$this->type = '軟件回收站';
		$this->subcate = '';
		$this->display('index');
	}

	//刪除文章到回收站
	public function del() {

		$id = I('id',0 , 'intval');
		$batchFlag = I('get.batchFlag', 0, 'intval');
		//批量刪除
		if ($batchFlag) {
			$this->delBatch();
			return;
		}

		$pid = I('pid',0 , 'intval');//單純的GET沒問題

		if (false !== M('soft')->where(array('id' => $id))->setField('status', 1)) {

			delCacheHtml('Show/index_*_'. $id.'.', false, 'show:index');	
			$this->success('刪除成功', U(GROUP_NAME. '/Soft/index', array('pid' => $pid)));
			
		}else {
			$this->error('刪除失敗');
		}
	}

	//批量刪除到回收站
	public function delBatch() {

		$idArr = I('key',0 , 'intval');
		$pid = I('get.pid', 0, 'intval');

		if (!is_array($idArr)) {
			$this->error('請選擇要刪除的項');
		}

		if (false !== M('soft')->where(array('id' => array('in', $idArr)))->setField('status', 1)) {
			
			//更新靜態緩存
			foreach ($idArr as $v) {
				delCacheHtml('Show/index_*_'. $v.'.', false, 'show:index');	
			}
			$this->success('批量刪除成功', U(GROUP_NAME. '/Soft/index', array('pid' => $pid)));
			
		}else {
			$this->error('批量刪除文失敗');
		}
	}

	//還原文章
	public function restore() {
		
		$id = I('id',0 , 'intval');
		$batchFlag = I('get.batchFlag', 0, 'intval');
		//批量刪除
		if ($batchFlag) {
			$this->restoreBatch();
			return;
		}

		$pid = I('get.pid', 0, 'intval');

		if (false !== M('soft')->where(array('id' => $id))->setField('status', 0)) {
			
			$this->success('還原成功', U(GROUP_NAME. '/Soft/trach', array('pid' => $pid)));
			
		}else {
			$this->error('還原失敗');
		}
	}

	//批量還原文章
	public function restoreBatch() {
		
		$idArr = I('key',0 , 'intval');
		$pid = I('get.pid', 0, 'intval');
		if (!is_array($idArr)) {
			$this->error('請選擇要還原的項');
		}

		if (false !== M('soft')->where(array('id' => array('in', $idArr)))->setField('status', 0)) {
			
			$this->success('還原成功', U(GROUP_NAME. '/Soft/trach', array('pid' => $pid)));
			
		}else {
			$this->error('還原失敗');
		}
	}

	//徹底刪除文章
	public function clear() {

		$id = I('id',0 , 'intval');
		$batchFlag = I('get.batchFlag', 0, 'intval');
		//批量刪除
		if ($batchFlag) {
			$this->clearBatch();
			return;
		}

		$pid = I('get.pid', 0, 'intval');
		$modelid = D2('ArcView','soft')->where(array('id' => $id))->getField('modelid');

		if (M('soft')->delete($id)) {
			// delete picture index
			if ($modelid) {
				M('attachmentindex')->where(array('arcid' => $id , 'modelid' => $modelid ))->delete();//test
			}
			$this->success('徹底刪除成功', U(GROUP_NAME. '/Soft/trach', array('pid' => $pid)));
		}else {
			$this->error('徹底刪除失敗');
		}
	}


	//批量徹底刪除文章
	public function clearBatch() {

		$idArr = I('key',0 , 'intval');		
		$pid = I('get.pid', 0, 'intval');
		if (!is_array($idArr)) {
			$this->error('請選擇要徹底刪除的項');
		}
		$where = array('id' => array('in', $idArr));
		$modelid = D2('ArcView','soft')->where(array('id' => $idArr[0]))->getField('modelid');//

		if (M('soft')->where($where)->delete()) {
			// delete picture index
			if ($modelid) {
				M('attachmentindex')->where(array('arcid' => array('in', $idArr) , 'modelid' => $modelid ))->delete();
			}
			$this->success('徹底刪除成功', U(GROUP_NAME. '/Soft/trach', array('pid' => $pid)));
		}else {
			$this->error('徹底刪除失敗');
		}
	}

	
}



?>