<?php
// 单网页模型
class OnepageModel extends Model {
	public function save($category = array()) {
		$info = $_POST['info'];
		$info['id'] = intval($info['id']);
		if ($info['id']) {
			$isAdd = false;
		} else {
			$isAdd = true;
			$info['id'] = $this -> getId('id');
		}
		if (!empty($category)) {
			$info['catid'] = $category['catid'];
			$info['name'] = $category['dir'];
		}
		// 判断标题有效性
		$info['title'] = trim($info['title']);
		$len = C('APP_CHARSET', 1) == 'utf-8'?Func :: utf8Strlen($info['content']):strlen($info['content']);
		$attachmentObj = M('attachment', '', 'onepage');
		if ($len) {
			// 远程上传
			if (R('saveremote')) $info['content'] = $attachmentObj -> remote($info['content']);
			// 获取已上传附件
			$attachments = $attachmentObj -> getAttachments($info['content']);
		}
		if (!empty($info['description'])) $info['description'] = strip_tags($info['description']);
		if (isset($info['keywords'])) {
			$info['keywords'] = strip_tags($info['keywords']);
			$info['keywords'] = str_replace('，', ',', $info['keywords']);
		}
		$this -> create($info);
		$rs = $isAdd ? $this -> add() : $this -> update();
		if ($rs) {
			$attachmentObj -> setContentId($attachments, $info['id']);
			$attachmentObj -> check($attachments, $info['id']);
			$rs = $info['id'];
		}
		return $rs;
	}
	// 删除
	public function del() {
		$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', '', $this -> moduleName);
				$obj -> del(array("module=" . $this -> moduleName, strstr($selids, ',')?"contentid IN ($selids)":"contentid=$selids"));
				$rs = true;
			}
		} else {
			$this -> error = L('NOPARAM');
			$rs = false;
		}
		return $rs;
	}
	public function listTpl() {
		$rs = array();
		$rootDir = MODULE_DIR && is_dir(JXCMS_ROOT . MODULE_DIR . 'templates/') ? JXCMS_ROOT . MODULE_DIR : JXCMS_ROOT;
		foreach (glob($rootDir . 'templates/' . C('style') . '/*' . C('htmlext')) as $file) {
			$file = basename($file, C('htmlext'));
			if (substr($file, 0, 7) == 'onepage') $rs[] = $file;
		}
		return $rs;
	}
}
