<?php
class SitemapAction extends BaseAction {
	public function defaults() {
		if ($this -> isSubmit) {
			$set = R('set');
			if (R('ischange')) {
				Cache :: write('sitemap', $set, '', 'data');
			}
			$today = date('Y-m-d');

			$map = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F>\n\t<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
			$map .= $this -> item(ROOT_URL, $today, 'daily', '1.0');

			$models = array();
			$tmp = get_module();
			foreach($tmp as $module) {
				if ($module['state'] == 1 && $module['usecategory'] == 1) $models[] = $module['name'];
			}
			$cnt = count($models);
			$obj = M($models[0]);
			$field = array("id", "updatetime", "'$module[name]' AS model");
			if ($cnt > 1) {
				for($i = 0; $i < $cnt; $i++) {
					$field = array("id", "updatetime", "'$models[$i]' AS model");
					if ($i == 0) {
						$obj -> field($field);
					} elseif ($i < $cnt - 1) {
						$obj -> union(array('field' => $field, 'table' => $obj -> getTableName($models[$i])), true);
					} else {
						$obj -> union(array('field' => $field, 'table' => $obj -> getTableName($models[$i]), 'limit' => $set['num'], 'order' => 'id DESC'), true);
					}
				}
				$data = $obj -> select();
			} elseif ($cnt == 1) {
				$data = $obj -> field(array("id", "updatetime", "'$models[0]' AS model")) -> order('id DESC') -> select();
			}
			if (is_array($data)) {
				foreach($data as $tmp) {
					$map .= $this -> item($set_url . Url :: getContentUrl($tmp['model'], $tmp['id'], 0, C('urlmodel', 0, $tmp['model'])), date('Y-m-d', $tmp['updatetime']), $set['changefreq'], $set['priority']);
				}
			}
			$map .= "\t</urlset>\n";
			$msg = FileUtil :: write('sitemaps.xml', $map)?L('OPERATE_SUCCESS'):L('OPERATE_FAIL');
			$this -> showMsg($msg);
		}
		$this -> assign('data', Cache :: read('sitemap', '', 0, 'data'));
		$this -> display('sitemap');
	}
	private function item($loc, $lastmod = '', $changefreq = '', $priority = '') {
		$item = "\t\t<url>\n\t\t\t<loc>" . htmlentities($loc, ENT_QUOTES) . "</loc>\n";
		// lastmod
		if (!empty($lastmod))
			$item .= "\t\t\t<lastmod>$lastmod</lastmod>\n";
		// changefreq
		if (!empty($changefreq))
			$item .= "\t\t\t<changefreq>$changefreq</changefreq>\n";
		// priority
		if (!empty($priority))
			$item .= "\t\t\t<priority>$priority</priority>\n";

		$item .= "\t\t</url>\n\n";
		return $item;
	}
}
