<?php


/*
ScreevoCMS v1.2
August 24, 2006

Author: Stephen Martin - stephen@screevo.com
---------------------------
A simple content management system for reading,
writing, and creating content in an SQL database to
be used in an easily managed webpage.

Pages are stored in a table called 'pages'.
Users who are allowed to edit content are
stored in a table called 'users'.

The authorization functions authenticateUser() and
checkUser() rely on hooks that are not usable when
running PHP as CGI. Thus, you must be running mod_php under
Apache for this to function properly.

The header and footers in which the content is wrapped
are set by the constants HEADER and FOOTER at the
beginning of the file and must be the absolute
file location, relative to /, and not to your domain name.
Also set will be the SQL Server (SQLSERVER), the SQL user
(SQLUSER), the SQL password (SQLPASSWORD). and the database
in which the information is stored (SQLDB)

The variable 'carat' is set while in the administration
panel to direct the CMS to the right administrative function.

The next release will allow pages to be reordered, and
previewed before posting.
*/

//====== CONSTANTS ======//
define("HEADER", "Location of Header");
define("FOOTER", "Location of Footer");
define("SQLSERVER", "MySQL Database Location");
define("SQLUSER", "MySQL Username");
define("SQLPASSWORD", "MySQL Password");
define("SQLDB", "MySQL Database");
//========================//



//====== FUNCTIONS =======//
//Opens Database Connection
function openDatabaseScreevo() {
        mysql_connect(SQLSERVER, SQLUSER, SQLPASSWORD) or die("Can not connect to DB server.");
        mysql_select_db(SQLDB) or die("Can not connect to database.");
}
//End Function


//Prompts User for Credentials
function authenticateUser() {
        header('WWW-Authenticate: Basic realm="Private"');
        header("HTTP/1.0 401 Unauthorized");
        echo 'Invalid username and password. lol h4xx0rz roflcopter.';
        exit;
}
//End Function


//Checks Credentials against Database
function checkUser() {
        if (!isset ($_SERVER['PHP_AUTH_USER'])) {
                authenticateUser();
        } else {
                openDatabaseScreevo();
                $user = mysql_real_escape_string($_SERVER['PHP_AUTH_USER']);
                $pass = md5(mysql_real_escape_string($_SERVER['PHP_AUTH_PW']));
                $query = "SELECT username,pswd FROM users
                                                                                    WHERE username='$user' AND
                                                                                    pswd='$pass'";

                $result = mysql_query($query);
                if (mysql_num_rows($result) == 0) {
                        authenticateUser();
                }
        }
}
//End Function

//Gathers links for use in the includes. Modify the echo statement to reflect how you want the links displayed.
function screevoLinks() {
    openDatabaseScreevo();
    $query = "SELECT link AS link, linkimage AS linkimage, title AS title FROM pages WHERE id > 0 ORDER BY id ASC";
    $result = mysql_query($query);

    $num_rows = mysql_num_rows($result);

    while ($row = mysql_fetch_array($result)) {
        $link = $row["link"];
        $linkimage = $row["linkimage"];
        $title = $row["title"];
        echo '<img src="/siteimages/spacer.gif" alt=" "><a href="'.$link.'"><img src="'.$linkimage.'" alt="'.$title.'" border="0"></a><br>';
    }
}
//End Function

//Admin Panel Default Page - Carat is blank
function screevoStart() {
        echo '<h2>Content Management System</h2>';
        echo '<form action="/?id=admin" method="post">';
        echo '<input type="radio" name="carat" value="update">Update Existing Page<br>';
        echo '<input type="radio" name="carat" value="new">Create New Page<br>';
        echo '<input type="radio" name="carat" value="delete">Delete a Page<br><br>';
        echo '<input type="submit" value="Go">';
        echo '</form>';
} //End function




//Create New Page - Carat = "new"
function screevoNew() {
    echo 'Content Creator<br><br>';
    echo '<form action="/?id=admin" method="post">';
    echo '<input type="text" name="id" size="4" value="id">';
    echo '<input type="text" name="title" size="20" value="title"><br>';
    echo '<input type="text" name="link" size="5" value="/?id=">';
    echo '<input type="text" name="linkimage" size="30" value="/siteimages/image.jpg"><br>';
    echo '<textarea id="content" name="content" rows="50" cols="50">';
    echo 'The content of your new page goes here. HTML is allowed. PHP is not.';
    echo '</textarea>';
    echo '<input type="hidden" name="carat" value="preview">';
    echo '<input type="submit" value="Preview New Page"> </p> </form> <br>';
} 
// End Function

