<?php
session_start();
///////////////////////////////////////////////////////////////////////////////////
//	Wak's Ask&Answer/FAQs Script
//
//	Script by Katie http://luved.org - Teljes magyar felület by Adliz http://hd.vilaga.hu
//
//	This script is linkware and can be used or modified as long as all credit is
//	left attached to this file and a link is placed on your website to
//	http://www.luved.org
//	You are forbidden to sell or distribute this script without permission by
//	it's creator and if a bug is found, report to scripts@luved.org
///////////////////////////////////////////////////////////////////////////////////

define(DBFILE, "{$dir}askanswer.txt");
define(CONFIGFILE, "{$dir}config.txt");
define(ANSWERS, "{$dir}templates.txt");
define(BANLIST, "{$dir}banlist.txt");
$phpSelf = $_SERVER['PHP_SELF'];
$TBLCONFIG = 'border="0" width="600" align="center" cellpadding="5" cellspacing="0"';
$sec = 30;
$defaultEntryPerPage = 10;
$timeBetweenPost = time();
$qLen = 30;
if (!isSet($_SESSION['floodcontrol'])) $_SESSION['floodcontrol'] = time();

function convertLinks($str) {
	$str = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',    '<a href="\\1" target="_blank">\\1</a>', $str);
	$str = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',    '\\1<a href="http://\\2" target="_blank">\\2</a>', $str);
	$str = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',    '<a href="mailto:\\1">\\1</a>', $str);
	return $str;
}

function printRedirect($url, $sec) {
?>
<script>
<!--
var targetURL="<?php echo $url?>"
var countdownfrom=<?php echo $sec?>;
var currentsecond=countdownfrom
function countredirect(){
	if (currentsecond!=1){
		currentsecond-=1
	} else{
		window.location=targetURL
		return
	}
	setTimeout("countredirect()",1000)
}
countredirect()
//-->
</script>
<?php
}

function perPage($dbRows, $perpage, $pagenum) {
	global $defaultEntryPerPage;
	if ($perpage < 1)
		$perpage = $defaultEntryPerPage;
	if ($pagenum == "") $pagenum = 1;
	// total posts in tagboard
	$totalRecords = count($dbRows);
	// numer of pages needed to scroll through all entries
	$numPages = (int) ($totalRecords / $perpage);
		if ($totalRecords % $perpage != 0) {
			$numPages += 1;	
		}
	$endentry = $perpage * $pagenum;
	$startentry = $endentry - $perpage + 1;
	if ($endentry > $totalRecords)
		$endentry = $totalRecords;
	
	while ($startentry <= $endentry) {
		$tmpEntries[] = $dbRows[$startentry-1];
		$startentry++;
	}
	$info = array('entries' => $tmpEntries, 'numpages' => $numPages);
	return $info;
}

function printJumpToPage($url, $numPages, $pagenum) {
if ($pagenum == "") $pagenum = 1;
  if ($numPages > 1) {
		echo "lapok: ";
		echo "<a href=\"${url}1\" title=\"Első lap\">Első</a> ";
		if ($pagenum > 1) {
			$x = $pagenum - 1;
			echo "<a href=\"${url}$x\" title=\"Előző lap\">&laquo;</a> ";
		}
	if ($numPages > 5) {
		if ($pagenum < $numPages - 1) {
			// start at the page number before the current one
			if ($pagenum > 1) $start = $pagenum - 1;
			for ($x = $start; $x < $numPages; $x++) {
				if ($x != $numPages - 1) {
					if ($pagenum == $x) {
						$lastPrinted = $x;
						echo "$x ";
					} else if ($x == $pagenum - 1 || $x == $pagenum + 1) {
						$lastPrinted = $x;
						echo "<a href=\"${url}$x\">$x</a> ";
					}
				}
			}
			$dot = " ... ";
			for ($x = $numPages-1; $x < $numPages + 1; $x++) {
				if ($dot != '') {
					if ($lastPrinted != $numPages-2)
						$dot = " ... ";
					else
						$dot = "";
				}
				echo "$dot<a href=\"${url}$x\">$x</a> ";
				$dot = "";
			}
		} else {
			$end = 3;
			for ($x = 1; $x < $end; $x++) {
				if ($pagenum == $x) 
					echo "$x ";
				else
					echo "$dot<a href=\"${url}$x\">$x</a> ";
			}
				echo " ... ";
				if ($pagenum > 1) $start = $pagenum - 1;
				for ($x = $start; $x < $numPages + 1; $x++) {
					if ($x != 2) {
						if ($pagenum == $x) {
							$lastPrinted = $x;
							echo "$x ";
						} else if ($x == $pagenum - 1 || $x == $pagenum + 1) {
							$lastPrinted = $x;
							echo "<a href=\"${url}$x\">$x</a> ";
						}
					}
				}
		}
	} else {
		for ($x = 1; $x < $numPages + 1; $x++) {
			if ($pagenum == $x) {
				echo "$x ";
			} else {
				echo "<a href=\"${url}$x\">$x</a> ";
			}
		}
	}
		
		if ($pagenum < $numPages) {
			$x = $pagenum + 1;
			echo "<a href=\"${url}$x\" title=\"Következő lap\">&raquo;</a> ";
		}
	echo "<a href=\"${url}$numPages\" title=\"Utolsó lap\">Utolsó</a> ";
  }
}

