<?php
   session_start();
   error_reporting(E_ALL);
   define('ADMIN_PASS', 'design');
   $mysql_server = 'localhost';
   $mysql_username = 'root';
   $mysql_password = 'root';
   $mysql_database = 'cms_design';
   $username = 'admin';

   $asset_folder = './files/';
   $upload_result = '';
   $labelName = "Name";
   $labelCreatedBy = "Created by";
   $labelLastUpdate = "Last update";
   $labelVisible = "Visible";
   $labelHomePage = "Home page";
   $labelViews = "Views";
   $labelOrder = "Order";
   $labelContent = "Content";
   $labelURL = "External URL";
   $labelExtraData = "Extra data";
   $labelAction = "Action";
   $labelNewPage = "New Page";
   $labelFileManager = "File Manager";
   $labelPages = "Pages";
   $labelCaption = "Content Management System";
   $labelLogin = "Login";
   $labelLogout = "Logout";
   $labelEdit = "Edit";
   $labelCopy = "Copy";
   $labelDelete = "Delete";
   $labelYes = "Yes";
   $labelNo = "No";
   $labelFileName = "Filename";
   $labelSize = "Size";
   $labelLastModified = "Last modified";
   $labelUploadFile = "Upload File";
   $labelBrowse = "Use the 'Browse' button to select a file and then click 'Upload'";
   $labelUpload = "Upload";
   $labelSave = "Save";
   $labelCancel = "Cancel";
   $labelUp = "Up";
   $labelDown = "Down";
   $admin_password = isset($_COOKIE['cmsadmin_pwd']) ? $_COOKIE['cmsadmin_pwd'] : '';

   if (empty($admin_password))
   {
      if (isset($_POST['admin_password']))
      {
         $admin_password = md5($_POST['admin_password']);
         if ($admin_password == md5(ADMIN_PASS))
         {
            setcookie('cmsadmin_pwd', $admin_password);
         }
      }
   }
   $authorized = ($admin_password == md5(ADMIN_PASS));
   $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
   $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
   $name = isset($_POST['name']) ? $_POST['name'] : '';
   $content = isset($_POST['content']) ? $_POST['content'] : '';
   $url = isset($_POST['url']) ? $_POST['url'] : '';
   $extra_data = isset($_POST['extra_data']) ? $_POST['extra_data'] : '';
   $visible = isset($_POST['visible']) ? $_POST['visible'] : 0;
   $timestamp = date("y-m-d H:i:s", time());

   $db = mysql_connect($mysql_server, $mysql_username, $mysql_password);
   if (!$db)
   {
      die('Failed to connect to database server!<br>'.mysql_error());
   }
   mysql_select_db($mysql_database, $db) or die('Failed to select database<br>'.mysql_error());
   if ($authorized)
   {
      if (get_magic_quotes_gpc())
      {
         $content = stripslashes($content);
      }
      $content = mysql_real_escape_string($content);
      $sql = "CREATE TABLE IF NOT EXISTS pagesPAGES (id INT UNSIGNED NOT NULL AUTO_INCREMENT,
              category_id INT NOT NULL, 
              name VARCHAR(255) NOT NULL, 
              content TEXT NOT NULL, 
              home tinyint(1) NOT NULL, 
              visible tinyint(1) NOT NULL, 
              create_date TIMESTAMP NOT NULL, 
              created_by VARCHAR(255) NOT NULL, 
              last_update_date TIMESTAMP NOT NULL, 
              last_update_by VARCHAR(255) NOT NULL, 
              views INT NOT NULL, 
              menu_index INT NOT NULL, 
              url VARCHAR(255), 
              extra_data VARCHAR(255), 
              PRIMARY KEY(id));";
      $result = mysql_query($sql, $db);
      if (!$result)
      {
         die('Invalid query: ' . mysql_error());
      }
      $sql = "CREATE TABLE IF NOT EXISTS pagesSEARCH_WORDS (id INT UNSIGNED NOT NULL AUTO_INCREMENT,
              word VARCHAR(50) NOT NULL,
              PRIMARY KEY (id));";
      $result = mysql_query($sql, $db);
      if (!$result)
      {
         die('Invalid query: ' . mysql_error());
      }
      $sql = "CREATE TABLE IF NOT EXISTS pagesSEARCH_WORDMATCH (page_id INT UNSIGNED NOT NULL,
              word_id INT UNSIGNED NOT NULL,
              PRIMARY KEY(page_id, word_id));";
      $result = mysql_query($sql, $db);
      if (!$result)
      {
         die('Invalid query: ' . mysql_error());
      }
      if (!empty($action))
      {
         if ($action == 'delete')
         {
            $sql = "SELECT * FROM pagesPAGES WHERE `id` = '$id'";
            $result = mysql_query($sql, $db);
            if ($data = mysql_fetch_array($result))
            {
               $menu_index = $data['menu_index'];
            }
            $sql = "DELETE FROM pagesPAGES WHERE `id` = '$id'";
            mysql_query($sql, $db);
            $sql = "DELETE FROM pagesSEARCH_WORDMATCH WHERE `page_id` = '$id'";
            mysql_query($sql, $db);
            $sql = "UPDATE pagesPAGES SET menu_index=menu_index-1 WHERE menu_index > '$menu_index'";
            mysql_query($sql, $db);
            mysql_close($db);
            header('Location: '.basename(__FILE__));
            exit;
         }
         else
         if ($action == 'update')
         {
            $sql = "UPDATE pagesPAGES SET `name` = '$name', `content` = '$content', `url` = '$url', `extra_data` = '$extra_data', `visible` = $visible, `last_update_date` = '$timestamp', `last_update_by` = '$username' WHERE `id` = '$id'";
            mysql_query($sql, $db);
            addToSearchIndex($id, $content);
            mysql_close($db);
            header('Location: '.basename(__FILE__));
            exit;
         }
         else
         if ($action == 'create')
         {
         $sql = "SELECT * FROM pagesPAGES";
         $result = mysql_query($sql, $db);
         $menu_index = mysql_num_rows($result);
         $menu_index = $menu_index + 1;
            $sql = "INSERT pagesPAGES (`category_id`, `name`, `content`, `url`, `extra_data`, `visible`, `create_date`, `created_by`, `last_update_date`, `last_update_by`, `menu_index`) VALUES (0, '$name', '$content', '$url', '$extra_data', $visible, '$timestamp', '$username', '$timestamp', '$username', $menu_index)";
            mysql_query($sql, $db);
            $id = mysql_insert_id();
            addToSearchIndex($id, $content);
            mysql_close($db);
            header('Location: '.basename(__FILE__));
            exit;
         }
         else
         if ($action == 'deletefile')
         {
            $filename = $asset_folder . $_REQUEST['file'];
            if (file_exists($filename))
            {
               unlink ($filename) or die ("Could not delete file");
            }
            header('Location: '.basename(__FILE__).'?action=filemanager');
            exit;
         }
         else
         if ($action == 'upload')
         {
            if (isset($_FILES['filename']))
            {
               $name  = $_FILES['filename']['name'];
               $tmp_name = $_FILES['filename']['tmp_name'];
               $error = $_FILES['filename']['error'];
               if ($error > 0)
               {
                  $upload_result = "File upload error: " . $error;
               }
               else
               {
                  if (move_uploaded_file($tmp_name, $asset_folder. $name))
                  {
                     $upload_result = "File succesfully uploaded!<br><br>Filename:<br>". $asset_folder. $name. "<br>";
                  }
                  else
                  {
                     $upload_result = "File upload error: Upload failed, please verify the folder's permissions.";
                  }
               }
            }
            else
            {
               $upload_result = "File upload error: No filename specified!";
            }
         }
         else
         if ($action == 'home')
         {
            $sql = "UPDATE pagesPAGES SET `home` = 0";
            mysql_query($sql, $db);
            $sql = "UPDATE pagesPAGES SET `home` = 1 WHERE `id` = '$id'";
            mysql_query($sql, $db);
            mysql_close($db);
            header('Location: '.basename(__FILE__));
            exit;
         }
         else
         if ($action == 'moveup' || $action == 'movedown')
         {
            $sql = "SELECT * FROM pagesPAGES WHERE `id` = '$id'";
            $result = mysql_query($sql, $db);
            if ($data = mysql_fetch_array($result))
            {
               $menu_index = $data['menu_index'];
            }
            if ($action == 'moveup')
               $new_index = $menu_index - 1;
            else
               $new_index = $menu_index + 1;
            $sql = "UPDATE pagesPAGES SET menu_index = $menu_index WHERE menu_index = '$new_index'";
            mysql_query($sql, $db);
            $sql = "UPDATE pagesPAGES SET menu_index = $new_index WHERE id = '$id'";
            mysql_query($sql, $db);
            mysql_close($db);
            header('Location: '.basename(__FILE__));
            exit;
         }
         else
         if ($action == 'logout')
         {
            session_unset();
            session_destroy();
            setcookie('cmsadmin_pwd', '', time() - 3600);
            header('Location: '.basename(__FILE__));
            exit;
         }
      }
   }
   function addToSearchIndex($page_id, $content)
   {
      $sql = "DELETE FROM pagesSEARCH_WORDMATCH WHERE page_id = '$page_id'";
      mysql_query($sql);
      $content = strtolower(html_entity_decode($content));
      $content = preg_replace('/&#?\w+;/', ' ', $content);
      if (!get_magic_quotes_runtime())
         $content = addslashes($content);
      $content = preg_replace('/\s+/', ' ', $content);
      $content = strip_tags($content);
      $content = preg_replace('/\W+/', ' ', $content);
      $words = preg_split('/\s+/', trim($content));
      $id_array = array();
      $index = 0;
      foreach ($words as $word)
      {
         if (strlen($word) < 2) continue;
         if (is_numeric($word)) continue;
         $sql = "SELECT id FROM pagesSEARCH_WORDS WHERE word = '$word';";
         $result = mysql_query($sql);
         if (!$result)
         {
            die('Invalid query: ' . mysql_error());
         }
         $record = mysql_fetch_object($result);
         if (!$word_id = $record->id)
         {
            $sql = "INSERT INTO pagesSEARCH_WORDS (word) VALUES ('$word');";
            mysql_query($sql);
            $word_id = mysql_insert_id();
         }
         $id_array[$index] = $word_id;
         $index++;
      }
      foreach ($id_array as $word_id)
      {
         $sql = "INSERT INTO pagesSEARCH_WORDMATCH (`word_id`, `page_id`) VALUES ('$word_id', '$page_id');";
         mysql_query($sql);
      }
   }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Content Management System Administrator</title>
