<?php

function pageHeader() {
	$page_title = TINYIB_PAGETITLE;
	$base_url = getBaseUrl();
	$return = <<<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>{$page_title}</title>
		<base href="{$base_url}" />
		<link rel="shortcut icon" href="favicon.ico" />
		<link rel="stylesheet" type="text/css" href="inc/style.css" />
		<link rel="alternate" type="application/rss+xml" href="rss.php" />
		<meta http-equiv="content-type" content="text/html;charset=UTF-8">
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="expires" content="-1">
	</head>
EOF;
	return $return;
}

function pageFooter() {
	return <<<EOF
	</body>
</html>
EOF;
}

function buildPost($post, $isrespage) {
	$return = "";
	$threadid = ($post['parent'] == 0) ? $post['id'] : $post['parent'];
	$postlink = 'res/' . $threadid . '.html#' . $post['id'];

	if ($post['parent'] == 0 && !$isrespage) {
		$action_message = isLocked($threadid) ? 'R' : 'View or r';
		
		$return .= "<span class=\"replylink\">&nbsp;[<a href=\"res/${post["id"]}.html\">{$action_message}eply to this thread</a>]&nbsp;</span>";
	}
	
	if ($post["parent"] != 0) {
		$return .= <<<EOF
<table>
	<tbody>
		<tr>
			<td class="doubledash">&gt;&gt;</td>
			<td class="reply" id="reply${post["id"]}">
EOF;
	} elseif ($post["file"] != "") {
		$return .= <<<EOF
<span class="filesize">File: <a href="src/${post["file"]}">${post["file"]}</a>&ndash;(${post["file_size_formatted"]}, ${post["image_width"]}x${post["image_height"]}, ${post["file_original"]})</span>
<br>
<a target="_blank" href="src/${post["file"]}">
<span id="thumb${post['id']}"><img src="thumb/${post["thumb"]}" alt="${post["id"]}" class="thumb" width="${post["thumb_width"]}" height="${post["thumb_height"]}"></span>
</a>
EOF;
	}
	
	$return .= <<<EOF
<a name="${post['id']}"></a>
EOF;

	if ($post["subject"] != "") {
		$return .= "	<span class=\"filetitle\">${post["subject"]}</span> ";
	}
	
	$return .= <<<EOF
<a href="imgboard.php?delpost&id={$post['id']}" title="Delete" />X</a>
${post["nameblock"]}
<span class="reflink">
	<a href="$postlink">No.${post["id"]}</a>
</span>
EOF;
	
	
	if ($post['parent'] != 0 && $post["file"] != "") {
		$return .= <<<EOF
<br>
<span class="filesize"><a href="src/${post["file"]}">${post["file"]}</a>&ndash;(${post["file_size_formatted"]}, ${post["image_width"]}x${post["image_height"]}, ${post["file_original"]})</span>
<br>
<a target="_blank" href="src/${post["file"]}">
	<span id="thumb${post["id"]}"><img src="thumb/${post["thumb"]}" alt="${post["id"]}" class="thumb" width="${post["thumb_width"]}" height="${post["thumb_height"]}"></span>
</a>
EOF;
	}

	$return .= <<<EOF
<blockquote>
{$post['message']}
</blockquote>
EOF;

	if ($post['parent'] == 0) {
		if (!$isrespage && $post["omitted"] > 0) {
			$return .= '<span class="omittedposts">' . $post['omitted'] . ' ' . plural("post", $post["omitted"]) . ' omitted. <a href="res/'.$post["id"].'.html">Click here</a> to view.</span>';
		}
	} else {
		$return .= <<<EOF
</td>
</tr>
</tbody>
</table>
EOF;
	}
	
	return $return;
}

