<?php defined('KOBLOG') or die('Koblog CMS.');

class Archives extends dbList {

	function __construct()
	{
		parent::__construct(DB_ARCHIVES);
	}

	function numberOfPages($key)
	{
		return $this->countItems($key);
	}

	public function reindex()
	{
		global $pages;
		$db = $pages->getDB($onlyKeys=false);
		$archiveIndex = array();
		foreach ($db as $pageKey=>$pageFields) {
			if ($pageFields['type'] == "article" && $pageFields['state'] == "published") {
				$date = $pageFields['date'];
                $year = mb_substr($date, 0, 4);
                $month = mb_substr($date, 0, 7);

                // Index by years
				if (isset($archiveIndex[$year])) {
					array_push($archiveIndex[$year]['list'], $pageKey);
				} else {
					$archiveIndex[$year]['name'] = $year;
					$archiveIndex[$year]['list'] = array($pageKey);
				}

                // Index by month
                if (isset($archiveIndex[$month])) {
					array_push($archiveIndex[$month]['list'], $pageKey);
				} else {
					$archiveIndex[$month]['name'] = $month;
					$archiveIndex[$month]['list'] = array($pageKey);
				}
			}
		}

		$this->db = $archiveIndex;
		$this->sortAlphanumeric();
		return $this->save();
	}

}