function isLoggedIn() {
	if ($_SESSION['password'] == "") {
		header("Location: answer.php");
	}
}

function dateFormatAdv($timestamp, $format) {
	return date($format, $timestamp);
}

function fixStr($str) {
	$str = str_replace("¦", "&brvbar;", $str);
	$str = str_replace("<", "&lt;", $str);
	$str = str_replace(">", "&gt;", $str);
	$str = str_replace("\r\n", "(br)", $str);
	$str = stripslashes($str);
	return $str;
}

function fixBrk($str) {
	return str_replace("(br)", "\r\n", $str);
}

function fixBrkForHTML($str) {
	return str_replace("(br)", "<br />", $str);
}

function printTemplateAnswers() {
				$templates = file(ANSWERS);
				if (count($templates) > 0) {
				echo 'Mentett válaszok: 
				<select name="savedanswer">';
				foreach ($templates as $row) {
					list($id, $title) = get($row);
					echo '<option value="'.$id.'">'.$title.'</option>';
				}
				echo '</select>
					<input type="submit" name="insert" value="Választ" />
				</td>';
				} else {
					echo '<a href="'.$phpSelf.'?go=templates">Use a template</a>';
				}
}

function getTotalAnswered() {
	$dbRows = file(DBFILE);
	foreach ($dbRows as $rows) {
		list($id, $question, $answer)= get($rows);
		if ($answer != 'null') {
			$answeredRows[] = $rows;
		}
	}
	return $answeredRows;
}

function addQuestion($q) {
	global $timeBetweenPost, $sec, $phpSelf, $qSuccess, $qFailed_DoublePost, $qFailed_BlankPost;
	$id = getFileId(DBFILE);
	$ip = $_SERVER['REMOTE_ADDR'];
	if (($q != '') && ($_SESSION['floodcontrol'] <= $timeBetweenPost)) {
		$datetime = time();
		$q = fixStr($q);
		$break = "";
		if (total(DBFILE) != 0) $break = "\r\n";
			$fd = fopen(DBFILE, "a+") or die("Can not open file: ".DBFILE);
			$wdata = "$break$id\¦$q\¦null\¦$ip\¦$datetime\¦0";
			$fout = fwrite($fd, $wdata);
			if ($fout != strlen($wdata)) {
				echo "File write failed";
			return false;
		}
		fclose($fd);
		list($id, $key, $panelurl, $email, $notify, $entryPerPage, $dtFormat) = getFileRow(CONFIGFILE);
		if ($notify == 'yes' && $email != '@')
			sendMailNotification($email, $q, $panelurl);
		$_SESSION['floodcontrol'] = $timeBetweenPost + $sec;
		echo $qSuccess;
	} else {
		if ($_SESSION['floodcontrol'] > $timeBetweenPost) {
			echo $qFailed_DoublePost;
		} else if ($q == '') {
			echo $qFailed_BlankPost;
		}
	}
	printRedirect($phpSelf."?page=".$_GET['page'], 3);
}

function sendMailNotification($sendToEmail, $q, $domainUrl) {
	$subject = "New question submitted";
	$message = "Question submitted:\r\n";
	$message .= $q . "\r\n\r\n";
	$message .= "Reply by logging into your control panel:\r\n";
	$message .= $domainUrl;
	mail($sendToEmail, $subject, $message, "From: $sendToEmail<$sendToEmail>\r\n");
}

