<?php
//Set up the system
require('backend/timer.class.php');
$timer=&new timer;
require('geshi/geshi.php');
require('backend/pure.class.php');
require('backend/fetch.class.php');
require('backend/template.class.php');
require('backend/bbcode.class.php');
require('options.php');
$blockCodePath=THEMEFOLDER.'/'.THEME.'/'.THEME.'.bcd';

//Set up pure
$_p=new pure('',USE_GESHI_POSTS||USE_GESHI_COMMENTS||USE_GESHI_PAGES);

//Template blockcode
if(!file_exists($blockCodePath)) {
	trigger_error('Could not find the template blockcode file, please generate one from the admin panel.');
}
else {
	$blockCode=file_get_contents($blockCodePath);
}
$GLOBALS['_timer']=new timer();

$_tdata=array(
	'site_title'=>SITE_TITLE,
	'page_title'=>'',
	'site_url'=>SITE_URL,
	'is_single'=>false,
	'css_url'=>THEMEFOLDER.'/'.THEME.'/'.THEME.'.css',
	'rss'=>'<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="'.RSS_PATH.'" />',
	'theme_dir'=>THEMEFOLDER.'/'.THEME.'/',
	'title_desc'=>TITLE_DESC,
	'meta_tags'=>'
<meta name="description" content="'.htmlentities(META_DESC,ENT_QUOTES,"UTF-8").'" />
<meta name="keywords" content="'.htmlentities(META_KEYWORDS,ENT_QUOTES,"UTF-8").'" />',
	'favicon'=>'
	<link rel="shortcut icon" href="./favicon.ico" />',
	'meta_desc'=>htmlentities(META_DESC,ENT_QUOTES,"UTF-8"),
);

/*
* Decide what to do
*/
$_tdata['is_page']=false;
$_tdata['is_post']=false;
$_tdata['is_commenting']=false;

/*
* Set the default case
*/
if(!isset($_REQUEST['comment']) && !isset($_REQUEST['page']) && !isset($_REQUEST['post']) && !isset($_REQUEST['postp']) && !isset($_REQUEST['catid']) && !isset($_REQUEST['blog'])) {
	//Is there a default page?
	if(DEFAULT_PAGE!='' && $_p->tb_pages->idExists(DEFAULT_PAGE))
		$_REQUEST['page']=DEFAULT_PAGE;
	else
		$_REQUEST['blog']=true;
	$initial_load=true;
}
else
	$initial_load=false;

//Ok, begin processing
if(!isset($_REQUEST['p'])&&(isset($_REQUEST['post'])||isset($_REQUEST['page'])||isset($_REQUEST['blog']))) {
	$_REQUEST['p']=1;
}

