<?php
error_reporting 
E_ALL );

define "SITE_URI""http://phpgsy.com/1000lines/" );
define "HTACCESS"true );
define "SCRIPT_NAME"basename(__FILE__) );

define "DB_HOST""localhost" );
define "DB_USER""mozzer_1000" );
define "DB_PASS""********" );
define "DB_NAME""mozzer_1000" );

define "TBL_NEWS""blog" );
define "TBL_USERS""users" );
define "TBL_COMMENTS""comments" );

define "NEWS_ITEMS"10 );

define "RSS"'<?xml version="1.0"?>{n}<rss version="2.0">{n}{t}<channel>{n}{t}{t}<title>1000 Lines Blog</title>{n}{t}{t}<link>{site}</link>{n}{t}{t}<description>Liftoff to Space Exploration.</description>{n}{t}{t}<language>en-us</language>{n}{t}{t}<docs>http://blogs.law.harvard.edu/tech/rss</docs>{n}{t}{t}<generator>1000 Lines</generator>{n}{content}{n}{t}</channel>{n}</rss>' );
define "CSS"'N;' );
define "HTML"'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">{n}<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">{n}{t}<head>{n}{t}{t}{headers}{n}{t}</head>{n}{t}<body>{n}{t}{t}<div id="wrapper" >{n}{t}{t}{t}<div id="header">{n}{t}{t}{t}{t}<h1>{header}</h1>{n}{t}{t}{t}</div>{n}{t}{t}{t}<div id="navigation">{n}{t}{t}{t}{t}{nav}{n}{t}{t}{t}</div>{n}{t}{t}{t}<div id="maincontent">{n}{t}{t}{t}{t}{main}{n}{t}{t}{t}</div>{n}{t}{t}{t}<div id="footer">{n}{t}{t}{t}{t}{footer}{n}{t}{t}{t}</div>{n}{t}{t}</div>{n}{t}</body>{n}</html>' );
define "ACTIONS"'a:14:{s:4:"home";s:8:"showNews";s:4:"blog";s:8:"showBlog";s:7:"publish";s:11:"showPublish";s:6:"delete";s:10:"deleteBlog";s:4:"edit";s:8:"showEdit";s:4:"list";s:12:"listArticles";s:5:"login";s:9:"showLogin";s:3:"css";s:7:"showCSS";s:7:"editcss";s:7:"editCSS";s:3:"rss";s:7:"showRSS";s:2:"js";s:6:"showJS";s:6:"logout";s:10:"showLogout";s:7:"actions";s:11:"editActions";s:8:"edithtml";s:8:"editHTML";}' );
// Classes

class blog extends template
{
    var 
$action;
    var 
$arrayActions = array ();

    function 
blog ( )
    {
        
$this->{get_parent_class(__CLASS__)}();
        
$this->arrayActions unserialize ACTIONS );
        
$this->action         = isset ( $_GET['action'] ) && !is_array $_GET['action'] ) && isset ( $this->arrayActions[$_GET['action']] ) ? strtolower $_GET['action'] ) : 'home';
        
$this->request    = isset ( $_GET['request'] ) ? true false;
        
        
$this->request  = isset ( $_GET['ajax'] ) ? true false;
        
$this->{$this->arrayActions[$this->action]}();
        echo 
$this->parsePage();
    }

    function 
showNews $rss false )
    {
        
$data $this->getNews();
        while ( 
$array mysql_fetch_assoc $data ) )
            
$this->addNewsItem $array['title'], $array['post'], $array['tags'], $array['timestamp'], $rss );
    }
    
    function 
showRSS ( )
    {
        
$this->request true;
        
$this->showRSSHeader ( );
        
$this->showNews true );
        
$this->showRSSFooter ( );
    }
    
    function 
updateMySQL ( )
    {
        foreach ( 
$_POST as $key => $value )
            $
$key trim $value );
        
$data file_get_contents __FILE__ );
        
$data preg_replace "/define \( \"DB_HOST\", \"(.+)\" \);/""define ( \"DB_HOST\", \"{$host}\" );"$data );
        
$data preg_replace "/define \( \"DB_USER\", \"(.+)\" \);/""define ( \"DB_USER\", \"{$user}\" );"$data );
        
$data preg_replace "/define \( \"DB_PASS\", \"(.+)\" \);/""define ( \"DB_PASS\", \"{$password}\" );"$data );
        
$data preg_replace "/define \( \"DB_NAME\", \"(.+)\" \);/""define ( \"DB_NAME\", \"{$name}\" );"$data );
        
fwrite fopen __FILE__"w" ), $data );
        return 
