<?php
class OnepageAction extends Action {
	public function defaults($id = 0) {
		$id or $id = intval(R('id'));
		$isCreateHtml = defined('IN_CREATEHTML');
		if (C('urlmodel') == 1) {
			$url = Url :: getOnepageUrl($id);
			$path = Url :: getOnepagePath($id);
			if (is_file($path)) {
				if (!$isCreateHtml) {
					header('Location:' . $url);
					exit;
				}
			} else $isCreateHtml = true;
		}
		$data = M('onepage') -> where(array('id' => $id, 'catid' => 0, 'block' => 0)) -> find();
		$data['variable'] = explode("\n", $data['variable']);
		if (is_array($data['variable'])) {
			foreach($data['variable'] as $tmp) {
				list($k, $v) = split('=', $tmp);
				$data[$k] = $v;
			}
		}
		$tpl = empty($data['tpl'])?'onepage':$data['tpl'];
		unset($data['variable'], $data['tpl']);
		$data['content'] = Func :: fillDir($data['content']);
		$data['content'] = M('relatedlink') -> show($data['content'], 1, $data['keywords']);
		$this -> assign('extract', $data);
		if ($isCreateHtml) {
			$html = $this -> fetch($tpl);
			$size = FileUtil :: write($path , $html);
			if (!defined('IN_CREATEHTML')) {
				echo $html;
			} else {
				return $size;
			}
		} else $this -> display($tpl);
	}
	public function ajax() {
		$data = M('onepage') -> field(array('content')) -> where(array('name' => R('name'))) -> find();
		if (!empty($data['content']))echo iconv(C('APP_CHARSET', 1), 'utf-8', $data['content']);
	}
}