//If a comment was sent
if(isset($_REQUEST['comment'])) {
	$_tdata['is_single']=true;
	$_tdata['is_commenting']=true;
	$_tdata['page_title']='Commenting';
	$cmmntEmail=$_p->is_logged_in()?'p@r.o':fetch::unescapePostVar($_POST['email']);
	$cmmntName=$_p->is_logged_in()?'p':fetch::unescapePostVar($_POST['name']);
	$cmmntContent=fetch::unescapePostVar($_POST['content']);
	//Strip extra whitespace?
	if(STRIP_EXTRA_COMMENT_WHITESPACE) {
		$cmmntContent=trim($cmmntContent);
	}
	//Make comment
	$cmmntTarget=$_p->tb_posts->firstMatchingId('%%ID%%=='.$_POST['targetPost']);
	//Check if target post exists or if this user can't see it
	if($cmmntTarget!==false && (array_search(PRIVATE_CATEGORY,$_p->tb_posts->getFieldValue($cmmntTarget,'categories'))===false||$_p->is_whitelisted('ipwhitelist.php')||$_p->is_logged_in())) {
		//Check for valid name
		if(strlen(str_replace(' ','',$cmmntName))>0) {
			//Check for valid email
			if($_p->is_valid_email($cmmntEmail)) {
				//Test for minimum length
				if(strlen(str_replace(' ','',$cmmntContent))>=MINIMUM_COMMENT_LENGTH) {
					//Test for maximum length
					if(strlen($cmmntContent)<MAXIMUM_COMMENT_LENGTH) {
						//Get the blacklist
						$wordblacklist=unserialize(substr(file_get_contents('wordblacklist.php'),strlen(DIE_MSG)));
						$ipblacklist=unserialize(substr(file_get_contents('ipblacklist.php'),strlen(DIE_MSG)));
						//Make comment
						$status=$_p->makeComment($cmmntTarget,$cmmntName,$cmmntContent,$cmmntEmail,$wordblacklist,$ipblacklist);
						//Error string helper
						$errorInfo='
							<p>Your comment has been saved for your convenience:<br />'.$cmmntContent.'</p>
							<br />
							<a href="index.php?post='.$cmmntTarget.'">Return to post</a>';
						//Report
						$_tdata['content'][]=array(
							'title'=>'Thank you',
							'content'=>$status===NULL?
							'<p>Your comment cannot be entered either because you have entered a comment in the last '.MINIMUM_COMMENT_INTERVAL.' seconds, or your IP address has been blacklisted.</p>'.$errorInfo:(
							$status===true?
							'Your comment has been added.<br /><a href="index.php?post='.$cmmntTarget.'">Return</a>':
							'Your comment is awaiting approval.<br /><a href="index.php?post='.$cmmntTarget.'">Return</a>'),
						);
					}
					else {
						$_tdata['content'][]=array(
							'title'=>'Error',
							'content'=>'<p>Your comment length is above the maximum of '.MAXIMUM_COMMENT_LENGTH.' characters.</p>'.$errorInfo,
						);
					}
				}
				else {
					$_tdata['content'][]=array(
						'title'=>'Error',
						'content'=>'<p>Your comment length is below the minimum of '.MINIMUM_COMMENT_LENGTH.' non-whitespace characters.</p>'.$errorInfo,
					);
				}
			}
			else {
				$_tdata['content'][]=array(
					'title'=>'Error',
					'content'=>'<p>Invalid email address.</p>'.$errorInfo,
				);
			}
		}
		else {
			$_tdata['content'][]=array(
				'title'=>'Error',
				'content'=>'<p>Invalid name, valid characters are a-z, A-Z, 0-9, _, (space).</p>'.$errorInfo,
			);
		}
	}
	else {
		$_tdata['content'][]=array(

			'title'=>'Error',
			'content'=>'The target post does not exist.'.$errorInfo,
		);
	}
}

