<?php

if(stristr(htmlentities($_SERVER['PHP_SELF']), "npt-file-cms.php")){
	die("You cannot access this file directly!");
}

# Copyright (C) 2010 - onwards. The Napata CMS Project.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# http://www.gnu.org/copyleft/gpl.html

require('./npt-load.php');

class NapataFileCMS {

/*--------------------------------------------------------------------------------------
*Class Properties
----------------------------------------------------------------------------------------*/
private $path = DIRPATH /*'./'*/;
private $handle;
private $userid;
private $file_size = 80000;
public $sitename = SITENAME;
public $site_tagline = SITE_SUBTITLE;
public $stylesheet = STYLESHEET;
public $articles_directory = 'articles';
public $images_directory = 'images';

/*---------------------------------------------------------------------------------------*/
public $title;
public $content;

/*---------------------------------------------------------------------------------------
*User related methods
-----------------------------------------------------------------------------------------*/

function PasswordsMatch($pass1, $pass2) {

	if($pass1 == $pass2) {
	
		return true;
		
	}
	else
	{
	
		#die("<div style='padding: 10px; background-color: #f2f5a9; border: 1px solid #0000ff;'>Passwords do not match</p>");
		return false;
		
	}
	
}

function ChangePassword ($p,$p2) {

	require($this->path.'sec/class-pass.php');
	
	$hasher = new PasswordHash(8, false);
	
	if(isset($_POST['change_password']))
	{
		if($p != '' && !empty($p2) && $this->PasswordsMatch($p, $p2) !== false)
		{
		
			$password = $hasher->HashPassword($p);
			
			$this->handle = fopen($this->path.'sec/secret.txt', 'w+') or die("<p style='padding: 10px; background-color: #f2f5a9; border: 1px solid #0000ff;'>Your password could not be saved. Please check whether sec/secret.txt is writeable.</p>");
			
			if(false !== $this->handle)
			{
			
				fwrite($this->handle, $password);
				
				fclose($this->handle);
			
			}
			
			header('Location:index.php?page=console&success=1');
		
		}
		
	}
	
}

function CheckUserPassword($password, $hash) {

	require_once($this->path.'sec/class-pass.php');
	
	$login_pass = new PasswordHash(8, false);
	
	return $login_pass->CheckPassword($password, $hash);
	
}

function SetSessionId(){

	$this->userid = uniqid(microtime()); #prefix microtime to uniqid output
	
	return $this->userid.'_'.session_id();

}
	
function Login($password){
	if(isset($_POST['login'])){
		$this->handle = @file_get_contents($this->path.'sec/secret.txt');
		
		$h = $this->handle;
		
		if($this->CheckUserPassword($password, $h) !== false)
		{
		
			$_SESSION['logged'] = true;
			$_SESSION['username'] = $_POST['username'];
			$_SESSION['user_id'] = $this->SetSessionId();
			
			header('Location:index.php?page=console');
			exit;
			
		}
		else
		{
		
			return false;
			
		}
	}
	
}

function LoginFail($pass) {
	if(isset($_POST['login'])){
		if($this->Login($pass) == false){
		
			header('Location:index.php?page=Login&success=0');
			exit;
			
		}
	}
}


/*---------------------------------------------------------------------------------------
*File upload related methods
-----------------------------------------------------------------------------------------*/

function HandleArticleUploads() {

$ArticleFile = array();

		/*----------------------------------------------------------------------------------
		Following upload code credits go to Timothy Boronczyk at PHPMaster (http://phpmaster.com/file-uploads-with-php/)
		*NOTE: Minor alterations/modifications/additions have been added by me
		------------------------------------------------------------------------------------*/
		
		if (!empty($_FILES["articles"])) {
			$ArticleFile = $_FILES["articles"];

			if ($ArticleFile["error"] !== UPLOAD_ERR_OK) {
				echo "<p>Article upload failure!</p>";
				exit;
			}
			
			$name = preg_replace("/[^A-Z0-9._-]/i", "_", $ArticleFile["name"]);

			if($ArticleFile["size"] > $this->file_size){
				return false;
			}
			
			if($this->TestIfUploadTextFile($ArticleFile["name"]) == true)
			{
				
				$i = 0;
				$parts = pathinfo($name);
				while (file_exists($this->path.$this->articles_directory.'/'. $name)) {
					$i++;
					$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
				}
				
				$success = move_uploaded_file($ArticleFile["tmp_name"],$this->path.$this->articles_directory.'/'. $name);
				if (!$success) { 
					echo "<p style='padding: 10px; background-color: #ffe4e1; border: 1px solid #0000ff;'>The article was not saved.</p>";
					exit;
				}
				else
				{
					echo "<p style='padding: 10px; background-color: #f2f5a9; border: 1px solid #0000ff;'>Article saved successfully.</a>";
				}
				chmod($this->path.$this->articles_directory . $name, 0644);
				
			}
			
			#DISABLED Image uploads for now 
			#----------------------------------------------------------------------
			/*elseif($this->TestIfUploadImage() == true)
			{
				
				$parts = pathinfo($name);
				while (file_exists($this->path.$this->images_directory.'/'. $name)) {
					$i++;
					$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
				}
				$success = move_uploaded_file($ArticleFile["tmp_name"],
					$this->path.$this->images_directory.'/'. $name);
				if (!$success) { 
					echo "<p>The article was not saved.</p>";
					exit;
				}
				
				chmod($this->path.$this->images_directory .'/'. $name, 0644);
				
			}*/

			
		}
	
}

function TestIfUploadImage() {
	$ArticleFile = array();
	$ArticleFile = $_FILES["articles"];
	$fileType = getimagesize($ArticleFile["tmp_name"]);
	$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
	if (!in_array($fileType, $allowed)) {
	
		echo 'Invalid image recognized. Please upload either a GIF, JPEG, or a PNG image';
	}
	else
	{
		return true;
	}
}

function TestIfUploadTextFile($upload_file){
		if(substr($upload_file, -4, 4) != '.txt')
		{
			echo "<div style='padding: 10px; background-color: #ffe4e1; border: 1px solid #0000ff;'>Invalid file type detected. Please upload text file articles only. <a href='index.php?page=console'>&laquo; Back</a></div>";
			exit;
		}
		else {

			return true;
			
		}
}

/*---------------------------------------------------------------------------------------
*Display related methods
-----------------------------------------------------------------------------------------*/
function CSSFileExtension ($theme) {

	return substr($theme,-4, 4);
	
}

function InsertStyleSheet ($theme) {
		
		$templates = array();
		
		//Open the template directory
		$d = opendir($this->path.'css');
		
			while(false !== $dop = readdir($d))
			{
		
				if($dop[0] == "." || $dop[0] == "..") continue;
				
				else
				{
					$t[]= $dop;
				}
				
			}
			
				foreach($t as $temp){
				
					if(is_file($this->path."css/$temp") && $temp == $theme.'.css')
					{
						
						if($this->CSSFileExtension($temp) == '.css')
						{
						
							$theme = $temp;
							
						}
						
						else{ echo 'Theme is not a stylesheet file.'; }
							
					}
						
					//if(is_file("css/$temp")) {echo substr($temp, -4, 4);}
					
				}
			
			return $theme;

		}
	

function ActionLinks() {
?>
<div id="action-links">
		<?php
		echo "<table>";
		echo '<tbody><tr>';
		
		if(isset($_SESSION['logged']) && $_SESSION['logged'] == true){

				echo "<td><a href='index.php?page=admin'>Admin</a></td>";
				echo "<td><a href='index.php?page=console'>Upload Article</a></td>";

			if(!empty($_SESSION['username'])){
				echo "<td><a href='index.php?page=logout'>Logout</a></td>";
			}
		}
		echo "<td><a href='index.php'>Home</a></td>";
		if(empty($_SESSION['username']))
		{
			echo "<td><a href='index.php?page=Login'>Login</a></td>";
		}
		echo '</tr>';
		echo '</tbody></table>';
		?>
</div>
<?php
}


function Header() {

?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
	<html>
	<head>
	<title><?php echo $this->sitename.'::'.$this->title;?></title>
	<meta content='7 days' name='revisit' />
	<meta content='7 days' name='revisit-after' />
	<meta content='Napata CMS' name='generator' />
	<?php if(isset($GET['page']) && $_GET['page'] != '') echo "<meta content =\"NOINDEX, NOFOLLOW, NOARCHIVE\" name=\"robots\" />\n";?>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" />
	<link title="sheet" rel="StyleSheet" type="text/css" href="css/<?php echo $this->InsertStyleSheet($this->stylesheet); ?>" >
	</head>
	<body>
	<div id="siteTitle">
	<?php echo '<a href="index.php">'.$this->sitename.'</a>';?><div id="subTitle"><?php echo $this->site_tagline;?></div>
	</div>
	
<?php
}

function SpecHeader() {

?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
	<html>
	<head>
	<title><?php echo $this->sitename.'::'.$this->title;?></title>
	<meta content='Napata CMS' name='generator' />
	<meta content ="NOINDEX" name="robots" />
	<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
	<link title="sheet" rel="StyleSheet" type="text/css" href="css/admin/admin.css" >
	</head>
	<body>
	<div id="siteTitle">
	<?php echo '<a href="index.php">'.$this->sitename.'</a>';?><div id="subTitle"><?php echo $this->site_tagline;?></div>
	</div>
	<div id = "SPEClinks">
	<a href="index.php">[Home]</a> 
	<?php if(isset($_GET['page']) && !(empty($_SESSION['username']))) print '<a href="index.php?page=admin">[Admin Home]</a><a href="index.php?page=logout">[Logout]</a>';
	?>
	</div>
	<div id="content">
	
<?php
}

function AdminScreen() {
$this->title = 'Admin Home';
$this->SpecHeader();
?>

<div id="leftsideBar">
	
</div>
	
<div id="content">	
<h1><?php echo $title;?></h1>
</div>
<br>

<br>
<div id="footer"><?php include_once("./footer.php"); echo footer($copyright);?></div>
</body>
</html>
<?php
}

function LoginPage() {

$this->title = 'Login';
$this->SpecHeader();

?>

	<?php 
	$this->LoginFail($_POST['password']);
	if(isset($_GET['success']) && $_GET['success'] == 0) echo "<div style='padding: 10px; background-color: #f2f5a9; border: 1px solid #0000ff;'>Wrong password. Please <a href='index.php?page=Login'>try again</a></div>"; ?>
	<table><tbody>
	<tr>
	<td><form method='post' action='index.php?page=login'>
	<input type="hidden" name="redirect" value="index.php" />
	<label> Username :
	</label><br>
	<input type="text" name="username" value="" size="40"/ maxLength="18"/></td>
	</tr>
	<tr>
	<td>
	<label> Password:
	</label><br>
	<input type="password" name="password" value="" size="40" maxLength="18" title="Type in your password here"/></td>
	<tr>
	<td><input type="submit" name="login" value="Login"/></td>
	</tr>
	</form>
	</tbody></table>
	</div>
	<div id="footer"><?php include_once("./footer.php"); echo footer($copyright);?></div>
	</body>
	</html>
<?php
}

}