<?php
/*
This file powers most of the blog components. 
*/
session_start();
if(isset($_SESSION['autheticate']))
{
	$identification = $_SESSION['identification'];
	$admin = $_SESSION['admin'];
}
if($admin == 1)
{
	//echo " User is administrator <br>";
}
require_once("includes/mysql_login.php");
/*
Multipaging algorithm starts here. 
*/
$rowPerPage = 2;
$pageNum = 1; 
if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
}
$offset = ($pageNum - 1) * $rowPerPage;
$read_post = "SELECT * FROM `post` ORDER BY `date_created` DESC LIMIT $offset, $rowPerPage";
$query   = "SELECT COUNT(*) AS numrows FROM post";
$result  = mysql_query($query) or die('Error, query failed');
$row     = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$PageMax = ceil($numrows/$rowPerPage);
/*
Create the self link to be displayed. Links are for previous page, first page, next page, last page, and current number of pages
*/
$self = $_SERVER['PHP_SELF']; 
$nav = '';

	for($page = 1; $page <= $PageMax; $page++)
		{
			if($pageNum == $page)
			{
			$nav = $nav. " $page";
			} else
			{
			$nav = $nav."<a href = \"$self?page=$page\">$page ||</a>";
			}
		}
			if($pageNum > 1)
			{
				$page = $pageNum - 1;
				$prev = "<a href = \"$self?page=$page\">[prev]</a>";
				$first = "<a href = \"$self?page=1\"><< </a>";
			
			} else
			{
				$prev = "";
				$first = "";
			}
			if($pageNum < $PageMax)
			{
				$page = $pageNum + 1;
				$next = "<a href = \"$self?page=$page\">[next]</a>";
				$last = "<a href = \"$self?page=$PageMax\"> >> </a>";
			} else 
			{
				$next = "";
				$last = "";
			}