//Update Existing Page - Carat = "update"
function screevoUpdate() {
        openDatabaseScreevo();

        if (!$_POST["id"]) {
                $query = "SELECT id AS id, title AS title FROM pages WHERE id > '0' ORDER by id ASC";
                $result = mysql_query($query);


                echo 'Content Updater<br><form action="/?id=admin" method="post">';

                $num_rows = mysql_num_rows($result);

                while ($row = mysql_fetch_array($result)) {
                        $id = $row["id"];
                        $title = $row["title"];
                        echo '<input type="radio" name="id" value="' . $id . '">' . $id . ' - ' . $title . '<br>';
                }

                echo '<input type="hidden" name="carat" value="update"><br>';
                echo '<input type="submit" value="Edit selected page."></p></form>';
        } else {
                if (isset ($_POST["id"])) {
                        $id = intval($_POST["id"]);
                } else {
                        $id = "1";
                }

                $query = "SELECT content AS content, title AS title, link AS link, linkimage AS linkimage FROM pages WHERE id = '$id'";
                $result = mysql_query($query);

                if (!$result) {
                        echo 'FAILED! <br>';
                        echo mysql_error();
                } else {
                        $num_rows = mysql_num_rows($result);
                        if ($num_rows == 0)
                                echo 'OMG H4XX0RZ. Making up random numbers will get you nowhere. Try again from the menu on the left.';
                        else {
                                while ($row = mysql_fetch_array($result)) {
                                        $content = $row["content"];
                                        $title = $row["title"];
                                        $link = $row["link"];
                                        $linkimage = $row["linkimage"];
                                        echo '<h1>Now editing: ' . $title . ' Section number:' . $id . '<br>';
                                        echo '<form action="/?id=admin" method="post">';
                                        echo '<input type="text" name="id" size="4" readonly value="' . $id . '">';
                                        echo '<input type="text" name="title" size="20" value="' . $title . '"><br>';
                                        echo '<input type="text" name="link" size="5" value="' . $link . '">';
                                        echo '<input type="text" name="linkimage" size="20" value="' . $linkimage . '"><br>';
                                        echo '<textarea name="content" rows="30" cols="70">' . $content . '</textarea>';
                                        echo '<input type="hidden" name="carat" value="preview">';
                                        echo '<input type="submit" value="Preview Changes"></p></form>';
                                }
                        }
                }
        }
        mysql_close();
}
// End Function

// Delete Existing Page - Carat = "Delete"
function screevoDelete() {

        openDatabaseScreevo();

        if (!$_POST["id"]) { //select page to be deleted
                $query = "SELECT id AS id, title AS title FROM pages WHERE id > '0' ORDER by id ASC";
                $result = mysql_query($query);
                $num_rows = mysql_num_rows($result);
                echo "Delete a page.<br> n <form action="index.php?id=admin" method="post">";
                while ($row = mysql_fetch_array($result)) {
                        $id = $row["id"];
                        $title = $row["title"];
                        echo '<input type="radio" name="id" value="' . $id . '">' . $id . ' - ' . $title . '<br>';
                }
                echo '<input type="hidden" name="carat" value="delete">';
                echo '<input type="submit" value="Delete selected page.">n</p>n</form>';
        }

        elseif (isset ($_POST["id"]) AND !isset ($_POST["confirm"])) { //confirm deletion
                $id = intval($_POST['id']);
                $query = "SELECT id AS id, title AS title FROM pages WHERE id = '$id'";
                $result = mysql_query($query);
                $num_rows = mysql_num_rows($result);
                while ($row = mysql_fetch_array($result)) {
                        $id = $row["id"];
                        $title = $row["title"];
                }

                echo 'Are you absolutely, positively sure you want to delete page ' . $id . ' - ' . $title . '?<br>';
                echo 'If you do, and you change your mind, you will have to recreate the page from scratch.<br>';
                echo 'To confirm, click Submit. Or else, <a href="/index.php?id=admin"> click here to go back.</a><br>';
                echo '<form action="/?id=admin" method="post">';
                echo '<input type="hidden" name="id" value="' . $id . '">';
                echo '<input type="hidden" name="title" value="' . $title . '">';
                echo '<input type="hidden" name="confirm" value="1"> <input type="hidden" name="carat" value="delete">';
                echo '<input type="submit" value="Yes, I am sure I want to delete the page.">';
        }

        elseif (isset ($_POST["id"]) AND $_POST["confirm"] == "1") {
                $id = intval($_POST["id"]);
                $title = $_POST["title"];
                $query = "DELETE FROM pages WHERE id ='$id'";
                $result = mysql_query($query);

                if (!$result) {
                        echo "FAILED!";
                        echo mysql_error();
                } else {
                        echo 'You have successfully deleted page number ' . $id . ' called ' . $title . '.';
                        mysql_close();
                }
        }

}
// End Function