//If a post was requested
else if(isset($_REQUEST['post'])) {
	$_tdata['is_single']=true;
	$_tdata['is_post']=true;
	//Check for a 404 or if the post is not yet published
	if(!$_p->post_exists($_REQUEST['post']) || !$_p->tb_posts->getFieldValue($_REQUEST['post'],'is_published')) {
		$_tdata['content'][]=array(
			'title'=>'Post not found',
			'content'=>'We could not find the post you were looking for.',
		);
	}
	else {
		/*
		* Post data
		*/
		$pid=$_REQUEST['post'];
		$ptimestamp=$_p->tb_posts->getFieldValue($pid,'timestamp');
		$tempdyn=array(
			'id'=>$pid,
			'title'=>htmlentities($_p->tb_posts->getFieldValue($pid,'title'),ENT_QUOTES,"UTF-8"),
			'date_d'=>date('d',$ptimestamp),
			'date_D'=>date('D',$ptimestamp),
			'date_j'=>date('j',$ptimestamp),
			'date_l'=>date('l',$ptimestamp),
			'date_S'=>date('S',$ptimestamp),
			'date_F'=>date('F',$ptimestamp),
			'date_m'=>date('m',$ptimestamp),
			'date_M'=>date('M',$ptimestamp),
			'date_n'=>date('n',$ptimestamp),
			'date_Y'=>date('Y',$ptimestamp),
			'date_y'=>date('y',$ptimestamp),
			'date_a'=>date('a',$ptimestamp),
			'date_A'=>date('A',$ptimestamp),
			'date_g'=>date('g',$ptimestamp),
			'date_G'=>date('G',$ptimestamp),
			'date_h'=>date('h',$ptimestamp),
			'date_H'=>date('H',$ptimestamp),
			'date_i'=>date('i',$ptimestamp),
			'date_s'=>date('s',$ptimestamp),
			'date_e'=>date('e',$ptimestamp),
			'date_O'=>date('O',$ptimestamp),
			'date_T'=>date('T',$ptimestamp),
			'authorid'=>$_p->tb_posts->getFieldValue($pid,'author'),
			'post_url'=>'index.php?post='.$pid,
			'comment_count'=>$_p->tb_posts->getFieldValue($pid,'comment_count'),
			'content'=>$_p->parsePost($_p->tb_posts->getFieldValue($pid,'content'),$pid,USE_GESHI_POSTS,true),
			'is_single'=>$_tdata['is_single'],
		);
		$tempdyn['has_comments']=$tempdyn['comment_count']!=0;
		$tempdyn['comment_plural']=$tempdyn['comment_count']!=1;
		//Get category strings
		$catString='';
		$linkedCatString='';
		foreach($_p->tb_posts->getFieldValue($pid,'categories') as $catID) {
			if($_p->category_id_exists($catID))
				$catName=$_p->tb_categories->getFieldValue($catID,'name');
			else
				$catName='[category deleted]';
			$catString.=$catName.',';
			$linkedCatString.='<a class="post_meta_link" href="index.php?catid='.$catID.'">'.$catName.'</a>, ';
		}
		if($catString!='') {
			$catString=substr($catString,0,strlen($catString)-2);
			$linkedCatString=substr($linkedCatString,0,strlen($linkedCatString)-2);
		}
		else {
			$catString='nowhere';
			$linkedCatString='nowhere';
		}
		$tempdyn['category_list']=$catString;
		$tempdyn['linked_category_list']=$linkedCatString;
		//Set page title
		$_tdata['page_title']='Viewing post ('.$tempdyn['title'].')';
		//Admin links
		if($_p->is_logged_in()) {
			$tempdyn['post_meta_link']=array(
				array(
					'url'=>'admin/manageposts.php?p='.$pid.'&amp;edit',
					'text'=>'Edit',
				),
			);
		}
		//Previous/next post links
		$prevposts=$_p->tb_posts->select('%is_published%&&%%ID%%<'.$pid,array());
		if(count($prevposts)>0) {
			$prevpostid=array_pop(array_keys($prevposts));
			$_tdata['pagination'][]=array('url'=>'index.php?post='.$prevpostid,
					'text'=>'&lsaquo; '.htmlentities($_p->tb_posts->getFieldValue($prevpostid,'title'),ENT_QUOTES,"UTF-8"),
					'type'=>'previouspost',
			);
		}
		$nextposts=$_p->tb_posts->select('%is_published%&&%%ID%%>'.$pid,array());
		if(count($nextposts)>0) {
			$nextpostid=array_shift(array_keys($nextposts));
			$_tdata['pagination'][]=array('url'=>'index.php?post='.$nextpostid,
					'text'=>htmlentities($_p->tb_posts->getFieldValue($nextpostid,'title'),ENT_QUOTES,"UTF-8").' &rsaquo;',
					'type'=>'nextpost',
			);
		}		$tempdyn['author']=$_p->tb_users->getFieldValue($tempdyn['authorid'],'username');
		
		//Check for private category
		$has_private_cat=array_search(PRIVATE_CATEGORY,$_p->tb_posts->getFieldValue($pid,'categories'))!==false;
		if($has_private_cat&&!$_p->is_whitelisted('ipwhitelist.php')&&!$_p->is_logged_in())
			$tempdyn['content']='Only IP addresses in the site whitelist can access this post. If you feel that this is an error, please contact the webmaster.';
		
		$_tdata['post'][]=$tempdyn;
		
		/*
		* Comments
		*/
		$leaveComment=false;
		$_tdata['has_comments']=false;
		if((!$has_private_cat||$_p->is_whitelisted('ipwhitelist.php')||$_p->is_logged_in()) && $_p->tb_posts->getFieldValue($_REQUEST['post'],'comments')) {
			$comments=$_p->tb_comments->select('%parent%=='.$_REQUEST['post'].'&&%approved%');
			$commentcount=count($comments);
			$_tdata['comment_count']=$commentcount;
			if($commentcount==0) {
				$leaveComment=true;
			}
			else {
				$_tdata['has_comments']=true;
				$count=0;
				foreach($comments as $data) {
					$tsmp=$data['timestamp'];
					$is_prominent=$data['prominent']!==false;
					$commentList[]=array(
						'is_prominent'=>$is_prominent,
						//If prominent user, get data from DB
						'author'=>htmlentities(($is_prominent?$_p->tb_users->getFieldValue($data['prominent'],'username'):$data['name']),ENT_QUOTES,"UTF-8"),
						'content'=>COMMENTS_PARSE_BBCODE?$_p->parsePost($data['content'],false,USE_GESHI_COMMENTS): //Apply bbcode if chosen
						str_replace("\n",'<br />',htmlentities($data['content'],ENT_QUOTES,"UTF-8")), //Convert new lines into line breaks
						'date_d'=>date('d',$tsmp),
						'date_D'=>date('D',$tsmp),
						'date_j'=>date('j',$tsmp),
						'date_l'=>date('l',$tsmp),
						'date_S'=>date('S',$tsmp),
						'date_F'=>date('F',$tsmp),
						'date_m'=>date('m',$tsmp),
						'date_M'=>date('M',$tsmp),
						'date_n'=>date('n',$tsmp),
						'date_Y'=>date('Y',$tsmp),
						'date_y'=>date('y',$tsmp),
						'date_a'=>date('a',$tsmp),
						'date_A'=>date('A',$tsmp),
						'date_g'=>date('g',$tsmp),
						'date_G'=>date('G',$tsmp),
						'date_h'=>date('h',$tsmp),
						'date_H'=>date('H',$tsmp),
						'date_i'=>date('i',$tsmp),
						'date_s'=>date('s',$tsmp),
						'date_e'=>date('e',$tsmp),
						'date_O'=>date('O',$tsmp),
						'date_T'=>date('T',$tsmp),
						'is_even'=>$count%2==0?true:false,
						'is_odd'=>$count%2!=0?true:false,
						'is_prominent'=>$is_prominent,
						'type'=>$is_prominent?'prominentcomment':($count%2==0?'evencomment':'oddcomment'),
					);
					$count++;
				}
				$_tdata['comment']=$commentList;
				$leaveComment=true;
			}
			$_tdata['comment_form']=$leaveComment;
		}
		else {
			$_tdata['comment_form_html']='
					Comments have been disabled for this post.';
		}
		if((!$has_private_cat||$_p->is_whitelisted('ipwhitelist.php')||$_p->is_logged_in()) && $leaveComment) {
			$_tdata['comment_form_html']='
					<form id="comment_form" action="index.php" method="post">'.
						(!$_p->is_logged_in()?'
						Name<br />
						<input type="text" name="name" /><br />
						Email (required, will not be published)<br />
						<input type="text" name="email" /><br />'
						:''
						).'Message<br />
						<textarea rows="10" cols="50" id="comment_content" name="content"></textarea><br />
						<input type="hidden" name="comment" value="" />
						<input type="hidden" name="targetPost" value="'.$pid.'" />
						<input type="submit" value="Comment" />
					</form>';
		}
	}
}