/*
Multipage algorithm ends here. 
*/
$read_post_query = mysql_query($read_post);
if(!$read_post_query)
{
	echo "Error on reading database " . "<b> " . mysql_error(). " </b>" ;
}
while($result_row = mysql_fetch_array($read_post_query))
{
// Create the table with different background for odd and even row
if($result_row['postid']%2 == 0)
{
echo "<table width=727 border=0 bgcolor=#999999>";               
echo "<tr>";
echo "<td>";
} else
{
echo "<table width=727 border=0 bgcolor=#9999FF>";              
echo "<tr>";
echo "<td>";
}
/*
Display the contenst of the blog by title, category and body. Link to the file if file has been uploaded
*/
echo "<br><b>". $result_row['title']. "</b>". "<br> <br>";
echo "<b> Category : " . $result_row['category']. "</b><br><br>";
echo $result_row['post']. "<br>";
	if($result_row['attachment'] != NULL)
	{
	$attached_file = $result_row['attachment'];
	echo "<br>";
	echo "<i><a href=file_upload/$attached_file> Attached File</a></i><br>";
	}
echo " <img src = images/time.jpg width = 16 height = 16>  ". $result_row['date_created']. "  ||  ";
				$read_user_query = "SELECT * FROM user where identification = $result_row[identification]";
				$read_user_result = mysql_query($read_user_query);
				/*
				Grant access to modify if user is owner of the blog. 
				*/
				while($result_user = mysql_fetch_array($read_user_result))
				{
					echo "  <img src = images/user.jpg width = 16 height = 18>    " . $result_user['username'] . "   ||  ";
					if($identification == $result_row['identification'])
					{
							echo " || <a href = $authen_change?which=$result_row[postid]&what=edit&page=$pageNum#myanchor_edit_post>  		                                  Edit ||</a> ";
							echo " <a href = $authen_change?which=$result_row[postid]&what=delete&page=$pageNum> Delete ||</a> ";
							echo " <a href = post.php>New Post ||</a>";
					}
					/*
					user use is administrator give him/her access to delete the conent if not appropriate
					$admin == 0, for regular user and $admin == 1 for administrator
					*/
					if($admin == 1)
					{
						   echo " <a href = $authen_change?which=$result_row[postid]&what=delete&page=$pageNum>Admin Delete || </a> ";
					}
					if(isset($identification))
					{
						echo " <a href = $authen_change?which=$result_row[postid]&what=add_comment&page=$pageNum&#myanchor_add_comment><img src = images/comment.jpg width = 20 height = 12> Add Comment</a>";
					}
				}
				/*
				 If comment has been submitted for the corresponding blog display it in the reverse chronological order.  
				 */
				$num_row = $result_row['postid'];
				$read_comment = "SELECT * FROM comment where postid = $result_row[postid] ORDER BY `date_created` DESC";
				$read_comment_result = mysql_query($read_comment);
				while($result_comment_row = mysql_fetch_array($read_comment_result))
				{
					echo "<b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $result_comment_row['subject'] . "</b>	                          <br>"; 
					echo " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Comment : " . $result_comment_row['body'] . "                         <br> " ;
					$authen_user_comment = "SELECT * FROM user where identification = $result_comment_row[identification]"; 
					echo "<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src = images/time.jpg> " . 	        $result_comment_row['date_created'] . " || " ;
					$authen_user_comment_result = mysql_query($authen_user_comment);
					while($result_user_comment = mysql_fetch_array($authen_user_comment_result))
					{
						echo " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src = images/user.jpg width = 16 height                              = 18>  ". $result_user_comment['username'] . " || " ;
						if($identification == $result_comment_row['identification'])
						{
							echo "<a href = $authen_change?which=$result_comment_row[commentid]&what=edit_comm&page=$pageNum#anchor_edit_comment>Edit </a> || ";
							echo "<a href = $authen_change?which=$result_comment_row[commentid]&what=delete_comm&page=$pageNum> Delete</a> || ";
						}
						/*
						 if user is administrator allow him to delete the comment 
						 */
						if($admin == 1)
						{
							echo " <a href = $authen_change?which=$result_comment_row[commentid]&what=delete_comm&page=$pageNum>Admin Delete</a> || ";
						}
					}
				}
				echo "</td>";
				echo "</tr>";
				echo "</table>";

}
/*
Allow authenticated user to delete comments
*/
if($_GET['what'] == delete_comm)
{
	//include("javapopups.htm");
	//echo "<br> Delete the comment " ; 
	//echo "Row number " ;
	$row_num = $_GET['which'];
	//echo $row_num .  "<br>is row number ";
	$delete_comment = "DELETE FROM comment where commentid = $row_num";
	$delete_comment_query = mysql_query($delete_comment);
	if(!delete_comment_query)
	{	
		echo "Error on deleting ".mysql_error();
	} else
	{
		echo "<br>Comment deleted! "; 
		echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$pageNum\">";
	}
}
/*
Allow authenticated user edit the comment
*/
if(($_GET['what']==edit_comm)&&(!isset($_POST['edit_comment'])))
{
$comment_row_num = $_GET['which']; 
$comment_row = "SELECT * FROM `comment` where commentid = $comment_row_num";
$comment_row_result = mysql_query($comment_row);
	if(!$comment_row_result)
	{
		echo "Error on quering comment " . mysql_error() . "<br> " ;
	}
	else
	{
		while($row_comment = mysql_fetch_array($comment_row_result))
		{
			echo "<a name=anchor_edit_comment></a>";
			echo "<form action=\"$PHP_SELF\" method=\"POST\">";
			echo "Subject:<input type = text name = editsubject value = $row_comment[subject]><br> <br>";
			echo "Comment:<br><textarea name = editcommentbody cols = 30 rows = 10>$row_comment[body]</textarea><br><br>";
			echo "<input type = submit name = edit_comment value = Edit >";
			echo "</form>";
			
		}
	}
}
/*
 Store new value of comment and store in MySQL
 */
