<?php
	class BlogComponent extends Component
	{
		function GetUUIDs()
		{
			$uuids[] = '^blog$';
			$uuids[] = '^blog\/(.*){0,1}$';
			return $uuids;
		}

		function Run( $page, $matches )
		{
			global $frameworks_path;
			require_once( $frameworks_path . '/SafeHtmlChecker.php');
			require_once( $frameworks_path . '/Markdown/markdown_parser.php');

			function _blog_comment_is_safe( $text )
			{
		        	$checker = new SafeHtmlChecker;
		        	$checker->check( '<all>' . $text . '</all>' );
		        	return $checker->isOK();
			}

			$action = isset( $matches[1] ) ? $matches[1] : 'list';

			if( $action == 'list')
			{
				_page_header(SITE_NAME . ' :: Blog');
				
				echo '<a href="/blog/feed/atom" rel="external">&raquo; Get this blog as atom feed</a>' . PHP_EOL;

				$res = get_db_rows( 'SELECT * FROM blog_posts ORDER BY time DESC' );
				while( $tuple = get_db_tuple( $res ) )
				{
					$total = get_db_tuple( get_db_rows( 'SELECT COUNT(*) AS count FROM blog_comments WHERE postid=' . $tuple['id'] ) );
					$hidden = get_db_tuple( get_db_rows( 'SELECT COUNT(*) AS count FROM blog_comments WHERE visible=0 AND postid=' . $tuple['id'] ) );

					echo '<h2><a href="/blog/' . $tuple['id'] . '">' . $tuple['title'] . '</a></h2>' . PHP_EOL . '<blockquote>' . $tuple['post_html'] . '</blockquote>' . PHP_EOL;

					echo '<p style="border-top: 1px #999999 dashed; font-size: 85%; text-align: right;">' . PHP_EOL .
						PHP_TAB . $tuple['author'] . ' / ' . gmdate('M-d-Y H:i:s T', $tuple['time'] ) . ' / <strong>' . $total['count'] . '</strong> comment(s)' .
						( $hidden['count'] ? ' (<strong>' . $hidden['count'] . '</strong> moderated)' : '' ) . ' / <a href="/blog/' . $tuple['id'] . '">Comment</a>' . 
						( _hasflag( FLAG_BLOG ) ? ' / <a href="/admin/blog/edit?r=' . $tuple['id'] . '">Edit blog entry</a>' : '' ) . PHP_EOL .
						'</p>' . PHP_EOL;
				}

				_page_footer();
			}
			else if( $action == 'feed/atom' )
			{
				echo	'<?xml version="1.0" encoding="UTF-8" ?>' . PHP_EOL .
					'<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xml:lang="en" xml:base="http://dronebl.org/blog/">' . PHP_EOL .
					PHP_TAB . '<title type="text">' . SITE_NAME . ' blog</title>' . PHP_EOL .
					PHP_TAB . '<subtitle type="text"></subtitle>' . PHP_EOL .
					PHP_TAB . '<link rel="alternate" type="text/html" href="http://dronebl.org/blog/" />' . PHP_EOL .
					PHP_TAB . '<id>http://dronebl.org/blog/feed/atom</id>' . PHP_EOL .
					PHP_TAB . '<link rel="self" type="application/atom+xml" href="http://dronebl.org/blog/feed/atom" />' . PHP_EOL;
				$res = get_db_rows( 'SELECT * FROM blog_posts ORDER BY time DESC' );
				$latest = true;
				while( $tuple = get_db_tuple( $res ) )
				{
					if( $latest )
					{
						echo PHP_TAB . '<updated>' . gmdate('Y-m-d\TH:i:s\Z', $tuple['time'] ) . '</updated>' . PHP_EOL;
						$latest = false;
					}
					echo	PHP_TAB . '<entry>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<id>http://dronebl.org/blog/' . $tuple['id'] . '</id>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<author>' . PHP_EOL .
						PHP_TAB . PHP_TAB . PHP_TAB . '<name>' . $tuple['author'] . '</name>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '</author>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<title type="text">' . $tuple['title'] . '</title>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<link rel="alternate" type="text/html" href="http://dronebl.org/blog/' . $tuple['id'] . '" />' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<content type="html" xml:base="http://dronebl.org/blog/' . $tuple['id'] . '"><![CDATA[' . $tuple['post_html'] . ']]></content>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<updated>' . gmdate( 'Y-m-d\TH:i:s\Z', $tuple['time'] ) . '</updated>' . PHP_EOL .
						PHP_TAB . PHP_TAB . '<published>' . gmdate( 'Y-m-d\TH:i:s\Z', $tuple['time'] ) . '</published>' . PHP_EOL .
						PHP_TAB . '</entry>' . PHP_EOL;
				}
				echo '</feed>' . PHP_EOL;
			}
			else if( $action == 'comment' )
			{
				if( !_hasflag( FLAG_BLOG ) )
				{
					$reCaptcha = new reCaptcha();
					$captcha = $reCaptcha->verify();
				}

				if( _hasflag(FLAG_BLOG) ||
					(
						
						$captcha &&
						is_numeric( $_REQUEST['postid'] ) && 
						_blog_comment_is_safe( Markdown( $_REQUEST['text'] ) ) &&
						!preg_match( '/([\<])([^\>]{1,})*([\>])/i', $_REQUEST['author'] ) &&
						!_islisted( USERIP )
					)
				)
				{
					_page_header( SITE_NAME . ' :: Blog :: Comment added' );
					$author = db_escape( $_REQUEST['author'] );
					$res = get_db_rows( 'INSERT INTO blog_comments (postid, post, author, time, ip' .
						( _hasflag( FLAG_BLOG ) ? ',visible' : '' ) .
						') VALUES(' .
						$_REQUEST['postid'] . ", '" . db_escape($_REQUEST['text']) . "', '" .
						$author . "', " . time() . ", '" . USERIP . "'" .
						( _hasflag( FLAG_BLOG ) ? ',1' : '' ) .
						');' );
					echo	'<p>Your comment has been added and is pending review by our moderators.</p>' . PHP_EOL .
						'<p><a href="/blog/' . $_REQUEST['postid'] . '">Return to the blog post.</a></p>' . PHP_EOL;
					_page_footer();
				}
				else
				{
					_page_header( SITE_NAME . ' :: Blog :: Comment rejected' );
					echo	'<h2>Comment rejected</h2>' . PHP_EOL . '<p>' .
						( $captcha ?
						'We apologize, but your comment was rejected because it appeared to be an XSS attempt.' :
						'Sorry, but the CAPTCHA challenge you attempted failed.' ) . '</p>' . PHP_EOL .
						'<p>Please correct the errors in your comment and <a href="javascript:history.go(-1);">try again</a>. Thanks!</p>' . PHP_EOL .
						'<p><a href="/blog/' . $_REQUEST['postid'] . '">Return to the blog post.</a></p>' . PHP_EOL;
					_page_footer();
				}
			}
			else if( is_numeric( $action ) )
			{
				if( isset( $_POST['id'] ) && _hasflag( FLAG_BLOG ) )
				{
					if( !isset( $_REQUEST['todo'] ) )
						exit;
						
					$idlist = !is_array( $_POST['id'] ) ? array( $_POST['id'] ) : $_POST['id'];
	
					$tmp = array();
					foreach( $idlist AS $id )
					{
						if( !is_numeric($id) )
							continue;
						$tmp[] = $id;
					}
					$idlist = array_unique( $tmp );
					
					switch( intval( $_REQUEST['todo'] ) )
					{
						case 0:
							$del = get_db_rows( 'DELETE FROM blog_comments WHERE postid=' . $action . ' AND id IN (' . implode( ',', $idlist ) . ')' );
							break;
						case 1:
							$tmp = array();
							$res = get_db_rows( 'SELECT DISTINCT(ip) FROM blog_comments WHERE postid=' . $action . ' AND id IN ('.implode(',',$idlist).')' );
							while( $tuple = get_db_tuple( $res ) )
							{
								$ip = $tuple['ip'];
								if( empty($ip) )
									continue;
								$tmp[] = $ip;
							}
							$iplist = array_unique( $tmp );

							foreach( $iplist AS $ip )
							{
								$res = get_db_rows( 'INSERT INTO blacklist (ip, type, listed, comment, uid_add) '.
										   "VALUES ('" . $ip . "', 6, 1," .
										   "'Spamming " . SITE_NAME . " Blog', '" . $_SESSION['uid'] . "')" );
								_activity_log_add(0, 1, 'IP <strong>' . $ip . '</strong> added as type <strong>6</strong> by <strong>Blog Admin</strong>.' );
								$del = get_db_rows( "DELETE FROM blog_comments WHERE ip='".$ip."'");
							}
							break;
						case 2:
							$res = get_db_rows( 'SELECT id, visible FROM blog_comments WHERE postid=' . $action . ' AND id IN (' . implode( ',', $idlist ) . ')');
							while( $tuple = get_db_tuple( $res ) )
								$upd = get_db_rows( 'UPDATE blog_comments SET visible=' . ( $tuple['visible'] == '1' ? 0 : 1 ) . ' WHERE postid=' . $action . ' AND id=' . $tuple['id'] );
							break;
					}
					exit;
				}

				$tuple = get_db_tuple( get_db_rows( 'SELECT * FROM blog_posts WHERE id=' . $action . ' ORDER BY time DESC' ) );
				$cdata = array();
				$hiddencount = 0;
				$res2 = get_db_rows( 'SELECT * FROM blog_comments WHERE postid=' . $tuple['id'] );
				while( $tuple2 = get_db_tuple( $res2 ) )
				{
					if( !$tuple2['visible'] )
					{
						$hiddencount++;
						if ( !_hasflag( FLAG_BLOG ) )
							continue;
					}
					$cdata[] = $tuple2;
				}

				_page_header( SITE_NAME . ' :: Blog :: ' . $tuple['title'] );
				echo '<h2>' . $tuple['title'] . '</h2>' . PHP_EOL . '<blockquote>' . $tuple['post_html'] . '</blockquote>' . PHP_EOL;
				echo '<p style="border-top: 1px #999999 dashed; font-size: 85%; text-align: right;">' . PHP_EOL . 
					PHP_TAB . $tuple['author'] . ' / ' . gmdate( 'M-d-Y H:i:s T', $tuple['time'] ) . 
					( _hasflag( FLAG_BLOG ) ? ' / <a href="/admin/blog/edit?r=' . $tuple['id'] . '">Edit blog entry</a>' : '' ) .
					PHP_EOL . '</p>' . PHP_EOL .
					'<h3>Comments for ' . $tuple['title'] . '</h3>' . PHP_EOL . '<p>' .
					( count($cdata) ? 'These are the ' . count( $cdata ) . ' (' . $hiddencount . ' hidden) comments for the above post. ' : '' ) .
					'You may add your own comment about the blog entry below! (Removal requests made here are IGNORED as they do not belong here! Contact the maintainer instead.)</p>' . PHP_EOL;

				foreach( $cdata AS $tuple2 )
				{
					echo 	'<div' . ( !$tuple2['visible'] ? ' class="hidden"' : '' ) . '>' . PHP_EOL .
						( _hasflag( FLAG_BLOG ) ? PHP_TAB . '<input type="checkbox" name="id[]" value="' . $tuple2['id'] . '" />' . PHP_EOL : '' ) .
						PHP_TAB . $tuple2['author'] . ' said on ' . gmdate( 'M-d-Y H:i:s T', $tuple2['time'] ) . ' :' . PHP_EOL .
						PHP_TAB . '<blockquote>' . PHP_EOL . PHP_TAB . PHP_TAB . Markdown( nl2br($tuple2['post']) ) . PHP_EOL . PHP_TAB . '</blockquote>' . PHP_EOL . '</div>' . PHP_EOL;
				}

				if( isset( $_SESSION['uid'] ) || !_islisted( USERIP ) )
				{
?>
<h3>Add your own comment</h3>
<form method="post" action="/blog/comment">
	<input type="hidden" name="postid" value="<?= $tuple['id'] ?>" />
	<table>
		<tr>
			<th>Your name</th>
			<td><input type="text" name="author" size="50" value="<?=( isset( $_SESSION['realname'] ) ? $_SESSION['realname'] : '' ) ?>" /></td>
		</tr>
<?php
					if( !isset( $_SESSION['uid'] ) && !_hasflag( FLAG_BLOG ) )
					{
							$captcha = new reCaptcha();
?>
		<tr>
			<th>Captcha</th>
			<td><?= $captcha->create(); ?></td>
		</tr>
<?php
					}
?>
		<tr>
			<th>Your comment</th>
			<td>
				<textarea cols="50" rows="15" name="text"></textarea><br/>
				<span style="font-size: 85%;">You can use <a href="//daringfireball.net/projects/markdown/syntax" rel="external">markdown syntax</a> here for formatting.</span>
			</td>
		</tr>
		<tr>
			<td colspan="2" align="right"><input type="submit" value="Add comment" /></td>
		</tr>
	</table>
</form>
<?php
				}
				_page_footer();
			}
			else
			{
				_page_header( SITE_NAME . ' :: Blog :: Error');
				echo '<p>An unsupported action was requested: <code>' . $action . '</code></p>' . PHP_EOL;
				_page_footer();
			}
		}
	};

	new BlogComponent;
?>