//If a page was requested
else if(isset($_REQUEST['page'])) {
	$_tdata['is_single']=true;
	$_tdata['is_page']=true;
	//Check for a 404 or if the page is not yet published
	if(!$_p->page_exists($_REQUEST['page']) || !$_p->tb_pages->getFieldValue($_REQUEST['page'],'is_published')) {
		$_tdata['content'][]=array(
			'title'=>'Page not found',
			'content'=>'We could not find the page you were looking for.',
		);
	}
	else {
		/*
		* Page data
		*/
		$pid=$_REQUEST['page'];
		$ptimestamp=$_p->tb_pages->getFieldValue($pid,'timestamp');
		$tempdyn=array(
			'id'=>$pid,
			'title'=>htmlentities($_p->tb_pages->getFieldValue($pid,'title'),ENT_QUOTES,"UTF-8"),
			'date_d'=>date('d',$ptimestamp),
			'date_D'=>date('D',$ptimestamp),
			'date_j'=>date('j',$ptimestamp),
			'date_l'=>date('l',$ptimestamp),
			'date_S'=>date('S',$ptimestamp),
			'date_F'=>date('F',$ptimestamp),
			'date_m'=>date('m',$ptimestamp),
			'date_M'=>date('M',$ptimestamp),
			'date_n'=>date('n',$ptimestamp),
			'date_Y'=>date('Y',$ptimestamp),
			'date_y'=>date('y',$ptimestamp),
			'date_a'=>date('a',$ptimestamp),
			'date_A'=>date('A',$ptimestamp),
			'date_g'=>date('g',$ptimestamp),
			'date_G'=>date('G',$ptimestamp),
			'date_h'=>date('h',$ptimestamp),
			'date_H'=>date('H',$ptimestamp),
			'date_i'=>date('i',$ptimestamp),
			'date_s'=>date('s',$ptimestamp),
			'date_e'=>date('e',$ptimestamp),
			'date_O'=>date('O',$ptimestamp),
			'date_T'=>date('T',$ptimestamp),
			'page_url'=>'index.php?page='.$pid,
			'content'=>$_p->parsePost($_p->tb_pages->getFieldValue($pid,'content'),$pid,USE_GESHI_PAGES,true),
		);
		$_tdata['page_title']='Viewing page ('.$tempdyn['title'].')';
		//Admin links
		if($_p->is_logged_in()) {
			$tempdyn['page_meta_link']=array(
				array(
					'url'=>'admin/managepages.php?p='.$pid.'&amp;edit',
					'text'=>'Edit',
				),
			);
		}
		$_tdata['page'][]=$tempdyn;
	}
}
//If not, separate tasks into posts or pages
else {
	//Working with post pages
	if(!isset($_REQUEST['pagep'])) {
		/*
		* Grab the posts in the requested month
		*/
		$p=isset($_REQUEST['postp'])?$_REQUEST['postp']:0;
		$months=fetch::sortSelection($_p->tb_archives->select('true',array('month')),'month');
		$URLappend=''; //Stuff to add to the end of pagination links
		//If missing a year or month
		if(!isset($_REQUEST['year'])||!isset($_REQUEST['month'])) {
			$posts=$_p->loadposts_all();
			if($p===0 && $initial_load)
				$_tdata['page_title']=TITLE_DESC;
			else
				$_tdata['page_title']='Posts (Page '.($p+1).')';
		}
		else {
			$year=$_REQUEST['year'];
			$month=$_REQUEST['month'];
			$URLappend.='&amp;month='.$month.'&amp;year='.$year;
			$_tdata['page_title']='Archives '.$month.'/'.$year.' (Page '.($p+1).')';
			$posts=$_p->loadposts_month($month,$year);
		}
		if($posts==false) {
			$_tdata['content'][]=array(
				'title'=>'Uh oh',
				'content'=>'There are no posts on record for this month ('.$month.'/'.$year.').',
			);
			$posts=array();
		}
		else
			$posts=fetch::sortSelection($posts,'timestamp',SORT_DESC);
		
		/*
		* Grab the posts in the requested category, if one is requested
		*/
		if(isset($_REQUEST['catid'])&&$_p->category_id_exists($_REQUEST['catid'])) {
			$posts=$_p->get_cat($_REQUEST['catid']);
			$_tdata['page_title']='Posts in &quot;'.$_p->category_name($_REQUEST['catid']).'&quot; (Page '.($p+1).')';
			$URLappend.='&amp;catid='.$_REQUEST['catid'];
		}
		
		/*
		* Pagination magic!
		*/
		//Count pages
		$total_posts=count($posts);
		$pages=$total_posts/POSTS_PER_PAGE;
		//If we can't divide cleanly, add one to the pages to cover the missing remainder because php will round down
		if($total_posts%POSTS_PER_PAGE!=0)
			$pages=floor($pages)+1;
		//Check if the page we are trying to display exists
		if($p<0||$p>=$pages) {
			//Report back the problem
			$_tdata['content'][]=array(
				'title'=>'Out of bounds',
				'content'=>'The requested posts do not exist'
			);
			//Clear out the list of posts
			$posts=array();
		}
		else {
			//Build template dynamic
			if($pages!=1&&$pages!=0) {
				$i=$p-PREVIOUS_PAGES;
				if($i<0)
					$i=0;
				if($p>0)
					$_tdata['pagination'][]=array(
						'url'=>'index.php?postp=0'.$URLappend,
						'text'=>'&laquo; First',
						'type'=>'first',
					);
				if($p>1)
					$_tdata['pagination'][]=array(
						'url'=>'index.php?postp='.($p-1).$URLappend,
						'text'=>'&lsaquo; Prev',
						'type'=>'previous',
					);
				for(;$i<$p;$i++) {
					$_tdata['pagination'][]=array(
						'url'=>'index.php?postp='.$i.$URLappend,
						'text'=>($i+1),
						'type'=>'previouspages',
					);
				}
				$_tdata['pagination'][]=array(
					'url'=>'index.php?postp='.$p.$URLappend,
					'text'=>($p+1),
					'type'=>'current',
				);
				$i=$p+NEXT_PAGES+1;
				if($i>$pages)
					$i=$pages;
				for($y=$p+1;$y<$i;$y++) {
					$_tdata['pagination'][]=array(
						'url'=>'index.php?postp='.$y.$URLappend,
						'text'=>($y+1),
						'type'=>'nextpages',
					);
				}
				if($p<$pages-2)
					$_tdata['pagination'][]=array(
						'url'=>'index.php?postp='.($p+1).$URLappend,
						'text'=>'Next &rsaquo;',
						'type'=>'next',
					);
				if($p<$pages-1)
					$_tdata['pagination'][]=array(
						'url'=>'index.php?postp='.($pages-1).$URLappend,
						'text'=>'Last ('.$pages.') &raquo;',
						'type'=>'last',
					);
			}
		}
		
		/*
		* Setting up the posts for display
		*/
		//Build dynamic data
		if(count($posts)>0) {
			$start=POSTS_PER_PAGE*$p; //When to start
			$left=POSTS_PER_PAGE; //When to stop
			foreach($posts as $pid=>$d) {
				if($start==0) {
					if($left>0) {
						$tempdyn=array(
							'id'=>$pid,
							'title'=>htmlentities($d['title'],ENT_QUOTES,"UTF-8"),
							'author'=>$_p->tb_users->getFieldValue($d['author'],'username'),
							'authorid'=>$d['author'],
							'date_d'=>date('d',$d['timestamp']),
							'date_D'=>date('D',$d['timestamp']),
							'date_j'=>date('j',$d['timestamp']),
							'date_l'=>date('l',$d['timestamp']),
							'date_S'=>date('S',$d['timestamp']),
							'date_F'=>date('F',$d['timestamp']),
							'date_m'=>date('m',$d['timestamp']),
							'date_M'=>date('M',$d['timestamp']),
							'date_n'=>date('n',$d['timestamp']),
							'date_Y'=>date('Y',$d['timestamp']),
							'date_y'=>date('y',$d['timestamp']),
							'date_a'=>date('a',$d['timestamp']),
							'date_A'=>date('A',$d['timestamp']),
							'date_g'=>date('g',$d['timestamp']),
							'date_G'=>date('G',$d['timestamp']),
							'date_h'=>date('h',$d['timestamp']),
							'date_H'=>date('H',$d['timestamp']),
							'date_i'=>date('i',$d['timestamp']),
							'date_s'=>date('s',$d['timestamp']),
							'date_e'=>date('e',$d['timestamp']),
							'date_O'=>date('O',$d['timestamp']),
							'date_T'=>date('T',$d['timestamp']),
							'post_url'=>'index.php?post='.$pid,
							'content'=>$_p->parsePost($d['content'],$pid,USE_GESHI_POSTS,false),
							'comment_count'=>$d['comment_count'],
							'is_single'=>$_tdata['is_single'],
						);
						$tempdyn['has_comments']=$tempdyn['comment_count']!=0;
						$tempdyn['comment_plural']=$tempdyn['comment_count']!=1;
						//Get category strings
						$catString='';
						$linkedCatString='';
						foreach($d['categories'] as $catID) {
							if($_p->category_id_exists($catID))
								$catName=$_p->tb_categories->getFieldValue($catID,'name');
							else
								$catName='[category deleted]';
							$catString.=$catName.',';
							$linkedCatString.='<a class="post_meta_link" href="index.php?catid='.$catID.'">'.$catName.'</a>, ';
						}
						if($catString!='') {
							$catString=substr($catString,0,strlen($catString)-2);
							$linkedCatString=substr($linkedCatString,0,strlen($linkedCatString)-2);
						}
						else {
							$catString='nowhere';
							$linkedCatString='nowhere';
						}
						$tempdyn['category_list']=$catString;
						$tempdyn['linked_category_list']=$linkedCatString;
						
						//Check for private category
						$has_private_cat=array_search(PRIVATE_CATEGORY,$_p->tb_posts->getFieldValue($pid,'categories'))!==false;
						if($has_private_cat&&!$_p->is_whitelisted('ipwhitelist.php')&&!$_p->is_logged_in()) {
							$tempdyn['content']='Only IP addresses in the site whitelist can access this post. If you feel that this is an error, please contact the webmaster.';
							$tempdyn['comment_count']='?';
						}

						//Admin links
						if($_p->is_logged_in()) {
							$tempdyn['post_meta_link']=array(
								array(
									'url'=>'admin/manageposts.php?p='.$pid.'&amp;edit',
									'text'=>'Edit',
								),
							);
						}
						$_tdata['post'][]=$tempdyn;
						$left--;
					}
					else {
						break;
					}
				}
				else {
					$start--;
				}
			}
		}
		else {
			$_tdata['content'][]=array(
				'title'=>'No posts to display',
				'content'=>'There are no posts to display'
			);
		}
	}
}
//Set pagination boolean
if(array_key_exists('pagination',$_tdata)&&count($_tdata['pagination'])>0)
	$_tdata['has_pagination']=true;