function buildPage($htmlposts, $parent, $pages=0, $thispage=0) {
	$locked = ($parent > 0) ? isLocked($parent) : false;
	$postingmode = "";
	$pagenavigator = "";
	if ($parent == 0) {
		$pages = max($pages, 0);
		$previous = ($thispage == 1) ? "index" : 'page/'.($thispage - 1);
		$next = 'page/' . ($thispage+1);
		
		$pagelinks = ($thispage == 0) ? "[ Previous ]" : '[ <a href="' . $previous . '.html">Previous</a> ]';
		
		for ($i = 0;$i <= $pages;$i++) {
			if ($thispage == $i) {
				$pagelinks .= '[ ' . $i . ' ]';
			} else {
				$href = ($i == 0) ? 'index' : 'page/'.$i;
				$pagelinks .= '[ <a href="'. $href . '.html">' . $i . '</a> ]';
			}
		}
		
		$pagelinks .= ($pages <= $thispage) ? "[ Next ]" : '[ <a href="' . $next . '.html">Next</a> ]';
		
		$returnlink = '';
		$pagenavigator = <<<EOF
<div class="pagelinks">
			$pagelinks
</div>
EOF;
	} else {
		$returnlink = '<span class="replylink">[<a href="../">Return</a>]</span>';
		$postingmode = '<div class="replymode">Posting mode: Reply '.($locked ? '(thread locked)' : '').'</div> ';
	}
	
	$unique_posts_html = 'Currently '.countPosts().' posts in '.countThreads().' threads, made by '.uniquePosts().' users.';
	
	$body = <<<EOF
	<body>
		<div class="logo">
EOF;
	$body .= TINYIB_LOGO . <<<EOF
		</div>
		<hr size="1">
		$postingmode
EOF;
	if (! $locked) {
		$body .= <<<EOF
		<div class="postarea">
			<form name="postform" id="postform" action="imgboard.php" method="post" enctype="multipart/form-data">
			
			<input type="hidden" name="parent" value="$parent">
			<table class="postform">
				<tbody>
					<tr>
						<td class="postblock" title="Optional">
							Name
						</td>
						<td>
							<input type="text" name="name" size="28" maxlength="75" accesskey="n">
						</td>
					</tr>
					<tr>
						<td class="postblock" title="Optional">
							E-mail
						</td>
						<td>
							<input type="text" name="email" size="28" maxlength="75" accesskey="e">
						</td>
					</tr>
EOF;

		if (TINYIB_USECAPTCHA) {			
			$captcha_key = md5(mt_rand());
			$captcha_expect = md5(TINYIB_CAPTCHASALT.substr(md5($captcha_key),0,4));
			$body .= <<<EOF
					<tr>
						<td class="postblock" title="Please copy the text to show you're a human.">
							Verification
						</td>
						<td>
							<input type="hidden" name="captcha_ex" value="$captcha_expect" />
							<input type="text" name="captcha_out" size="14" />
							<img src="inc/captcha_png.php?key=$captcha_key" />
						</td>
					</tr>
EOF;
		}
		$display_type = ($parent == 0) ? 'Create Thread' : 'Post reply';
		$body .= <<<EOF
	
					<tr>
						<td class="postblock" title="Optional">
							Subject
						</td>
						<td>
							<input type="text" name="subject" size="40" maxlength="75" accesskey="s">
							<input type="submit" value="{$display_type}" accesskey="z">
						</td>
					</tr>
					<tr>
						<td class="postblock">Message</td>
						<td>
							<textarea name="message" cols="48" rows="4" accesskey="m"></textarea>
						</td>
					</tr>
					<tr>
						<td class="postblock">Image</td>
						<td>
							<input type="file" name="file" size="35" accesskey="f">
						</td>
					</tr>
					<tr>
						<td>&nbsp;</td>
						<td class="rules">
							<ul>
								<li>Images may be GIF, JPG, or PNG up to 2 MB.</li>
								<li>{$unique_posts_html}</li>
							</ul>
						</td>
					</tr>
				</tbody>
			</table>
			</form>
		</div>
		<hr>
EOF;
	}
	$body .= <<<EOF
		$returnlink
		$htmlposts
		<div class="adminbar">
			[<a href="index.html">Home</a> | <a href="imgboard.php?manage">Admin</a>]
		</div>
		$pagenavigator		
		<br>
EOF;

	return pageHeader() . $body . pageFooter();
}

function rebuildIndexes() {	
	$page = 0; $i = 0; $htmlposts = "";
	$pages = ceil(countThreads() / TINYIB_THREADSPERPAGE) - 1;
	$threads = allThreads(); 
	
	foreach ($threads as $thread) {
		$replies = latestRepliesInThreadByID($thread['id']);
		
		$htmlreplies = array();
		foreach ($replies as $reply) {
			$htmlreplies[] = buildPost($reply, False);
		}
		
		$thread["omitted"] = (count($htmlreplies) == 3) ? (count(postsInThreadByID($thread['id'])) - 4) : 0;
		
		$htmlposts .= buildPost($thread, False) . implode("", array_reverse($htmlreplies)) . "<br clear=\"left\">\n<hr>";
		
		$i += 1;
		if ($i == TINYIB_THREADSPERPAGE) {
			$file = ($page == 0) ? "index.html" : 'page/'.$page.".html";
			writePage($file, buildPage($htmlposts, 0, $pages, $page));
			
			$page += 1; $i = 0; $htmlposts = "";
		}
	}
	
	if ($page == 0 || $htmlposts != "") {
		$file = ($page == 0) ? "index.html" : 'page/'.$page . ".html";
		writePage($file, buildPage($htmlposts, 0, $pages, $page));
	}
}