function addAnswer($answerToAdd) {
	$break = "";
	if (total(ANSWERS) != 0) $break = "\r\n";
	$fd = fopen(ANSWERS, "a+") or die("Can not open file: ".ANSWERS);
	$wdata = "$break$answerToAdd";
	$fout = fwrite($fd, $wdata);
	if ($fout != strlen($wdata)) {
		echo "File write failed";
		return false;
	}
	fclose($fd);
}


function getTotalUnanswered() {
	$dbRows = file(DBFILE);
	foreach ($dbRows as $rows) {
		list($id, $question, $answer)= get($rows);
		if ($answer == 'null')
			$unansweredRows[] = $rows;
	}
	return $unansweredRows;
}

function logUser($pass) {
	$config = getFileRow(CONFIGFILE);
	list($id, $key, $domainUrl) = $config;
	if (!$pass){
		return "Nem adtál meg jelszót<br />\r\n";
	} else {
		$pass = strtolower($pass);
		$pass = crypt($pass, $key);
	}
	if ($pass != $key) {
		return "Helytelen jelszó <br />\r\n";
	} else {
		$_SESSION['password'] = $pass;
		header("Location: ".$phpSelf."?go=home");	
	}
}

function desc($rows) {
	$rowCount = count($rows);
	$cur = end($rows);
	if ($rowCount != 1) {
		for ($i = 0; $i < $rowCount; $i++) {
			$newRows[$i] = $cur;
			$cur = prev($rows);
		}
		return $newRows;
	} else
		return $rows;
}


$HEADER = <<<HEADER
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<title>Üdv az adminfelületen</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script>
<!--
function checkall(formname, idname) {
	var x = 1;
	var state;
	var check1 = eval("document.forms." + formname + ".selectEntry1");
	if (check1.checked)
		state = true;
	else
		state = false;
	var checkobj = document.getElementById(idname + x)
	while (checkobj != null) {
		checkobj.checked = state;
		x++;
		checkobj = document.getElementById(idname + x)
	}
}

function confirmUpdate() {
	var agree = confirm("You are about to update the currently selected template.\\n Please check it is the one you want to update and click OK to continue.");
	if (agree)
		return true;
	else
		return false;
}

function confirmDelete() {
	if (confirm("WARNING: You are about to delete one or more entries from the database.\\nAre you sure you want to do this?"))
		return true;
	else
		return false;
}

-->
</script>
</head>
<body>
<center><h3>Adminfelület</h3></center>
<table width="80%" cellspacing="0" cellpadding="5" align="center" class="noborder">
	<tr>
		<td valign="top" align="right">
		<table class="noborder">
	<tr>
		<td class="td" colspan="2"><div style="text-align: left;"><b>MENÜ</b></div></td>
	</tr>
	<tr>
		<td class="td" colspan="2"><a href="$phpSelf?go=home">Megválaszolatlan kérdések</a></td>
	</tr>
	<tr>
		<td class="td"><a href="$phpSelf?go=manage">Kérdés/válasz szerkesztése, törlése </a></td>
	</tr>
	<tr>
		<td class="td" colspan="2"><a href="$phpSelf?go=templates">Sablon válaszok</a></td>
	</tr>
	<tr>
		<td class="td" colspan="2"><a href="$phpSelf?go=config">Beállítások</a></td>
	</tr>
	<tr>
		<td class="td"><a href="$phpSelf?go=logout">Kijelentkezés</a></td>
	</tr>
</table>
		
		</td>
		<td>
		<table $TBLCONFIG class="noborder">
HEADER;
/////////////////////////////////////////////////////////////////////////
//		NORMAL FOOTER
//		-------------
/////////////////////////////////////////////////////////////////////////
$FOOTER = <<<FOOTER
		</table>
		</td>
	</tr>
	<tr>
		<td colspan="3" align="center"><div class="copyright">Copyright&copy; <a href="http://luved.org/">WakScripts</a>, All rights reserved - Magyar felület <a href="http://hd.vilaga.hu/">by Adliz</div></td> 
	</tr>
</table>
</body>
</html>
FOOTER;