else
	$_tdata['has_pagination']=false;

/*
* The nav links
*/
$_tdata['nav_link'][]=array(
	'url'=>'index.php?blog=true',
	'text'=>'Blog',
	'is_current'=>isset($_REQUEST['blog'])||isset($_REQUEST['post'])||isset($_REQUEST['postp'])||isset($_REQUEST['catid'])?true:false,
);
$_tdata['is_logged_in']=false;
if(!HIDE_ADMIN||$_p->is_logged_in()) {
	if(!$_p->is_logged_in()) {
		$_tdata['nav_link'][]=array(
			'url'=>'./admin',
			'text'=>'Log In',
			'is_current'=>false,
		);
	}
	else {
		$_tdata['nav_link'][]=array(
			'url'=>'./admin',
			'text'=>'Dashboard',
			'is_current'=>false,
		);
		$_tdata['nav_link'][]=array(
			'url'=>'./admin/post.php',
			'text'=>'New Post',
			'is_current'=>false,
		);
		$_tdata['nav_link'][]=array(
			'url'=>'./admin/page.php',
			'text'=>'New Page',
			'is_current'=>false,
		);
		$_tdata['nav_link'][]=array(
			'url'=>'./admin/logout.php',
			'text'=>'Log Out',
			'is_current'=>false,
		);
	}
}
if(!$_p->is_logged_in())
	$_tdata['is_logged_in']=true;