true;
    }
    
    function 
createHTACCESS ( )
    {
        if ( 
is_writable ".htaccess" ) || !file_exists ".htaccess" ) )
        {
            
$data "RewriteEngine On\n";
            foreach ( 
$this->arrayActions as $url )
                
$data .= "RewriteRule ^{$url}/? ".SCRIPT_NAME."?action={$url} [PT]\n";
            
$arrayExtras = array (
                
'^blog/([A-Za-z0-9_\-\.!+]+)/?$'            => '?action=blog&post=$1',
                
'^edit/([A-Za-z0-9_\-\.!+]+)/?$'            => 'blog.php?action=edit&post=$1',
                
'^delete/([A-Za-z0-9_\-\.!+]+)/?$'        => 'blog.php?action=delete&post=$1',
                
'^delete/([A-Za-z0-9_\-\.!+]+)/ajax/?$'    => 'blog.php?action=delete&post=$1&ajax', );
            foreach ( 
$arrayExtras as $regex => $location )
                
$data .= "RewriteRule {$regex} ".SCRIPT_NAME."{$location} [PT]\n";
            return 
$data;
        } else
            return 
false;
    }
    
    function 
install ( )
    {
        if ( !
$this->connection )
        {
            
$formData = array (
                
"host"     => array ( 
                    
"name"     => "host",
                    
"title"    => "Host",
                    
"type"    => "text",
                    
"check"    => "post" ),
                
"user"    => array (
                    
"name"    => "user",
                    
"title"    => "Username",
                    
"type"    => "text",
                    
"check"    => "post" ),
                
"password"    => array (
                    
"name"    => "password",
                    
"title"    => "Password",
                    
"type"    => "text",
                    
"check"    => "post" ),
                
"name"    => array (
                    
"name"    => "dbname",
                    
"title"    => "Database",
                    
"type"    => "text",
                    
"check"    => "post" ),
                );
            
$formAction "?action=install";
            if ( isset ( 
$_POST['title'] ) )
            {
                
$this->initForm "MySQL Details"$formData"updateMySQL"true );
                
$this->main .= ( $this->showForm($formAction));
            } else {
                
$this->initForm "MySQL Details"$formData "updateMySQL" );
                
$this->main .= ( $this->showForm($formAction));
            }
            break 
2;
        }
        
$generateBlog $this->query (
        
"CREATE TABLE IF NOT EXISTS `".TBL_NEWS."` (
          `postid` int(11) NOT NULL auto_increment,
          `userid` int(11) NOT NULL,
          `title` varchar(100) NOT NULL,
          `post` text NOT NULL,
          `tags` text NOT NULL,
          `timestamp` int(11) NOT NULL,
          PRIMARY KEY  (`postid`)
        )" 
);
        
$generateComment $this->query (
        
"CREATE TABLE IF NOT EXISTS `".TBL_COMMENTS."` (
          `commentid` int(11) NOT NULL auto_increment,
          `blogid` int(11) NOT NULL,
          `name` varchar(100) NOT NULL,
          `comment` text NOT NULL,
          `email` varchar(100) NOT NULL,
          `remote_addr` varchar(15) NOT NULL,
          `url` varchar(100) NOT NULL,
          PRIMARY KEY  (`commentid`)
        )" 
);
        
$generateUsers $this->query (
        
"CREATE TABLE IF NOT EXISTS `".TBL_USERS."` (
          `userid` int(11) NOT NULL auto_increment,
          `username` varchar(50) NOT NULL,
          `password` varchar(32) NOT NULL,
          `sessid` varchar(32) NOT NULL,
          `userlevel` tinyint(4) NOT NULL,
          `email` varchar(50) NOT NULL,
          `timestamp` int(11) NOT NULL,
          PRIMARY KEY  (`userid`)
        )" 
);
    }
    
    function 
showBlog ( )
    {
        if ( !isset ( 
$_GET['post'] ) || is_array $_GET['post'] ) )
            return 
$this->showNews ( );
        
        
$sql $this->getBlog $_GET['post'] );
        
$array mysql_fetch_assoc $sql );
        
$this->addNewsItem $array['title'], $array['post'], $array['tags'], $array['timestamp'] );
        
$this->showComments ( );
    }
    
    function 