function rebuildThread($id) {
	$htmlposts = "";
	$posts = postsInThreadByID($id);
	foreach ($posts as $post) {
		$htmlposts .= buildPost($post, True);
	}
	
	$htmlposts .= "<br clear=\"left\">\n<hr>";
	
	writePage("res/" . $id . ".html", buildPage($htmlposts, $id));
}

function adminBar() {
	global $loggedin, $isadmin, $returnlink;
	if (!$loggedin) { return '[<a href="' . $returnlink . '">Return</a>]'; }
	$text = '[';
	$text .= ($isadmin) ? '<a href="imgboard.php?manage&bans">Bans</a>] [' : '';
	$text .= '<a href="imgboard.php?manage&moderate">Moderate Post</a>] [<a href="imgboard.php?manage&modpost">Mod Post</a>] [';
	$text .= ($isadmin) ? '<a href="imgboard.php?manage&rebuildall">Rebuild All</a>] [' : '';
	$text .= '<a href="imgboard.php?manage&logout">Log Out</a>] [<a href="' . $returnlink . '">Return</a>]';
	return $text;
}

function managePage($text, $onload='') {
	$adminbar = adminBar();
	$body = <<<EOF
	<body$onload>
		<div class="adminbar">
			$adminbar
		</div>
		<div class="logo">
EOF;
	$body .= TINYIB_LOGO . <<<EOF
		</div>
		<hr width="90%" size="1">
		<div class="replymode">Manage mode</div>
		$text
		<hr>
EOF;
	return pageHeader() . $body . pageFooter();
}

function manageOnLoad($page) {
	switch ($page) {
		case 'login':
			return ' onload="document.tinyib.password.focus();"';
		case 'moderate':
			return ' onload="document.tinyib.moderate.focus();"';
		case 'modpost':
			return ' onload="document.tinyib.message.focus();"';
		case 'bans':
			return ' onload="document.tinyib.ip.focus();"';
	}
}

function manageLogInForm() {
	return <<<EOF
	<form id="tinyib" name="tinyib" method="post" action="imgboard.php?manage">
		<fieldset>
			<legend align="center">Please enter an administrator or moderator password</legend>
			<div class="login">
				<input type="password" id="password" name="password"><br>
				<input type="submit" value="Submit" class="managebutton">
			</div>
		</fieldset>
	</form>
	<br/>
EOF;
}

function manageBanForm() {
	return <<<EOF
	<form id="tinyib" name="tinyib" method="post" action="imgboard.php?manage&bans">
		<fieldset>
			<legend>Ban an IP address from posting</legend>
			<label for="ip">IP Address:</label>
			<input type="text" name="ip" id="ip" value="${_GET['bans']}">
			<input type="submit" value="Submit" class="managebutton">
			<br/>
			<label for="expire">Expire(sec):</label>
			<input type="text" name="expire" id="expire" value="0">&nbsp;&nbsp;<small><a href="#" onclick="document.tinyib.expire.value='3600';return false;">1hr</a>&nbsp;<a href="#" onclick="document.tinyib.expire.value='86400';return false;">1d</a>&nbsp;<a href="#" onclick="document.tinyib.expire.value='172800';return false;">2d</a>&nbsp;<a href="#" onclick="document.tinyib.expire.value='604800';return false;">1w</a>&nbsp;<a href="#" onclick="document.tinyib.expire.value='1209600';return false;">2w</a>&nbsp;<a href="#" onclick="document.tinyib.expire.value='2592000';return false;">30d</a>&nbsp;<a href="#" onclick="document.tinyib.expire.value='0';return false;">never</a></small>
			<br/>
			<label for="reason">Reason:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
			<input type="text" name="reason" id="reason">&nbsp;&nbsp;<small>(optional)</small>
		</fieldset>
	</form>
	<br/>
EOF;
}