/*
* Setting up the archives list
*/
$archives=fetch::sortSelection($_p->tb_archives->select('true',array('month','created'),60),'month',SORT_DESC);
if(count($archives)>0) {
	$_tdata['has_archives']=true;
	foreach($archives as $data) {
		$mth=substr($data['month'],0,2);
		$yr=substr($data['month'],2);
		$_tdata['archive_link'][]=array(
			'url'=>'index.php?month='.$mth.'&amp;year='.$yr,
			'text'=>date('M y',$data['created']),
			'is_current'=>false,
		);
	}
}
else {
	$_tdata['has_archives']=false;
}
/*
* Setting up the pages list
*/
$pagesdata=fetch::sortSelection($_p->tb_pages->select('%is_published%',array('title')),'title',SORT_ASC);
if(count($pagesdata)>0) {
	$_tdata['has_pages']=true;
	foreach($pagesdata as $pageid=>$pagedata) {
		$_tdata['page_link'][]=array(
			'url'=>'index.php?page='.$pageid,
			'title'=>$pagedata['title'],
			'is_current'=>isset($_REQUEST['page'])&&$pageid==$_REQUEST['page']?true:false,
		);
	}
}
else {
	$_tdata['has_pages']=false;
}
/*
* Setting up the blogroll
*/
$_tdata['has_blogroll']=false;
if(file_exists(BLOGROLL_PATH)) {
	$blogroll=explode("\n",file_get_contents(BLOGROLL_PATH));
	if(count($blogroll)>0 && $blogroll[0]!='') {
		foreach($blogroll as $index=>$link) {
			$url=substr($link,0,strpos($link,'->'));
			$text=substr($link,strpos($link,'->')+2);
			$_tdata['blogroll_link'][]=array(
				'url'=>$url,
				'text'=>$text,
				'is_current'=>false,
			);
		}
		$_tdata['has_blogroll']=true;
	}
}
/*
* Setting up the recent comments
*/
$_tdata['has_recent_comments']=false;
$recentComments=$_p->tb_comments->select('%approved%');
if(count($recentComments)>0) {
	$recentComments=fetch::sortSelection($recentComments,'timestamp',SORT_DESC);
	$_tdata['comment_link']=array();
	$i=0;
	while($i<5 && count($recentComments)>0) {
		$data=array_shift($recentComments);
		//Check for private post
		if($_p->is_whitelisted('ipwhitelist.php')||$_p->is_logged_in()||array_search(PRIVATE_CATEGORY,$_p->tb_posts->getFieldValue($data['parent'],'categories'))===false) {
			$is_prominent=$data['prominent']!==false;
			$comment_info=array(
				'is_prominent'=>$is_prominent,
				//If prominent user, get data from DB
				'author'=>htmlentities(($is_prominent?$_p->tb_users->getFieldValue($data['prominent'],'username'):$data['name']),ENT_QUOTES,"UTF-8"),
				//Title of the post this comment was made on
				'title'=>htmlentities($_p->tb_posts->getFieldValue($data['parent'],'title')),
				'url'=>htmlentities('index.php?post='.$data['parent']),
			);
			array_push($_tdata['comment_link'],$comment_info);
			$i++;
		}
	}
}
/*
* Setting up the categories
*/
$_tdata['has_categories']=false;
$categorylist=$_p->get_categories();