showPublish ( )
    {
        
$this->main .= ( "<h2>Post</h2>" );
        if ( 
ADMIN )
        {
            
$formData = array (
                
"title"     => array ( 
                    
"name"     => "title",
                    
"title"    => "Title",
                    
"type"    => "text",
                    
"check"    => "title" ),
                
"post"    => array (
                    
"name"    => "post",
                    
"title"    => "Post",
                    
"type"    => "textarea",
                    
"style"    => "post",
                    
"check"    => "post" ),
                
"tags"    => array (
                    
"name"    => "tags",
                    
"title"    => "Tags",
                    
"type"    => "text",
                    
"check"    => "tags" ),
                );
            
$formAction HTACCESS "publish" SCRIPT_NAME ."?action=publish";
            if ( isset ( 
$_POST['title'] ) )
            {
                
$this->initForm "Publish Blog"$formData"post"true );
                
$this->main .= ( $this->showForm($formAction));
            } else {
                
$this->initForm "Publish Blog"$formData "post" );
                
$this->main .= ( $this->showForm($formAction));
            }
        } else
            
$this->showForm();
    }
    
    function 
editCSS ( )
    {
        
$this->editCons "CSS" );
    }
    
    function 
editHTML ( )
    {
        
$this->editCons "HTML" );
    }
    
    function 
editActions ( )
    {
        
$this->editCons "ACTIONS" );
    }
    
    function 
editCons $constant )
    {
        
$this->main .= ( "<h2>Edit {$constant}</h2>" );
        if ( 
ADMIN )
        {
            
$formData = array (
                
$constant    => array (
                    
"name"    => strtolower $constant ),
                    
"title"    => $constant,
                    
"type"    => "textarea",
                    
"style"    => "constantedit",
                    
"check"    => "post" ),
                );
            
$preset[strtolower($constant)] = $this->{"clean".$constant} ( constant ($constant) );
            if ( isset ( 
$_POST[strtolower $constant )] ) )
            {
                
$this->initForm "Edit {$constant}"$formData"update{$constant}"true );
                
$this->main .= ( $this->showForm(''));
            } else {
                
$this->initForm "Edit {$constant}"$formData "update{$constant}"false$preset );
                
$this->main .= ( $this->showForm(''));
            }
        } else
            
$this->showLogin();
    }
    
    function 
updateCons $constant$newval )
    {
        
$currentFile file_get_contents __FILE__ );
        
$newval str_replace "'""\'"$newval );
        
$newFile preg_replace "/define \( \"{$constant}\", '(.+)' \);/""define ( \"{$constant}\", '{$newval}' );"$currentFile );
        
fwrite fopen __FILE__"w" ), $newFile );
        return 
true;
    }
    
    function 
updateHTML ( )
    {
        
$html $this->cleanHTML $_POST['html'], true );
        return 
$this->updateCons "HTML"$html );
    }
    
    function 
updateCSS ( )
    {
        
$style $this->css2serial $_POST['css'] );
        return 
$this->updateCons "CSS"$style );
    }
    
    function 
updateActions ( )
    {
        
$action $this->action2serial $_POST['actions'] );
        return 
$this->updateCons "ACTIONS"$action );
    }
    
    function 
css2serial $css )
    {
        
$data explode "}"$css );
        foreach ( 
$data as $item )
        {
            
$d explode "{"$item );
            
$title trim($d[0]);
            if ( 
count $d ) == )
                
$items explode ";"$d[1] );
            else
                break 
1;
            foreach ( 
$items as $item )
            {
                
$parts explode ":"$item);
                if ( 
count $parts ) == )
                    
$cssArr[$title][trim($parts[0])] = trim($parts[1]);
            }
        }
        return 
serialize $cssArr );
    }
    
    function 
action2serial $actions )
    {
        
$data explode "\n"$actions );
        foreach ( 
$data as $part 
        {
            
$d explode ":"$part );
            if ( 
count $d ) == )
                
$return[trim($d[0])] = trim $d[1] );
        }
        return 
serialize $return );
    }
    
    function 
deleteBlog ( )
    {
        if ( !isset ( 
$_GET['post'] ) || is_array $_GET['post'] ) )
            return 
$this->listArticles ( );
        
        if ( isset ( 
$_GET['confirm'] ) )
            
$this->delete();
        else
            
$this->main "<script>q('".urlencode $_GET['post'] )."');</script><noscript><a href='" SITE_URI SCRIPT_NAME "?action=delete&post="urlencode $_GET['post'] )."&confirm'>Delete Post</a></noscript>";
    }

    function 
showEdit ( )
    {
        if ( !isset ( 
$_GET['post'] ) || is_array $_GET['post'] ) )
            return 