function manageBansTable() {
	$text = '';
	$allbans = allBans();
	if (count($allbans) > 0) {
		$text .= '<table border="1"><tr><th>IP Address</th><th>Set At</th><th>Expires</th><th>Reason Provided</th><th>&nbsp;</th></tr>';
		foreach ($allbans as $ban) {
			$expire = ($ban['expire'] > 0) ? date('y/m/d(D)H:i:s', $ban['expire']) : 'Never';
			$reason = ($ban['reason'] == '') ? '&nbsp;' : htmlentities($ban['reason']);
			$text .= '<tr><td>' . $ban['ip'] . '</td><td>' . date('y/m/d(D)H:i:s', $ban['timestamp']) . '</td><td>' . $expire . '</td><td>' . $reason . '</td><td><a href="?manage&bans&lift=' . $ban['id'] . '">lift</a></td></tr>';
		}
		$text .= '</table>';
	}
	return $text;
}

function manageModeratePostForm() {
	return <<<EOF
	<form id="tinyib" name="tinyib" method="get" action="imgboard.php?">
		<input type="hidden" name="manage" value="">
		<fieldset>
			<legend>Moderate a post</legend>
			<label for="moderate">Post ID:</label>
			<input type="text" name="moderate" id="moderate">
			<input type="submit" value="Submit" class="managebutton">
			<br/>
		</fieldset>
	</form>
	<br/>
EOF;
}

function manageModpostForm() {
	return <<<EOF
	<div class="postarea">
		<form id="tinyib" name="tinyib" method="post" action="imgboard.php?" enctype="multipart/form-data">
		<input type="hidden" name="modpost" value="1">
		<input type="hidden" name="MAX_FILE_SIZE" value="2097152">
		<table class="postform">
			<tbody>
				<tr>
					<td class="postblock">
						Thread No.
					</td>
					<td>
						<input type="text" name="parent" size="28" maxlength="75" value="0" accesskey="t">&nbsp;(0 for new thread)
					</td>
				</tr>
				<tr>
					<td class="postblock">
						Name
					</td>
					<td>
						<input type="text" name="name" size="28" maxlength="75" accesskey="n">
					</td>
				</tr>
				<tr>
					<td class="postblock">
						E-mail
					</td>
					<td>
						<input type="text" name="email" size="28" maxlength="75" accesskey="e">
					</td>
				</tr>
				<tr>
					<td class="postblock">
						Subject
					</td>
					<td>
						<input type="text" name="subject" size="40" maxlength="75" accesskey="s">
						<input type="submit" value="Submit Modpost" accesskey="z">
					</td>
				</tr>
				<tr>
					<td class="postblock">
						Message
					</td>
					<td>
						<textarea name="message" cols="48" rows="4" accesskey="m"></textarea>
					</td>
				</tr>
				<tr>
					<td class="postblock">
						File
					</td>
					<td>
						<input type="file" name="file" size="35" accesskey="f">
					</td>
				</tr>
				<tr>
					<td class="postblock">
						Password
					</td>
					<td>
						<input type="password" name="password" size="8" accesskey="p">&nbsp;(for post and file deletion)
					</td>
				</tr>
				<tr>
					<td>
						&nbsp;
					</td>
					<td class="rules">
						<ul>
							<li>All text entered in the "Message" field will be posted AS-IS with absolutely no formatting applied.</li>
							<li>This means for all line-breaks you must enter the text "&lt;br&gt;".</li>
						</ul>
					</td>
				</tr>
			</tbody>
		</table>
		</form>
	</div>
EOF;
}

function manageModeratePost($post) {
	global $isadmin;
	$ban = banByIP($post['ip']);
	$ban_disabled = (!$ban && $isadmin) ? '' : ' disabled';
	$ban_disabled_info = (!$ban) ? '' : (' A ban record already exists for ' . $post['ip']);
	$post_html = buildPost($post, true);
	$post_or_thread = ($post['parent'] == 0) ? 'Thread' : 'Post';
	return <<<EOF
	<fieldset>
		<legend>Moderating post No.${post['id']}</legend>		
		<div class="floatpost">
			<fieldset>
				<legend>$post_or_thread</legend>	
				$post_html
			</fieldset>
		</div>		
		<fieldset>
			<legend>Action</legend>					
			<form method="get" action="imgboard.php?">
				<input type="hidden" name="manage" value="" />
				<input type="hidden" name="delete" value="${post['id']}" />
				<input type="submit" value="Delete $post_or_thread" class="managebutton" />
			</form>
			<br/>
			<form method="get" action="imgboard.php?">
				<input type="hidden" name="manage" value="" />
				<input type="hidden" name="bans" value="${post['ip']}" />
				<input type="submit" value="Ban Poster" class="managebutton"$ban_disabled />$ban_disabled_info
			</form>
		</fieldset>	
	</fieldset>
	<br />
EOF;
}