$TOP_LOGIN_FORM = <<<TOPLOGINFORM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<title>Belépés az adminfelületre</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<!--Start-->
<table width="250" border="0" align="center">
	<thead>
  		<td colspan="3" class="td">
  		<b>Bejelentkezés</b>
  		</td>
	</thead>

  <tr><form action="$PHP_SELF?action=login" method="post">
  	<td align="right">
		Jelszó: <input class="small" tabindex="1" type="password" name="p" size="9" value="" maxlength="20" />
	</td>
	<td>
		<input class="submit" type="submit" name="submit" value="Belépés" />
		</td>
	</form>
	</tr>
	<tr>
		<td colspan="3" align="center">
TOPLOGINFORM;
/////////////////////////////////////////////////////////////////////////
//		LOGGIN PAGE  - BOTTOM/FOOTER
//		------------------
/////////////////////////////////////////////////////////////////////////
$BOTTOM_LOGIN_FORM = <<<BOTTOMLOGINFORM
		</td>
	</tr>
		<tr>
			<td colspan="3" align="center"><a href="http://luved.org" target="_blank">Powered by WakScripts</a> <br> <a href="http://hd.vilaga.hu" target="_blank">HUN by Adliz</a> </td>
		</tr>
    </td>
  </tr>
</table>
</body>
</html>
BOTTOMLOGINFORM;

$phpSelf = $_SERVER['PHP_SELF'];

function get($data) {
	return explode("\¦", $data);
}

function addRow($db_loc, $rowToAdd) {
	$id = getFileId(DBFILE);
	$break = "";
	if (total($db_loc) != 0) $break = "\r\n";
	$fd = fopen($db_loc, "a+") or die("Can not open file: ".$db_loc);
	$wdata = "$break$id\¦$rowToAdd";
	$fout = fwrite($fd, $wdata);
	if ($fout != strlen($wdata)) {
		echo "File write failed";
		return false;
	}
	fclose($fd);
}

function getFileRow($file) {
	$fd = fopen($file, "r") or die("Can not open file: $file");
	$rstr = fread($fd, filesize($file));
	fclose($fd);
	return explode("\¦", $rstr);
}

function total($db_loc) {
	$db = file($db_loc);
	if (is_array($db))
		return count($db);
	else
		return 1;
}

function getFileId($db_loc) {
	$db = file($db_loc);
	$db = get($db[count($db)-1]);
	return $db[0]+1;
}

function getFileRowById($db_loc, $match_id) {
	$db = file($db_loc);
	foreach ($db as $t) {
		$d = get($t);
		$id = $d[0];
		if ($id == $match_id)
			return $d;
	}
	return false;
}

function replaceRow($db_loc, $matchid, $wdata) {
	$data = "";
	$break = "\r\n";
	$wdata = trim($wdata);
	$dbRows = file($db_loc);
	foreach ($dbRows as $rows) {
		list($id)= get($rows);
		if ($id != $matchid)
			$data .= $break.trim($rows);
		else
			$data .= "$break$wdata";
	}
	$data = trim($data);
	$fd = fopen($db_loc, "w+") or die("Can not open file: ".$db_loc);
	$fout = fwrite($fd, $data);
	fclose($fd);
}

function delete($db_loc, $id) {
	$db = file($db_loc);
	$dbentries = "";
	if (count($db) == 1) {
		$d = getFileRow($db_loc);
		if ($d[0] != $id) {
			$dbentries .= $db[0];
		}
	} else {
		foreach ($db as $t) {
			$d = get($t);
			if ($d[0] != $id) {
				$dbentries .= $t;
			}
		}
	}
	$dbentries = trim($dbentries);
	$fd = fopen($db_loc, "w+") or die("Can not open file: ".$db_loc);
	$fout = fwrite($fd, $dbentries);
	fclose($fd);
}

function dateFormatShort($timestamp) {
	return date('d-m-y', $timestamp);
}

function dateFormatFull($timestamp) {
	return date('d-m-Y', $timestamp) . " " . timeFormat($timestamp);
}

function dateFormat($timestamp) {
	return date('d-m-Y', $timestamp);
}

function timeFormat($timestamp) {
	if (date("H", $timestamp) > 12) {
		$hrampm = date("H", $timestamp) - 12;
		$hrampm = date("$hrampm:i:s", $timestamp) . "pm";
	} else {
		$hrampm = date("H", $timestamp);
		$hrampm = date("$hrampm:i:s", $timestamp). "am";
	}
	return $hrampm;
}
?>