<?php
ApplicationSettings::RegisterDefaultSetting("blog", "preview_length", 1000);

class BlogPost extends DBObjectAutoCreate {
	//const PREVIEW_LENGTH=1000;
	
	private $_uri;

	public static function GetCount() {
		//self::SetupPDO();
		self::CreateTable("blog_posts");
		return self::$PDO->query("SELECT COUNT(*) FROM blog_posts WHERE post_content<>'' AND post_deleted=0")->fetchColumn();
	}
	
	public static function GetLatest($count=1,$offset=0){
		//self::SetupPDO();
		self::CreateTable("blog_posts");
		$prep=self::$PDO->prepare("SELECT post_id FROM blog_posts WHERE post_content<>'' AND post_deleted=0 ORDER BY post_timestamp DESC LIMIT ?,?");
		$prep->bindValue(1,(int)$offset,PDO::PARAM_INT); // can't just use array in execute this time as execute array is treated like strings
		$prep->bindValue(2,(int)$count,PDO::PARAM_INT);
		$prep->execute();
		$ids=$prep->fetchAll(PDO::FETCH_COLUMN);
		$posts=array();
		foreach ($ids as $id)
			$posts[]=new BlogPost($id);
		return $posts;
		//return new BlogPost($url);
	}
	
	public static function GetAll(){
		$posts=array();
		self::SetupPDO();
		$ids=self::$PDO->query("SELECT post_id FROM blog_posts WHERE post_deleted=0")->fetchAll(PDO::FETCH_COLUMN);
		foreach ($ids as $id)
			$posts[]=new BlogPost($id);
		return $posts;
	}

	public function __construct($id=0) {
		$field="post_id";
		if (!is_numeric($id))
			$field="post_url";
		parent::__construct("blog_posts", $field, $id);
		
		$this->_uri=new URI($this->PostTitle, $this->PostUrl);
	}
	
	public function Save() {
		if (!isset($this->PostUrl) || $this->PostUrl==null || $this->PostUrl=="")
			$this->PostUrl=Utils::MakeUniqueURL("blog_posts","post_url",$this->PostTitle);
		if (is_numeric($this->PostUrl))
			$this->PostUrl="_".$this->PostUrl;
		parent::Save();
	}
	
	public function Delete() {
		$this->PostDeleted=1;
		$this->Save();
	}
	
	public function GetPostPreview() {
		$previewLength=ApplicationSettings::GetSetting("blog", "preview_length");
		$content=$this->PostContent;
		if ($previewLength<strlen($content)){
			$pTagPos=strpos($content,"\n",$previewLength);
			$content=substr($content, 0, $pTagPos);
		}
		$content=Utils::CloseOpenTags($content);
		return $content;
	}
	
	public function GetURI() {
		return $this->_uri;
	}
	
	public function Publish() {
		$this->PostContent=$this->PostDraft;
		$this->Save();
	}
}