$this->listArticles ( );
        
        
$this->main .= ( "<h2>Edit</h2>" );
        if ( 
ADMIN )
        {
            
$formData = array (
                
"title"     => array ( 
                    
"name"     => "title",
                    
"title"    => "Title",
                    
"type"    => "text",
                    
"check"    => "title" ),
                
"post"    => array (
                    
"name"    => "post",
                    
"title"    => "Post",
                    
"type"    => "textarea",
                    
"style"    => "post",
                    
"check"    => "post" ),
                
"tags"    => array (
                    
"name"    => "tags",
                    
"title"    => "Tags",
                    
"type"    => "text",
                    
"check"    => "tags" ),
                );
            
$formAction "";
            if ( isset ( 
$_POST['title'] ) )
            {
                
$this->initForm "Modify Blog"$formData"edit"true );
                
$this->main .= ( $this->showForm($formAction));
            } else {
                
$this->initForm "Modify Blog"$formData "edit"falsemysql_fetch_assoc $this->getBlog $_GET['post'] ) ) );
                
$this->main .= ( $this->showForm($formAction));
            }
        } else
            
$this->showForm();
    }

    function 
showLogin ( )
    {
        
$this->main .= ( "<h2>Login</h2>" );
        if ( !
ADMIN )
        {
            
$formData = array (
                
"username"     => array ( 
                    
"name"     => "username",
                    
"title"    => "Username",
                    
"type"    => "text",
                    
"check"    => "text" ),
                
"password"    => array (
                    
"name"    => "password",
                    
"title"    => "Password",
                    
"type"    => "password",
                    
"check"    => "text" )
                );
            if ( isset ( 
$_POST['username'] ) )
            {
                
$this->initForm "Login"$formData"login"true );
                
$this->main .= ( $this->showFormSCRIPT_NAME "?action=login" ) );
            } else {
                
$this->initForm "Login"$formData "login" );
                
$this->main .= ( $this->showFormSCRIPT_NAME "?action=login" ) );
            }
        } else
            
$this->addContent "You are already logged in" );
    }
    
    function 
showComments ( )
    {
        
$comments $this->getComments $_GET['post'] );
        while ( 
$array mysql_fetch_assoc $comments ) )
            
$this->addComment $array['name'], $array['comment'], $array['url'] );
        
$formData = array (
            
"name" => array (
                
"name"    => "name",
                
"title"        => "Name",
                
"type"    => "text",
                
"check"    => "text",),
            
"comment" => array (
                
"name"    => "comment",
                
"title"    => "Comment",
                
"type"    => "textarea",
                
"style"    => "commentarea",
                
"check"    => "post",),
            
"url" => array (
                
"name"    => "url",
                
"title"        => "Site",
                
"type"    => "text",
                
"check"    => "url",),
        );
        if ( isset ( 
$_POST['name'] ) )
        {
            
$this->initForm "Post a Comment"$formData"comment"true );
            
$this->main .= ( $this->showForm "" ) );
        } else {
            
$this->initForm "Post a Comment"$formData"comment" );
            
$this->main .= ( $this->showForm "" ) );
        }
    }
    
    function 
showLogout ( )
    {
        
setcookie "userid"""$this->time-1000 );
        
header "Location: {$_SERVER['HTTP_REFERER']}" );
    }
    
    function 
listArticles ( )
    {
        
$data $this->getBlogs ( );
        while ( 
$array mysql_fetch_assoc $data ) )
            
$this->addBlog $array['title'], $array['post'], $array['tags'], $array['timestamp'] );
    }
    
};
$blog = new blog();

class 
mysql
{

    var 
$connection;
    var 
$queries 0;
    
    function 
mysql ( )
    {
        
$this->connection mysql_connect DB_HOSTDB_USERDB_PASS );
        if ( !
$this->connection )
            if ( 
$_GET['action'] != "install" )
                die ( 
"MySQL Connection failed" );
        
        if ( !
mysql_select_db DB_NAME$this->connection ) )
            if ( 
$_GET['action'] != "install" )
                die ( 
"No database found: " DB_NAME);
        
        return 
true;
    }
    
    function 
query $query )
    {
        ++
$this->queries;
        return 
mysql_query $query$this->connection );
    }
    
};

class 
setQueries extends mysql
{
    
    function 
setQueries ( )
    {
        
$this->{get_parent_class(__CLASS__)}();
    }
    
    function 
checkUserID $username$userid )
    {
        
$result $this->getUserField "sessid"$username );
        if ( 
$result === false )
            return 
false;        
        
        return ( 
$userid === $result ) ? true false;
    }
    
    function 
getBlogs ( )
    {
        return 
$this->query "SELECT * FROM ".TBL_NEWS." ORDER BY `timestamp` DESC" );
    }
    
    function 
getBlog $title )
    {
        return 
$this->query "SELECT * FROM ".TBL_NEWS." WHERE title = '".$this->mres($title)."' LIMIT 0,1" );
    }
    
    function 