//Preview Page - Carat = "preview"
function screevoPreview() {
$id=$_POST['id'];
$title=$_POST['title'];
$content=$_POST['content'];
$link=$_POST['link'];
$linkimage=$_POST['linkimage'];
echo 'Previewing: '.$title.'';
echo '<hr>';
echo $content;
echo '<br><br><br><br><br><br><br><br><br><br>';
echo '<hr>';
echo '<form action="/?id=admin" method="post">';
echo '<input type="text" name="id" size="4" value="'.$id.'">';
echo '<input type="text" name="title" size="20" value="'.$title.'"><br>';
echo '<input type="text" name="link" size="5" value="'.$link.'">';
echo '<input type="text" name="linkimage" size="20" value="'.$linkimage.'"><br>';
echo '<textarea name="content" rows="15" cols="50">'.$content.'</textarea><br>';
echo '<input type="hidden" name="carat" value="preview"';
echo '<input type="submit" value="Preview Changes">';
echo '<form action="/?id=admin" method="post">';
echo '<input type="hidden" name="id" value="'.$id.'">';
echo '<input type="hidden" name="title" value="'.$title.'">';
echo '<input type="hidden" name="content" value="'.htmlentities($content).'">';
echo '<input type="hidden" name="link" value="'.$link.'">';
echo '<input type="hidden" name="linkimage" value="'.$linkimage.'">';
echo '<input type="hidden" name="carat" value="put">';
echo '<input type="submit" value="Submit">';
}
//End Function

function screevoPut() {
    openDatabaseScreevo();
    $id = intval($_POST["id"]);
    $title = mysql_real_escape_string($_POST["title"]);
    $link = mysql_real_escape_string($_POST["link"]);
    $linkimage = mysql_real_escape_string($_POST["linkimage"]);
    $content = mysql_real_escape_string(stripslashes($_POST["content"]));
    $query = "SELECT * FROM pages WHERE id =" . $id . "";
    $result = mysql_query($query);
    if (empty($result)) {
        $query = "INSERT INTO pages set id='$id', title='$title', content='$content',link='$link', linkimage='$linkimage'";
        $result2 = mysql_query($query);
        if (!$result2) {
            echo "FAILED! <br>";
            echo mysql_error();
        } else {
            echo 'You have successfully created page number ' . $id . ' called ' . $title . '. To update more, please go back.';
            mysql_close();
        } 
    } else { 
        $query = "UPDATE pages SET content = '$content', title = '$title', link = '$link', linkimage = '$linkimage' WHERE id = '$id'";
        $result2 = mysql_query($query);
        if (!$result2) {
            echo 'FAILED!';
            echo mysql_error();
        } else {
            echo 'You have successfully updated page number ' . $id . ' called ' . $title . '. To update more, please go back.';
            mysql_close();
        } 
    }
}
//End Function

//==========END FUNCTIONS==========//

//========ADMIN PANEL=========//
if ($_GET['id'] == "admin") {

        checkUser(); //Get username and Password
        include (HEADER);
        switch (mysql_real_escape_string($_POST['carat'])) {
                case 'new' :
                        screevoNew();
                        break;
                case 'update' :
                        screevoUpdate();
                        break;
                case 'preview' :
                        screevoPreview();
                        break;
                case 'delete' :
                        screevoDelete();
                        break;
                case 'put' :
                        screevoPut();
                        break;
                default :
                        screevoStart();
                        break;
        }
        include (FOOTER);
}
//=======GENERATE PAGE========//

else { 
    include(HEADER);
    openDatabaseScreevo();    
    if(@!$_GET["id"]) 
        $id="1";
    else 
        $id=intval($_GET['id']);

    $query = "SELECT content AS content FROM pages WHERE id = '$id'";
    $result = mysql_query($query);

    if(!$result) 
        echo "Things are broken, people are dying, this page isn't working!";

    else {
        $num_rows = mysql_num_rows($result);   
        if($num_rows == 0) 
            echo "Quoth the database, "404". It appears the page you are trying to reach is not there."; 
        else {
            while ($row = mysql_fetch_array($result))     {
                                                        $content = $row["content"];
                                                        echo "n".$content."n";
                                                        }
        }
    mysql_close();
    }
    
    include(FOOTER);
}
?>