<?php
// 产品内容模型
class ProductModel extends Model {
	public function save($info = array(), $param = array()) {
		if (empty($info)) $info = R('info', 'post');
		$info['id'] = intval($info['id']);
		if (!$info['id']) {
			unset($info['id']);
			$info['userip'] = IP;
			$info['userid'] = get_cookie('userid');
			$info['username'] = get_cookie('username');
			if(empty($info['addtime'])) $info['addtime'] = TIME;
		}
		// 判断标题有效性
		$info['title'] = trim($info['title']);
		if (empty($info['title'])) {
			$this -> error = L('TITLE_EMPTY');
			return false;
		} else {
			$info['title'] = Func :: shtmlspecialchars($info['title']);
			$len = C('APP_CHARSET', 1) == 'utf-8'?Func :: utf8Strlen($info['title']):strlen($info['title']);
			if ($len < C('titlemin', 0, 'product') or $len > C('titlemax', 0, 'product')) {
				$this -> error = L('TITLE_LENGTH_ERROR');
				return false;
			}
		}
		// 非后台发布,脏字过滤
		if (!defined('IN_ADMIN')) {
			empty($info['content']) or $info['content'] = Func :: fbword(Func :: removeXSS($info['content']));
			$info['title'] = Func :: fbword($info['title']);
			empty($info['description']) or $info['description'] = Func :: fbword($info['description']);
		}
		// 检查分类是否可以发布内容
		$info['catid'] = intval($info['catid']);
		$category = Cache :: read('category', $info['catid']);
		if (empty($category) or $category['type']) {
			$this -> error = L('CATEGORY_INVALID');
			return false;
		} else {
			if ($category['subnum'] && !C('isbigpost', 0, 'product')) {
				$this -> error = L('CATEGORY_NOT_ALLOWED_POST');
				return false;
			}
		}
		$uselinkurl = $this -> param('uselinkurl', $param, R('uselinkurl'));
		if (empty($uselinkurl)) {
			// 判断内容是否有效
			$len = C('APP_CHARSET', 1) == 'utf-8'?Func :: utf8Strlen($info['content']):strlen($info['content']);
			if ($len > C('contentmax', 0, 'product') || $len < C('contentmin', 0, 'product')) {
				$this -> error = L('CONTENT_LENGTH_ERROR');
				return false;
			}
			$info['linkurl'] = '';
			$attachmentObj = M('attachment', '', 'product');
			// 远程上传
			$saveremote = $this -> param('saveremote', $param, R('saveremote'));
			if ($saveremote) {
				$remotetype = $this -> param('remotetype', $param);
				$info['content'] = $attachmentObj -> remote($info['content'], $remotetype);
			}
			// 获取已上传附件
			$attachments = $attachmentObj -> getAttachments($info['content']);
			$makesmallpic = $this -> param('makesmallpic', $param, R('makesmallpic'));
			// 处理标题图片
			if ($info['defaultpicurl']) {
				if ($saveremote && strstr($info['defaultpicurl'], '://')) {
					$info['defaultpicurl'] = $attachmentObj -> remoteOneImg($info['defaultpicurl']);
				}
				// 合并标题图片到附件中
				strstr($info['defaultpicurl'], '://') or $attachments[] = $info['defaultpicurl'];
			} else {
				$pic1_default = $this -> param('pic1_default', $param, R('pic1_default'));
				if ($pic1_default) {
					$info['defaultpicurl'] = $attachmentObj -> getFirstPic($info['content']);
					$makesmallpic = 1;
				}
			}
			// 生成缩略图
			if ($makesmallpic && $info['defaultpicurl'] && extension_loaded('gd')) {
				$info['defaultpicurl'] = $attachmentObj -> thump($info['defaultpicurl'], C('constrainw', 0, 'product'), C('constrainh', 0, 'product'));
			}
			if (!empty($info['description'])) $info['description'] = strip_tags($info['description']);
			elseif (!empty($info['content']) && C('cutedeslen', 0, 'product')) {
				$cutedes = $this -> param('cutedes', $param, R('cutedes'));
				if ($cutedes) {
					$info['description'] = Tag :: cut(strip_tags($info['content']), C('cutedeslen', 0, 'product'));
				}
			}
			if (isset($info['keywords'])) {
				$info['keywords'] = strip_tags($info['keywords']);
				$info['keywords'] = str_replace('，', ',', $info['keywords']);
			}
			$info['ontop'] = empty($info['ontop'])?0:1;
			$info['elite'] = empty($info['elite'])?0:1;
			$info['uncmt'] = empty($info['uncmt'])?0:1;
			$info['updatetime'] = TIME;
			if (defined('IN_ADMIN')) {
				$info['passed'] = 1;
				$info['checker'] = get_cookie('username');
				$info['checktime'] = TIME;
			}
		} else {
			$info['linkurl'] = strip_tags($info['linkurl']);
			unset($info['description'], $info['content']);
		}
		$this -> create($info);
		if (empty($info['id'])) {
			$info['id'] = $rs = $this -> add();
		} else {
			$rs = $this -> update();
		}
		if ($rs) {
			$attachmentObj -> setContentId($attachments, $info['id']);
			$tmp = $this -> param('attachments', $param, R('attachments', 'post'));
			if ($tmp) {
				$attachmentObj -> attachement($tmp, $info['id']);
				$attachments = array_merge($attachments, $tmp);
			}
			$attachmentObj -> check($attachments, $info['id']);
			M('updatehtml') -> save($info['id'], $info['catid']);
		}
		return $rs;
	}
	// 删除
	public function del($delRecycle = false) {
		if ($delRecycle) {
			$r = $this -> field('id') -> where('recycle=1') -> select();
			if (is_array($r)) {
				$selids = array();
				foreach($r as $t) $selids[] = $t['id'];
				$selids = implode(', ', $selids);
			}
		} else $selids = R('selids');
		if (!empty($selids)) {
			$where = strstr($selids, ',')?"id IN ($selids)":"id=$selids";
			if (!$this -> where($where) -> delete()) {
				$this -> error = L('OPERATE_FAIL');
				$rs = false;
			} else {
				$obj = M('attachment', '', 'product');
				$obj -> del(array("module=product", strstr($selids, ',')?"contentid IN ($selids)":"contentid=$selids"));
				$rs = true;
			}
		} else {
			$this -> error = L('NOPARAM');
			$rs = false;
		}
		return $rs;
	}
	public function listInfo($param = array()) {
		$page = $this -> param('page', $param);
		$pageSize = $this -> param('num', $param, 8);
		$where = array('passed' => 1, 'recycle' => 0);
		if ($param['ispic']) $where[] = "defaultpicurl!=''";
		if (isset($param['outid'])) {
			$tmp = intval($param['outid']);
			if($tmp)$where[] = 'id!=' . $tmp;
		}
		$catid = $this -> param('catid', $param, 0);
		$catrule = $this -> param('catrule', $param);
		$module = $this -> param('module', $param);
		$module or $module = true;
		if ($catid or $catrule) {
			$allChildId = M('category') -> childAll($catid, C('isbigpost', 0, 'product'), true, $module, $catrule);
			$where[] = count($allChildId) > 1?'catid IN(' . implode(', ', $allChildId) . ')':'catid=' . intval(current($allChildId));
		}
		$type = $this -> param('type', $param);
		$order = array('ontop DESC');
		switch ($type) {
			case 'hot':
				$hotday = $this -> param('hotday', $param, 0);
				if ($hotday) {
					$ftime = TIME - 3600 * 24 * $hotday;
					$where[] = 'updatetime>' . $ftime;
				}
				$order = array('hits DESC');
				break;
			case 'elite':
				$order = array('elite DESC');
				break;
			case 'like':
				$keyword = $this -> param('keyword', $param);
				$tmp = array();
				if ($keyword) {
					$keywords = preg_split("/[ ,]+/", $keyword);
					foreach($keywords as $word) {
						if ($word) {
							$tmp[] = "title LIKE %{$word}%";
							$tmp[] = "keywords LIKE %{$word}%";
						}
					}
				}
				if ($tmp) {
					$where[] = $tmp;
				} else {
					return false;
				}
				break;
		}
		$order[] = C('order', 0, 'product');
		$data = $this -> getList($page, $pageSize, $where, $order);
		if (is_array($data)) {
			$cutedeslen = C('cutedeslen', 0, 'product');
			if ($pageSize == 1) {
				if (!empty($data['color'])) $data['color'] = 'style="color:' . $data['color'] . '"';
				$data['description'] or $data['description'] = Tag :: description($data['content'], $cutedeslen);
				$data['url'] = Url :: getContentUrl('product', $data['id']);
			} else {
				foreach($data as $k => $v) {
					if (!empty($v['color'])) $v['color'] = 'style="color:' . $v['color'] . '"';
					$v['description'] or $v['description'] = Tag :: description($v['content'], $cutedeslen);
					$v['url'] = Url :: getContentUrl('product', $v['id']);
					$data[$k] = $v;
				}
			}
		}
		return $data;
	}
	public function search($q) {
		$page = intval(R('page'));
		$pageSize = C('searchnum', 0, 'product');
		$where = array('passed' => 1, 'recycle' => 0);
		$catid = intval(R('catid'));
		if ($catid) {
			$allChildId = M('category') -> childAll($catid, C('isbigpost', 0, 'product'), true, true);
			$where[] = count($allChildId) > 1?'catid IN(' . implode(', ', $allChildId) . ')':'catid=' . intval(current($allChildId));
		}
		if ($q) {
			$q = explode(' ', $q);
			$or = array();
			$this -> setTable('keywords');
			foreach($q as $word) {
				if ($word) {
					$r = $this -> field('kid') -> where(array('word' => $word, 'module' => 'product')) -> find();
					if ($r['kid']) {
						$this -> setFields(array('num' => 'num+1', 'updatetime' => TIME), 'kid', $r['kid']);
					} else {
						$this -> create(array('word' => $word, 'module' => 'product', 'updatetime' => TIME, 'num' => 1)) -> add();
					}
					$or[] = "title LIKE '%$word%'";
					$or[] = "keywords LIKE '%$word%'";
				}
			}
			Cache :: del('hotKeywords_product', 'base');
			$this -> setTable();
			empty($or) or $where[] = $or;
		}
		$order = array('ontop DESC', C('order', 0, 'product'), 'hits DESC');
		$data = $this -> getList($page, $pageSize, $where, $order);
		if (is_array($data)) {
			foreach($data as $k => $v) {
				if (!empty($v['color'])) $v['color'] = 'style="color:' . $v['color'] . '"';
				$v['url'] = Url :: getContentUrl('product', $v['id']);
				$data[$k] = $v;
			}
		}
		return $data;
	}
}
