<?php
//Set up the system
require('config.include.php');
//Auth stuff
require('auth.include.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Manage Posts</title>
<link rel="stylesheet" href="admin.css" />
<script type="text/javascript" src="editor.js"></script>
</head>

<body>
<div id="wrapper">
	<div id="header">
    	<?php echo('<a href="../" class="breadcrumb">'.SITE_TITLE.'</a> &raquo; <a href="dashboard.php" class="breadcrumb">Dashboard</a> &raquo; <a href="manageposts.php" class="breadcrumb">Manage Posts</a>'); ?>
    </div>
    <div id="sidebar">
<?php
	require('nav.include.php');
?>
    </div>
    <div id="content">
        <div class="contentblock">
				<h2>Edit A Post</h2>
<?php
	if(!isset($_REQUEST['p'])) {
		echo('<h3>Select Post To Edit</h3>');
		$posts=fetch::sortSelection($_p->tb_posts->select('true',array('title','author','timestamp','is_published')),'timestamp',SORT_DESC);
		if(count($posts)>0) {
			//Count pages
			$total_posts=count($posts);
			$pages=$total_posts/POSTS_PER_LIST;
			//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_LIST!=0)
				$pages=floor($pages)+1;
			//Decide what page is showing
			$p=isset($_REQUEST['postp'])?$_REQUEST['postp']:0;
			echo('<div class="pagination">');
			//Pagination
			if($pages!=1&&$pages!=0) {
				$i=$p-PREVIOUS_PAGES;
				if($i<0)
					$i=0;
				if($p>0)
					echo('<a class="first" href="manageposts.php?postp=0">&laquo; First</a> ');
				if($p>1)
					echo('<a class="previous" href="manageposts.php?postp='.($p-1).'">Previous</a> ');
				for(;$i<$p;$i++)
					echo('<a class="last5" href="manageposts.php?postp='.$i.'">'.$i.'</a> ');
				echo('<a class="current"a href="manageposts.php?postp='.$p.'">'.$p.'</a> ');
				$i=$p+NEXT_PAGES+1;
				if($i>$pages)
					$i=$pages;
				for($y=$p+1;$y<$i;$y++)
					echo('<a class="next5" href="manageposts.php?postp='.$y.'">'.$y.'</a> ');
				if($p<$pages-2)
					echo('<a class="next" href="manageposts.php?postp='.($p+1).'">Next</a> ');
				if($p<$pages-1)
					echo('<a class="last" href="manageposts.php?postp='.($pages-1).'">Last ('.($pages-1).') &raquo;</a>');
			}
			echo('</div>');
			//Show posts on that page
			$startat=$p*POSTS_PER_LIST;
			$i=0;
			$y=POSTS_PER_LIST;
			echo('<ul>');
			foreach($posts as $pid => $d) {
				if($i==$startat) {
					if($y>0) {
						echo('<li><strong>'.$d['title'].'</strong> by '.$_p->tb_users->getFieldValue($d['author'],'username').' on '.date('j<\s\up>S</\s\up> M y',$d['timestamp']).' ('.($d['is_published']===true?'Published':'Draft').')<br />
						<a href="manageposts.php?p='.$pid.'&amp;edit">Edit</a> | 
						<a href="manageposts.php?p='.$pid.'&amp;delete">Delete</a></li>');
						$y--;
					}
					else {
						break;
					}
				}
				else {
					$i++;
				}
			}
			echo('</ul>');
		}
		else {
			echo('There are no posts yet.');
		}
	}
	//If in edit mode
	elseif(isset($_REQUEST['edit'])) {
		$printform=true;
		$pid=isset($_GET['p'])?$_GET['p']:$_POST['p'];
		
		//Get existing categories if not loaded
		if(!is_array($_POST['categories'])) 
			$_POST['categories']=$_p->tb_posts->getFieldValue($pid,'categories');
		
		//Fix categories if empty
		$categories=$_p->get_categories();
		if(!is_array($_POST['categories']) || count($_POST['categories'])==0)
			if(count($categories)>0) {
				$first_category=array_shift(array_keys($categories));
				$_POST['categories']=array($first_category);
			}
			else
				$_POST['categories']=array();
		
		//noedits tells us if new data could have been recieved
		if(isset($_POST['publish'])||isset($_POST['draft'])||isset($_POST['preview'])||isset($_POST['attach'])||isset($_POST['attachsearch']))
			$noedits=false;
		else
			$noedits=true;
		//Get data from the database or from the user's submission?
		if(!$noedits) {
			$comments=false;
			if($_POST['comments']==1)
				$comments=true;
			$postcontent=fetch::unescapePostVar($_POST['postcontent']);
			$posttitle=fetch::unescapePostVar($_POST['posttitle']);
		}
		else {
			$comments=$_p->tb_posts->getFieldValue($pid,'comments');
			$postcontent=$_p->tb_posts->getFieldValue($pid,'content');
			$posttitle=$_p->tb_posts->getFieldValue($pid,'title');
		}
		//Do the right thing
		if(isset($_POST['posttitle'])) {
			//Fix post data
			if($_POST['posttitle']==='') {
				echo('<h3>Error</h3>
				Please enter a title.<br />');
			}
			else {
				//Publishing or drafting or attaching
				if(isset($_POST['attach'])||isset($_POST['attachsearch'])) {
					//Attachment system uploads
					if(isset($_POST['attach'])) {
						echo('<br />Attaching...');
						//Add and check result
						if(($attachedFile=$_p->attach(basename($_FILES['file_upload']['name']),$_FILES['file_upload']['tmp_name'],'../'.UPLOAD_PATH))!==false)
							echo('<br />Attachment "'.$attachedFile.'" added.');
						else
							echo('<br />Attachment failed to be added.');
					}
				}
				elseif(isset($_POST['publish'])||isset($_POST['draft'])) {
					echo('
					<h3>Post Saved</h3>
					<a href="manageposts.php?p='.$pid.'&amp;edit">Continue editing</a>');
					if(isset($_POST['publish'])) {
						$_p->edit_post($pid,$posttitle,$postcontent,$comments,true,$_POST['categories']);
						
						//Rebuild the rss feed
						$rssFile='../'.RSS_PATH;
						$xml=$_p->rebuildRSS();
						$rssHandle=@fopen($rssFile,'w+');
						if($rssHandle===false)
							die('Could not open "'.$rssFile.'" for writing, please check the file permissions.');
						fwrite($rssHandle,$xml);
						fclose($rssHandle);
						echo(' | <a href="../index.php?post='.$pid.'">View Post</a>');
					}
					else
						$_p->edit_post($pid,$posttitle,$postcontent,$comments,false,$_POST['categories']);
					$printform=false;
				}
				//Preview
				else {
					echo('
					<h3>Previewing Post</h3>'.
					$_p->parsePost($postcontent,-1,USE_GESHI_POSTS));
				}
			}
		}
		
		if($printform) {
		echo('
			<form enctype="multipart/form-data" action="manageposts.php" method="post">
				<h3>Title</h3>
				<input tabindex="1" type="text" class="full" name="posttitle" value="'.$posttitle.'"/>
				<h3>Content</h3>
				<div class="toolbar">
				<a href="#" title="Bold" onclick="addtag(\'postcontent\', \'b\')"><b>B</b></a>
				<a href="#" title="Italics" onclick="addtag(\'postcontent\', \'i\')"><i>I</i></a>
				<a href="#" title="Underline" onclick="addtag(\'postcontent\', \'u\')"><u>U</u></a>
				<a href="#" class="deform" title="Code" onclick="addtag(\'postcontent\', \'code\')">code</a>
				<a href="#" class="deform" title="Code" onclick="addtag(\'postcontent\', \'quote\')">quote</a>
				<a href="#" class="deform" title="Html" onclick="addtag(\'postcontent\', \'html\')">html</a>
				<a href="#" class="deform" title="Create A Link" onclick="addurl(\'postcontent\')">url</a>
				<a href="#" class="deform" title="Insert an Image" onclick="addtag(\'postcontent\', \'img\')">img</a>
				<a href="#" class="deform" title="Add ReadMore Tag" onclick="addtext(\'postcontent\', \'[readmore]\')">readmore</a>
				<a href="#" class="deform" title="Add Link to a Post" onclick="linkpost(\'postcontent\')">+post</a>
				<a href="#" class="deform" title="Add Link to a Page" onclick="linkpage(\'postcontent\')">+page</a>
				</div>
				<textarea tabindex="2" class="full" rows="30" cols="60" name="postcontent" id="postcontent">'.htmlentities($postcontent,ENT_QUOTES,"UTF-8").'</textarea>
				<h3>Insert Attachments</h3>
				<input type="text" id="attachment_search_text" name="attachment_search_text" value="'.htmlentities($_POST['attachment_search_text'],ENT_QUOTES,'UTF-8').'" onkeyup="javascript:searchattachments(true,true);" />
				<a href="javascript:searchattachments(\'\',true);">Show all attachments</a> | 
				<a href="javascript:searchattachments(false,true);">Show recent attachments</a>
				<div id="attachment_search_report">');
				//If we were sent a request for a search
				if(isset($_POST['attachsearch'])) {
					$searchResults=$_p->search_attachments($_POST['attachment_search_text'],'../'.UPLOAD_PATH);
					echo('<strong>Search results for "'.htmlentities($_POST['attachment_search_text'],ENT_QUOTES,'UTF-8').'":</strong><br />'.
					$_p->render_attachment_search(true,$searchResults));
				}
				//If not, display the recent attachments
				else {
					echo('
					Search results will appear here as you type.<br />
					(Requires Javascript, or else hit the Search button)<br /><br />
					<strong>Recent attachments:</strong><br />');
					echo($_p->render_attachment_search(true,$_p->recent_attachments('../'.UPLOAD_PATH)));
				}
		echo('</div>
				<br /><br />
				<input type="submit" name="attachsearch" value="Search" />
				<input type="hidden" id="userid" value="'.$_SESSION['auth_id'].'" />
				<input type="hidden" id="userkey" value="'.$_p->tb_users->getFieldValue($_SESSION['auth_id'],'hash').'" />
				<h3>Upload Attachments</h3>
				<input type="file" name="file_upload" />
				<input type="hidden" name="MAX_FILE_SIZE" value="'.MAX_UPLOAD_BYTES.'" /><br />
				Maximum upload size: '.MAX_UPLOAD_BYTES.' bytes<br />
				<br />
				<input type="submit" name="attach" value="Upload" />
				<h3>Allow Comments</h3>
				<input type="radio" name="comments" '.($comments?'checked="checked"':'').' value="1" /> Yes<br />
				<input type="radio" name="comments" '.(!$comments?'checked="checked"':'').' value="0" /> No
				<h3>Categories</h3>');
			//Category selection
			$categories=$_p->get_categories();
			if(count($categories)==0)
				echo('No categories available');
			foreach($categories as $catID=>$catInfo) {
				echo('<input type="checkbox" name="categories[]" value="'.$catID.'"'.(array_search($catID,$_POST['categories'])!==false?' checked="checked"':'').' /> '.$catInfo['name'].'<br />');
			}
			echo('
				<h3>Action</h3>
				<input tabindex="3" type="submit" name="publish" value="Publish" />
				<input tabindex="4" type="submit" name="draft" value="Save as draft" />
				<input tabindex="5" type="submit" name="preview" value="Preview" />
				<input type="hidden" name="edit" />
				<input type="hidden" name="p" value="'.$pid.'" />
			</form>
		');
		}
	}
	elseif(isset($_REQUEST['delete'])) {
		if(!isset($_REQUEST['confirm'])) {
			echo('<h3>Deleting Post</h3>
			You are about to delete the post "'.htmlentities($_p->tb_posts->getFieldValue($_REQUEST['p'],'title'),ENT_QUOTES,"UTF-8").'"<br />
			<a href="manageposts.php?p='.$_REQUEST['p'].'&amp;delete&amp;confirm">Confirm</a> | 
			<a href="manageposts.php">Cancel</a>');
		}
		else {
			if($_p->tb_posts->idExists($_REQUEST['p'])) {
				echo('<h3>Deleted Post</h3>
				<a href="manageposts.php">Return</a>');
				$_p->delete_post($_REQUEST['p']);
				$rssFile='../'.RSS_PATH;
				$xml=$_p->rebuildRSS();
				$rssHandle=@fopen($rssFile,'w+');
				if($rssHandle===false)
					die('Could not open "'.$rssFile.'" for writing, please check the file permissions.');
				fwrite($rssHandle,$xml);
				fclose($rssHandle);
			}
			else {
				echo('<h3>Post Not Found</h3>
				Did you hit the back button after deleting this post?');
			}
		}
	}
	else {
		echo('<h3>Error</h3>
		Unknown action requested');
	}
?>
		</div>
    </div>
    <div id="footer">
    </div>
</div>
</body>
</html>