<?php
/*
This class will be used to maintian web page content.
*/
class content {
  var $host;
  var $username;
  var $password;
  var $db;
  var $id;
  var $key;

  function content($host, $username, $password, $db, $key){
    $this->host = $host;
    $this->username = $username;
    $this->password = $password;
    $this->db = $db;
    $this->connect();
    $this->id = $this->get_id_from_key($key);
    $this->key = $key;
  }

  public function get_id_from_key($key){
   $q = "SELECT * FROM pages WHERE pagekey='$key'";
    $r = mysql_query($q);

    if ( $r !== false && mysql_num_rows($r) > 0 ) {
      $a = mysql_fetch_assoc($r); 
      return $a['id'];
  }
}

/**
  deletes a page by its id
  */
  public function delete_content(){
    $id = $this->id;
    $q = "DELETE FROM pages WHERE id = '$id'";
    return mysql_query($q);
  }

  /**
  returns the raw content for a page in an array
  keys are:
  title
  bodytext
  id
  */
  public function get_content() {
    $q = "SELECT * FROM pages WHERE id=".$this->id;
    $r = mysql_query($q);

    if ( $r !== false && mysql_num_rows($r) > 0 ) {
      return mysql_fetch_assoc($r);
    }
  }

  /*
  returns a html formated body
  */
  public function get_body() {
      $key = $this->key;
      $a = $this->get_content();
      $body = $this->txt2html($a['bodytext']);
      if($_SESSION['access'] == admin) {
        $body .= "</br><a href=\"content_manager.php?pagekey=$key\">Edit</a>";
      }
      return $body;
  }

  /*
  returns a non formated body
  */
  public function get_title() {
     $a = $this->get_content();
      return $a['title'];
  }

  /*
  This function will be used to edit a page
  */
  public function display_editor() {
    $content = $this->get_content();
    $id = $this->id;
    $key = $this->key;
    $title = $content['title'];
    $body = $content['bodytext'];

    return <<<ADMIN_FORM
    <form action="{$_SERVER['PHP_SELF']}" method="post">
    
      <input type="hidden" name="page" value="$id" />
      <input type="hidden" name="pagekey" value="$key" />
      <div class="clearfix">
        <label for="title">Title</label><br />
        <div class="input">
          <input name="title" id="title" type="text" maxlength="55"  class="xlarge" value="$title"> </input>
        </div>
      </div>
     
     <div class="clearfix">
      <label for="bodytext">Body Text</label><br />
      <div class="input">
        <textarea name="bodytext" id="bodytext" rows=10 cols=56 class="xxlarge">$body</textarea>
      </div>
      </div>
      
      <div class="actions">
        <button type="submit" class="btn primary" >Save</button>
        <button type="reset" class="btn">Cancel</button>
      </div>
    </form>

ADMIN_FORM;
  }

  /*
  saves page information
  */
  public function write($title, $body) {
    $title = mysql_real_escape_string(strip_tags($title));
    $bodytext = mysql_real_escape_string($body);
    $key = $this->key;
    $updateStm = "UPDATE pages SET title='$title', bodytext='$body' WHERE pagekey='$key'";

		mysql_query($updateStm);

  if(mysql_affected_rows()<=0){
      $sql = "INSERT INTO pages (title, bodytext, pagekey)VALUES('$title','$bodytext','$key')";
      mysql_query($sql);
    }
  }

  /**
  This function connects to the database
  */
  public function connect() {
    mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
    mysql_select_db($this->db) or die("Could not select database. " . mysql_error());

    return $this->buildDB();
  }

  private function buildDB() {
    $sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS pages ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, title TEXT, bodytext TEXT, pagekey TEXT)
MySQL_QUERY;

    return mysql_query($sql);
  }

public function stri_replace( $find, $replace, $string ) {
// Case-insensitive str_replace()

  $parts = explode( strtolower($find), strtolower($string) );

  $pos = 0;

  foreach( $parts as $key=>$part ){
    $parts[ $key ] = substr($string, $pos, strlen($part));
    $pos += strlen($part) + strlen($find);
  }

  return( join( $replace, $parts ) );
}


public function txt2html($txt) {
// Transforms txt in html

  //Kills double spaces and spaces inside tags.
  while( !( strpos($txt,'  ') === FALSE ) ) $txt = str_replace('  ',' ',$txt);
  $txt = str_replace(' >','>',$txt);
  $txt = str_replace('< ','<',$txt);

  //Transforms accents in html entities.
  $txt = htmlentities($txt);

  //We need some HTML entities back!
  $txt = str_replace('&quot;','"',$txt);
  $txt = str_replace('&lt;','<',$txt);
  $txt = str_replace('&gt;','>',$txt);
  $txt = str_replace('&amp;','&',$txt);

  //Ajdusts links - anything starting with HTTP opens in a new window
  $txt = $this->stri_replace("<a href=\"http://","<a target=\"_blank\" href=\"http://",$txt);
  $txt = $this->stri_replace("<a href=http://","<a target=\"_blank\" href=http://",$txt);

  //Basic formatting
  $eol = ( strpos($txt,"\r") === FALSE ) ? "\n" : "\r\n";
  $html = '<p>'.str_replace("$eol$eol","</p><p>",$txt).'</p>';
  $html = str_replace("$eol","<br />\n",$html);
  $html = str_replace("</p>","</p>\n\n",$html);
  $html = str_replace("<p></p>","<p>&nbsp;</p>",$html);

  //Wipes <br> after block tags (for when the user includes some html in the text).
  $wipebr = Array("table","tr","td","blockquote","ul","ol","li");

  for($x = 0; $x < count($wipebr); $x++) {

    $tag = $wipebr[$x];
    $html = $this->stri_replace("<$tag><br />","<$tag>",$html);
    $html = $this->stri_replace("</$tag><br />","</$tag>",$html);

  }

  return $html;
}

}
?>