//Only do this is there are categories
if(count($categorylist)>0) {
	$_tdata['has_categories']=true;

	//For every category..
	foreach($categorylist as $catid=>$catdata) {
		//This is our temporary array that holds info about the category
		$temp_catdata=array(
			'url'=>'index.php?catid='.$catid,
			'name'=>$catdata['name'],
			'is_current'=>isset($_REQUEST['catid'])&&$catid==$_REQUEST['catid']?true:false,
		);
		
		/******************************************************************************
		* Latest posts in category hack
		* Uncomment to add template variables for themes that use them
		******************************************************************************/
		
		/***************************Hack Start***************************\
		//Get the last $postsToGet posts in this category
		$postsToGet=5;
		$postsInCat=$_p->get_cat($catid);

		$temp_catdata['last_post']=array(); //The subdynamic we will be using

		//For the first $postsToGet posts in this category
		foreach($postsInCat as $postID=>$postData) {
			//Add data to the last_post subdynamic
			$temp_post_data=array(
				'url'=>'index.php?post='.$postID,
				'title'=>$postData['title'],
				'author'=>$_p->tb_users->getFieldValue($postData['author'],'username')
			);
			//Add to the end of the array, so they go in order
			array_push($temp_catdata['last_post'],$temp_post_data);

			//Decrement counter
			$postsToGet--;
			if($postsToGet==0)
				break;
		}

		//Tells us if there are any posts in here
		$temp_catdata['has_posts']=count($temp_catdata['last_post'])>0;
		
		\****************************Hack End****************************/
		
		//Finally, add the info we just processed
		$_tdata['category_link'][]=$temp_catdata;
	}
}//Generate the template
$page=new ubertemplate;
$page->addValues($_tdata);
$page->setBlockCode($blockCode);
$page->processBlockCode();
$page->write();
?>