<style type="text/css">
body
{
   background-color: #FFFFFF;
   margin: 0;
}
p
{
   font-size: 11px;
   font-family: Tahoma;
   font-weight: normal;
   text-decoration: none;
   color: #454545;
}
th
{
   font-size: 11px;
   font-family: Tahoma;
   font-weight: normal;
   text-decoration: none;
   background-color: #454545;
   color: #FFFFFF;
   text-align: left;
}
td
{
   font-size: 11px;
   font-family: Tahoma;
   font-weight: normal;
   text-decoration: none;
   color: #454545;
   vertical-align: top;
}
a, a:hover, a:visited
{
   color: #454545;
}
input, select, textarea
{
   font-size: 11px;
   font-family: Tahoma;
   font-weight: normal;
   text-decoration: none;
   color: #454545;
   border:1px #454545 solid;
}
</style>
<script type="text/javascript" src="./jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="./ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="./ckeditor/adapters/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
   $('#editor').ckeditor({});
});
</script>
</head>
<body>
<?php

   if (!$authorized)
   {
      echo "<p>$labelCaption</p>\n";
      echo "<form method=\"post\" action=\"" .basename(__FILE__) . "\">\n";
      echo "<input type=\"password\" name=\"admin_password\" size=\"20\" />\n";
      echo "<input type=\"submit\" value=\"$labelLogin\" name=\"submit\" />\n";
      echo "</form>\n";
   }
   else
   {
      if (!empty($action))
      {
         if ($action == 'edit' || $action == 'new' || $action == 'copy')
         {
            $sql = "SELECT * FROM pagesPAGES WHERE id = '".$id."'";
            $result = mysql_query($sql, $db);
            if ($data = mysql_fetch_array($result))
            {
               $name_value = $data['name'];
               $content_value = $data['content'];
               $visible_value = $data['visible'];
               $url_value = $data['url'];
               $extra_data_value = $data['extra_data'];
            }
            echo "<form action=\"" . basename(__FILE__) . "\" method=\"post\">\n";
            if ($action == 'new' || $action == 'copy')
            {
               echo "<input type=\"hidden\" name=\"action\" value=\"create\">\n";
            }
            else
            {
               echo "<input type=\"hidden\" name=\"action\" value=\"update\">\n";
            }
            echo "<input type=\"hidden\" name=\"id\" value=\"". $id . "\">\n";
            echo "<table width=\"100%\" border=\"0\">\n";
            echo "<tr><td>$labelName:</td>\n";
            echo "<td><input type=\"text\" size=\"50\" name=\"name\" value=\"" . $name_value . "\"></td></tr>\n";
            echo "<tr><td>$labelContent:</td>\n";
            echo "<td><textarea id=\"editor\" style=\"width:99%;height:200px\" name=\"content\">" . $content_value . "</textarea></td></tr>\n";
            echo "<tr><td>$labelURL:</td>\n";
            echo "<td><input type=\"text\" style=\"width:98%;\" name=\"url\" value=\"" . $url_value . "\"></td></tr>\n";
            echo "<tr><td>$labelExtraData:</td>\n";
            echo "<td><input type=\"text\" style=\"width:98%;\" name=\"extra_data\" value=\"" . $extra_data_value . "\"></td></tr>\n";
            echo "<tr><td>$labelVisible:</td>\n";
            echo "<td><select name=\"visible\" size=\"1\"><option " . ($visible_value == "0" ? "selected " : "") . "value=\"0\">Hidden</option><option " . ($visible_value != "0" ? "selected " : "") . "value=\"1\">Visible</option></select></td></tr>\n";
            echo "<tr><td>&nbsp;</td><td style=\"text-align:left\"><input type=\"submit\" name=\"submit\" value=\"$labelSave\">";
            echo "&nbsp;&nbsp;";
            echo "<input type=\"button\" name=\"back\" value=\"$labelCancel\" onclick=\"location.href='" . basename(__FILE__) . "'\"></td></tr>\n";
            echo "</table>\n";
            echo "</form>\n";
         }
         else
         if ($action == 'filemanager')
         {
            echo "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">\n";
            echo "<tr><th>$labelFileName</th>\n";
            echo "<th>$labelSize</th>\n";
            echo "<th>$labelLastModified</th>\n";
            echo "<th>$labelAction</th></tr>\n";
            if ($handle = opendir($asset_folder))
            {
               while (false !== ($filename = readdir($handle)))
               {
                  if ($filename != "." && $filename != ".." && is_file($asset_folder.$filename))
                  {
                     echo "<tr>\n";
                     echo "<td>" . $filename . "</td>\n";
                     echo "<td>";
                     $bytes = filesize($asset_folder.$filename);
                     if ($bytes < 1024)
                        echo $bytes.' B';
                     elseif ($bytes < 1048576)
                        echo round($bytes / 1024, 2).' KB';
                     elseif ($bytes < 1073741824)
                        echo round($bytes / 1048576, 2).' MB';
                     echo "</td>\n";
                     echo "<td>" . date("Y-m-d H:i:s", filemtime($asset_folder.$filename)) . "</td>\n";
                     echo "<td>\n";
                     echo "   <a href=\"" . basename(__FILE__) . "?action=deletefile&file=" . $filename . "\">$labelDelete</a>\n";
                     echo "</td>\n";
                     echo "</tr>\n";
                  }
               }
               closedir($handle);
            }
            echo "</table>\n";
            echo "<p><a href=\"" . basename(__FILE__) . "?action=newfile\">$labelUploadFile</a>&nbsp;&nbsp;<a href=\"" . basename(__FILE__) . "\">$labelPages</a>&nbsp;&nbsp;<a href=\"" . basename(__FILE__) . "?action=logout\">$labelLogout</a></p>\n";
         }
         else
         if ($action == 'newfile')
         {
            echo "<p>" . $labelBrowse . "</p>\n";
            echo "<form enctype=\"multipart/form-data\" action=\"" . basename(__FILE__) . "\" method=\"post\">\n";
            echo "<input type=\"hidden\" name=\"action\" value=\"upload\">\n";
            echo "<input type=\"file\" size=\"50\" name=\"filename\"><br><br>\n";
            echo "<input type=\"submit\" name=\"submit\" value=\"$labelUpload\">\n";
            echo "</form><br><br>\n";
            echo "<p><a href=\"" . basename(__FILE__) . "?action=filemanager\">$labelFileManager</a>&nbsp;&nbsp;<a href=\"" . basename(__FILE__) . "?action=logout\">$labelLogout</a></p>\n";
         }
         else
         if ($action == 'upload')
         {
            echo "<p>\n";
            echo $upload_result;
            echo "<a href=\"" . basename(__FILE__) . "?action=filemanager\"><br><br>$labelFileManager</a>\n";
            echo "</p>\n";
         }
      }
      else
      {
         echo "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">\n";
         echo "<tr><th>$labelName</th>\n";
         echo "<th>$labelCreatedBy</th>\n";
         echo "<th>$labelLastUpdate</th>\n";
         echo "<th>$labelVisible</th>\n";
         echo "<th>$labelHomePage</th>\n";
         echo "<th>$labelViews</th>\n";
         echo "<th>$labelOrder</th>\n";
         echo "<th>$labelAction</th></tr>\n";

         $sql = "SELECT * FROM pagesPAGES";
         if ($username != 'admin')
         {
            $sql = $sql . " WHERE created_by = '".$username."'";
         }
         $sql = $sql . " ORDER BY menu_index ASC";
         $result = mysql_query($sql, $db);
         $num_rows = mysql_num_rows($result);
         while ($data = mysql_fetch_array($result))
         {
            echo "<tr>\n";
            echo "<td>" . $data['name'] . "</td>\n";
            echo "<td>" . $data['created_by'] . "</td>\n";
            echo "<td>" . $data['last_update_date'] . "</td>\n";
            echo "<td>" . ($data['visible'] == "0" ? $labelNo : $labelYes) . "</td>\n";
            echo "<td>";
            if ($data['home'] == "1")
               echo $labelYes;
            else
               echo "   <a href=\"" . basename(__FILE__) . "?action=home&id=" . $data['id'] . "\">$labelNo</a>";
            echo "</td>\n";
            echo "<td>" . $data['views'] . "</td>\n";
            echo "<td>";
            if ($data['menu_index'] <= 1)
            {
               echo "   <a href=\"" . basename(__FILE__) . "?action=movedown&id=" . $data['id'] . "\">$labelDown</a>";
            }
            elseif ($data['menu_index'] >= $num_rows)
            {
               echo "   <a href=\"" . basename(__FILE__) . "?action=moveup&id=" . $data['id'] . "\">$labelUp</a>";
            }
            else
            {
               echo "   <a href=\"" . basename(__FILE__) . "?action=moveup&id=" . $data['id'] . "\">$labelUp</a> &nbsp; ";
               echo "   <a href=\"" . basename(__FILE__) . "?action=movedown&id=" . $data['id'] . "\">$labelDown</a>";
            }
            echo "</td>\n";
            echo "<td>\n";
            echo "   <a href=\"" . basename(__FILE__) . "?action=edit&id=" . $data['id'] . "\">$labelEdit</a> | \n";
            echo "   <a href=\"" . basename(__FILE__) . "?action=copy&id=" . $data['id'] . "\">$labelCopy</a> | \n";
            echo "   <a href=\"" . basename(__FILE__) . "?action=delete&id=" . $data['id'] . "\">$labelDelete</a>\n";
            echo "</td>\n";
            echo "</tr>\n";
         }
         echo "</table>\n";
         echo "<p><a href=\"" . basename(__FILE__) . "?action=new\">$labelNewPage</a>&nbsp;&nbsp;<a href=\"" . basename(__FILE__) . "?action=filemanager\">$labelFileManager</a>&nbsp;&nbsp;<a href=\"" . basename(__FILE__) . "?action=logout\">$labelLogout</a></p>\n";
      }
   }

?>
</body>
</html>