if(isset($_POST['edit_comment']))
{ 
	echo $subject =  mysql_real_escape_string($_POST[editsubject]);
	echo $body = mysql_real_escape_string($_POST[editcommentbody]);
	echo $commentid = $_GET[which];
	echo "<br>" . $subject . "<br> " . $body. "<br> " . $commentid ; 
	$dump_edit_comment = "UPDATE comment SET subject = '$subject', body = '$body' where commentid = '$commentid'";
	$edit_comment_query = mysql_query($dump_edit_comment);
		if(!$edit_comment_query)
		{
			echo "Error on updating comment " . mysql_error();
		}
		else
		{
			echo " Update Successful! " ;
			echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$pageNum\">";
		}
}
/*
Allow authenticated user to add comments. 
*/
if(($_GET['what']==add_comment))
{
	if(isset($_POST['submit_comment']))
	{
		function create_table_comment()
		{
			$create_table_comment = 'CREATE TABLE `comment`(`commentid` int(6) auto_increment NOT NULL, 
														`subject` varchar(200) NOT NULL, 
														`body` longtext NOT NULL, 
														`identification` int NOT NULL, 
														`postid` int NOT NULL,
														`date_created` timestamp NOT NULL, 
														 PRIMARY KEY(`commentid`))';
			$create_table_result = mysql_query($create_table_comment);
				if(!$create_table_result)
				{
					echo "<br>Error on creating table ". mysql_query();
				}
				else
				{
					echo "<br>Table created!";
				}												
		}
		function dump_comment_mysql()
		{
			$page_num = $_GET['page']; 
			$identification = $_SESSION['identification']; 
			$post_id = $_GET['which']; 
			$subject = stripslashes($_POST['subject']);
			$subject = mysql_real_escape_string($subject);
			$body = stripslashes($_POST['commentbody']);
			$body = mysql_real_escape_string($body);
			$dump_comment_mysql = "INSERT INTO `comment` VALUES('$commentid', '$subject', '$body', '$identification', '$post_id', now())";
			$dump_comment_result = mysql_query($dump_comment_mysql);
				if(!$dump_comment_result)
				{
				echo "<br>Error on quering comment" . mysql_error();
				}
				 else
				{
				echo "<br>Comment Submitted";
				echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$page_num\">";
				}
				
		}
		/*
		Function call to store comment on MySQL
		*/
		dump_comment_mysql();
	} else
	{
		echo "<a name=myanchor_add_comment></a>"; // Link Anchor
		echo "<form action=\"$PHP_SELF\" method=\"POST\">";
		echo "Subject: <input type = text name = subject> <br><br>";
		echo "Comment:<br> <textarea name = commentbody cols = 30 rows = 10></textarea><br><br>";
		echo "<input type = submit name = submit_comment value = Submit Comment>";
		echo "</form>";
	}
		
}
/*
For logged in user allow to create new Post
*/
if(isset($_SESSION['autheticate']))
{
	echo "<br><a href = post.php>New Post</a>";
}
else
{
}
/*
Multipage algorithm is called here. Link to multiple page will apprear on the bottom of the page. 
*/
echo "<br>$first$nav$last" ;// . $first. $prev. $nav. $next. $last;
$authen_change = $_SERVER['PHP_SELF']; 
/*
Allow authenticated user to edit the post. 
*/
if(($_GET['what']==edit)&&(!isset($_POST['submit'])))
{
$edit_row_num = $_GET['which'];
$edit_row_post = "SELECT * FROM `post` where postid = $edit_row_num";
$edit_row_post_result = mysql_query($edit_row_post);
		if(!$edit_row_post_result)
		{
			echo " Error on MySql " . mysql_error();
		}
		else
			{
				while($post_row = mysql_fetch_array($edit_row_post_result))
				{
					echo "<a name=myanchor_edit_post></a>"; // Anchored Edit Post
					echo "<form action=\"$PHP_SELF\" method=\"POST\">";
					echo "<input type = text name = title value = $post_row[title]> <br>";
					echo "<input type = text name = category value = $post_row[category]><br>";
					echo "<textarea name = body cols = 40 rows = 10> $post_row[post] </textarea><br>"; 
					echo "<input name=submit type=submit value=Edit>";
					echo "</form>";
				}
			}		

}
/*
Submit the editated post. 
*/
if(isset($_POST['submit']))
{
 $page_num = $_GET['page'];
 echo " <br>Title: " . $_POST['title'];
 echo " <br>Category: " . $_POST['category'];
 echo "<br> Body:" . $_POST['body'];
 echo "<br> Identification:". $identification;
 echo "<br>Row Number: " . $_GET['which'];
 $row_num = ($_GET['which']);
 $title = mysql_real_escape_string($_POST['title']);
 $category = mysql_real_escape_string($_POST['category']);
 $body = mysql_real_escape_string($_POST['body']);
 $identification;
  	$edit_post = "UPDATE `post` SET title = '$title', category = '$category', 
								post = '$body', identification = '$identification', date_created = now() where postid = '$row_num'";
									
	$edit_post_result = mysql_query($edit_post);
	if(!$edit_post_result)
	{
		echo "<br> Error on while editing the post " . mysql_error();
	} else
	{
		echo "<br> Your post has been successfully edited " ;
		echo "<meta http-equiv = \"refresh\" content = \"1; URL=index.php?page=$pageNum\">";
	}
	
}
/*
Allow authenticated user to delete the post. 
*/
if($_GET['what']==delete)
{
$page_num = $_GET['page'];
$delete_row_num = $_GET['which'];
$delete_post = "DELETE FROM `post` WHERE postid = '$delete_row_num'";
$delete_post_result = mysql_query($delete_post);
	if(!$delete_post_result)
	{
		echo " Post can not be deleted " . mysql_error();
	}
	else
	{
		echo " Post deleted! "; 
		echo "<meta http-equiv = \"refresh\" content = \"0; URL=index.php?page=$pageNum\">";
	}
}
?>