<?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 Pages</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="managepages.php" class="breadcrumb">Manage Pages</a>'); ?>
    </div>
    <div id="sidebar">
<?php
	require('nav.include.php');
?>
    </div>
    <div id="content">
        <div class="contentblock">
				<h2>Edit A Page</h2>
<?php
	if(!isset($_REQUEST['p'])) {
		echo('<h3>Select Page To Edit</h3>');
		$pagesdata=fetch::sortSelection($_p->tb_pages->select('true',array('title','timestamp','is_published')),'timestamp',SORT_DESC);
		if(count($pagesdata)>0) {
			//Count pages
			$total_pages=count($pages);
			$pages=$total_pages/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_pages%POSTS_PER_LIST!=0)
				$pages=floor($pages)+1;
			//Decide what page is showing
			$p=isset($_REQUEST['pagep'])?$_REQUEST['pagep']: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="managepages.php?pagep=0">&laquo; First</a> ');
				if($p>1)
					echo('<a class="previous" href="managepages.php?pagep='.($p-1).'">Previous</a> ');
				for(;$i<$p;$i++)
					echo('<a class="last5" href="managepages.php?pagep='.$i.'">'.$i.'</a> ');
				echo('<a class="current"a href="managepages.php?pagep='.$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="managepages.php?pagep='.$y.'">'.$y.'</a> ');
				if($p<$pages-2)
					echo('<a class="next" href="managepages.php?pagep='.($p+1).'">Next</a> ');
				if($p<$pages-1)
					echo('<a class="last" href="managepages.php?pagep='.($pages-1).'">Last ('.($pages-1).') &raquo;</a>');
			}
			echo('</div>');
			//Show pages on that page
			$startat=$p*POSTS_PER_LIST;
			$i=0;
			$y=POSTS_PER_LIST;
			echo('<ul>');
			foreach($pagesdata as $pid => $d) {
				if($i==$startat) {
					if($y>0) {
						echo('<li>ID#'.$pid.' <strong>'.$d['title'].'</strong> made on '.date('j<\s\up>S</\s\up> M y',$d['timestamp']).' ('.($d['is_published']===true?'Published':'Draft').')<br />
						<a href="managepages.php?p='.$pid.'&amp;edit">Edit</a> | 
						<a href="managepages.php?p='.$pid.'&amp;delete">Delete</a></li>');
						$y--;
					}
					else {
						break;
					}
				}
				else {
					$i++;
				}
			}
			echo('</ul>');
		}
		else {
			echo('There are no pages yet.');
		}
	}
	elseif(isset($_REQUEST['edit'])) {
		$printform=true;
		$pid=isset($_GET['p'])?$_GET['p']:$_POST['p'];
		//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) {
			$pagecontent=fetch::unescapePostVar($_POST['pagecontent']);
			$pagetitle=fetch::unescapePostVar($_POST['pagetitle']);
		}
		else {
			$pagecontent=$_p->tb_pages->getFieldValue($pid,'content');
			$pagetitle=$_p->tb_pages->getFieldValue($pid,'title');
		}
		//Do the right thing
		if(isset($_POST['pagetitle'])) {
			//Fix page data
			if($_POST['pagetitle']==='') {
				echo('<h3>Error</h3>
				Please enter a title.<br />');
			}
			else {
				if(isset($_POST['attach'])||isset($_POST['attachsearch'])) {
					//Attachment system
					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>Page Saved</h3>
					<a href="managepages.php?p='.$pid.'&amp;edit">Continue editing</a>');
					if(isset($_POST['publish'])) {
						$_p->edit_page($pid,$pagetitle,$pagecontent,true);
						echo(' | <a href="../index.php?page='.$pid.'">View Page</a>');
					}
					else
						$_p->edit_page($pid,$pagetitle,$pagecontent);
					
					//Attachment system
					if(isset($_POST['attach'])) {
						echo('<br />Attaching...');
						//Add and check result
						if($_p->attach_page(basename($_FILES['file_upload']['name']),$_FILES['file_upload']['tmp_name'],$pid))
							echo('<br />Attachment added.');
						else
							echo('<br />Attachment failed to be added.');
					}
					$printform=false;
				}
				//Preview
				else {
					echo('
					<h3>Previewing Page</h3>'.
					$_p->parsePost($pagecontent,-1,USE_GESHI_PAGES));
				}
			}
		}
		
		if($printform) {
		echo('
			<form enctype="multipart/form-data" action="managepages.php" method="post">
				<h3>Title</h3>
				<input tabindex="1" type="text" class="full" name="pagetitle" value="'.$pagetitle.'"/>
				<h3>Content</h3>
				<div class="toolbar">
				<a href="#" title="Bold" onclick="addtag(\'pagecontent\', \'b\')"><b>B</b></a>
				<a href="#" title="Italics" onclick="addtag(\'pagecontent\', \'i\')"><i>I</i></a>
				<a href="#" title="Underline" onclick="addtag(\'pagecontent\', \'u\')"><u>U</u></a>
				<a href="#" class="deform" title="Code" onclick="addtag(\'pagecontent\', \'code\')">code</a>
				<a href="#" class="deform" title="Code" onclick="addtag(\'pagecontent\', \'quote\')">quote</a>
				<a href="#" class="deform" title="Html" onclick="addtag(\'pagecontent\', \'html\')">html</a>
				<a href="#" class="deform" title="Create A Link" onclick="addurl(\'pagecontent\')">url</a>
				<a href="#" class="deform" title="Insert an Image" onclick="addtag(\'pagecontent\', \'img\')">img</a>
				<a href="#" class="deform" title="Add Link to a Post" onclick="linkpost(\'pagecontent\')">+post</a>
				<a href="#" class="deform" title="Add Link to a Page" onclick="linkpage(\'pagecontent\')">+page</a>
				</div>
				<textarea tabindex="2" class="full" rows="30" cols="60" name="pagecontent" id="pagecontent">'.htmlentities($pagecontent,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,false);" />
				<a href="javascript:searchattachments(\'\',false);">Show all attachments</a> | 
				<a href="javascript:searchattachments(false,false);">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="Attach" />
				<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 Page</h3>
			You are about to delete the page "'.htmlentities($_p->tb_pages->getFieldValue($_REQUEST['p'],'title'),ENT_QUOTES,"UTF-8").'"<br />
			<a href="managepages.php?p='.$_REQUEST['p'].'&amp;delete&amp;confirm">Confirm</a> | 
			<a href="managepages.php">Cancel</a>');
		}
		else {
			echo('<h3>Deleted Page</h3>
			<a href="managepages.php">Return</a>');
			$_p->delete_page($_REQUEST['p']);
		}
	}
	else {
		echo('<h3>Error</h3>
		Unknown action requested');
	}
?>
		</div>
    </div>
    <div id="footer">
    </div>
</div>
</body>
</html>