getComments $title )
    {
        return 
$this->query "SELECT ".TBL_COMMENTS.".* 
            FROM "
.TBL_COMMENTS.", ".TBL_NEWS."
            WHERE "
.TBL_COMMENTS.".blogid = ".TBL_NEWS.".postid
            AND title = '"
.$this->mres($title)."'");
    }
    
    function 
comment ( )
    {
        if ( 
$this->query "INSERT INTO `".TBL_COMMENTS."` (`blogid`, `name`, `comment`, `url`, `remote_addr`,`timestamp` ) VALUES (".$this->getArticleID$_GET['post'] ).",    '".$this->mres($_POST['name'])."',     '".$this->mres($_POST['comment'])."', '".$this->mres($_POST['url'])."', '".$this->mres($_SERVER['REMOTE_ADDR'])."', ".$this->time.")" ) )
        {
            
$this->addContent "Comment Added" );
            return 
$this->addRedirect ""1000 );
        } else
            return 
false;
    }
    
    function 
getNews ( )
    {
        return 
$this->query "SELECT * FROM  ".TBL_NEWS." ORDER BY `timestamp` DESC LIMIT 0,10" );
    }
    
    function 
getArticleID $title )
    {
        return 
mysql_result (  $this->query "SELECT `postid` FROM ".TBL_NEWS." WHERE `title` = '".$this->mres $title )."'" ), );
    }
    
    function 
getUserData $username )
    {
        
$query "SELECT * FROM `".TBL_USERS."` WHERE `username` = '".$this->mres($username)."' LIMIT 0,1";
        
$result $this->query $query );
        
$this->userdata mysql_fetch_assoc $result );
        return 
true;
    }

    function 
getUserField $field$username )
    {
        
$query $this->query "SELECT `".$field."` FROM `".TBL_USERS."` WHERE `username` = '".$this->mres($username)."' LIMIT 0,1" );
        return 
mysql_num_rows $query ) == mysql_result $query) : false;
    }
    
    function 
updateSessID $username$ui )
    {
        return 
$this->query "UPDATE `".TBL_USERS."` SET `sessid` = '{$ui}' WHERE `username` = '".$this->mres($username)."'");
    }
    
    function 
post ( )
    {
        if ( 
$this->query "INSERT INTO `".TBL_NEWS."` (`userid`, `title`, `post`, `tags`, `timestamp` ) VALUES (".$this->userdata['userid'].", '".$this->mres($_POST['title'])."', '".$this->mres($_POST['post'])."', '".$this->mres($_POST['tags'])."', ".$this->time.")" ) )
            return 
$this->addContent "Post Added" );
        else
            return 
false;
    }
    
    function 
edit ( )
    {
        if ( 
$this->query "UPDATE `".TBL_NEWS."` 
            SET`title` = '"
.$this->mres($_POST['title'])."',
             `post` = '"
.$this->mres($_POST['post'])."',
             `tags` = '"
.$this->mres($_POST['tags'])."'
            WHERE `title` = '"
.$this->mres($_GET['post'])."'" ) )
            return 
$this->addContent "Post Updated" );
        else
            return 
false;
    }
    
    function 
delete ( )
    {
        
$data $this->query "DELETE FROM `".TBL_NEWS."` WHERE `title` = '".$this->mres $_GET['post'] )."'" ) ? "Post Deleted" "Delete failed";
        
$this->addContent $data );
    }
    
};

class 
security extends setQueries
{
    function 
security ( )
    {
        
$this->{get_parent_class(__CLASS__)}();
        foreach ( 
$_POST as $key => $data )
        {
            if ( 
html_entity_decode $_POST[$key] ) !== $_POST[$key] )
                
$_POST[$key] = html_entity_decode $_POST[$key] );
            if (
get_magic_quotes_gpc()) 
                
$_POST[$key] = stripslashes($_POST[$key]);
        }
    }
    
    function 
mres $string )
    {
        return 
mysql_real_escape_string $string );
    }
    
    function 
dbout $string )
    {
        return 
htmlspecialchars $string );
    }
    
    function 
fingerPrint() 
    {
        
$x 0;
        while(
$x 8) {
            
$s[] =  chr(rand(0,256));
            ++
$x;
        }
        return 
md5 (  implode ""$s ) );
    }
};

class 
session extends security
{
    
    var 
$time;
    var 
$loggedin true;
    var 
$userdata = array();
    
    function 
session ()
    {
        
$this->{get_parent_class(__CLASS__)}();
        
$this->time time();
        
        
$this