<?php

class db {
  public $conn;

  function __construct() {
    if ( $_SERVER[ 'HTTP_HOST' ] == "localhost" ) {
      $conn = new mysqli( "localhost", "root", "", "pgl" );
    } elseif ( strpos( $_SERVER[ 'HTTP_HOST' ], "isappointment" ) || strpos( $_SERVER[ 'HTTP_HOST' ], "awoftheplayground" ) ) {
      $conn = new mysqli("localhost", $_SERVER['REDIRECT_DBUSER'], $_SERVER['REDIRECT_DBPASS'], $_SERVER['REDIRECT_DBUSER']);
    }

    $this->conn = $conn;

    if ( $conn->connect_error ) {
      die( "Connection failed: " . $conn->connect_error );
    }
  }
}

abstract class Page {
  abstract function on_page(); // Every page needs an on_page function that returns a div that tells you what page you're on
  public static $pagination = 25; // Items per page. Not adjustable at this point		
  public $stagingFilter = 4;

  public static $stagingdescription = array("Obliterated", "Deleted", "Rejected", "Pending", "Approved");
  public static $statingscore = array(-5, -3, -1, 1, 5);
  public static $admincredit = array( "obliterated by", "deleted by", "disapproved by", "left hanging by", "approved by" );

  static $pageHeader = "<a href='index.php'><img src='images/header.png' class='header_image'></a>";
  static $pageFooter = "(c) 20xx all rights reserved<br>haha lol don't be daft this is all yours baby ilu";
  static $alphaGrid = <<<ALPHAGRID
<div class="alphagrid hidemobile">
<nav>

<a href="index.php?letter=1">#</a> 
<a href="index.php?letter=a">a</a> 
<a href="index.php?letter=b">b</a> 
<a href="index.php?letter=c">c</a> 
<a href="index.php?letter=d">d</a> 
<a href="index.php?letter=e">e</a> 
<a href="index.php?letter=f">f</a> 
<a href="index.php?letter=g">g</a> 
<a href="index.php?letter=h">h</a><br>
<a href="index.php?letter=i">i</a> 
<a href="index.php?letter=j">j</a> 
<a href="index.php?letter=k">k</a> 
<a href="index.php?letter=l">l</a> 
<a href="index.php?letter=m">m</a> 
<a href="index.php?letter=n">n</a> 
<a href="index.php?letter=o">o</a> 
<a href="index.php?letter=p">p</a> 
<a href="index.php?letter=q">q</a><br> 
<a href="index.php?letter=r">r</a> 
<a href="index.php?letter=s">s</a> 
<a href="index.php?letter=t">t</a> 
<a href="index.php?letter=u">u</a> 
<a href="index.php?letter=v">v</a> 
<a href="index.php?letter=w">w</a> 
<a href="index.php?letter=x">x</a> 
<a href="index.php?letter=y">y</a> 
<a href="index.php?letter=z">z</a><br>
<a href="index.php?type=latest">latest</a> | 
<a href="index.php?type=random">random</a>
</nav>
</div>

ALPHAGRID;
    
    function __construct() {
        $this->stagingFilter = $_SESSION['filters'];
    }

  function filters() {
    if ( !isset( $_SESSION[ 'filters' ] ) ) {
      $_SESSION[ 'filters' ] = 4;
    }
    $qc[ 1 ] = "* <span class='greyed'>* * * </span>";
    $qc[ 2 ] = "* * <span class='greyed'>* *</span>";
    $qc[ 3 ] = "* * * <span class='greyed'>*</span>";
    $qc[ 4 ] = "* * * *<span class='greyed'></span>";

    echo "<div class='alphagrid filters'>";
    echo "shit filter<br>" . $qc[ $_SESSION[ 'filters' ] ];
    $link = $_SERVER[ 'REQUEST_URI' ];
    if ( $link == "index.php" ) {
      $link = "index.php?staging=";
    } else {
      $link = $link . "&staging=";
    }
    echo "<br>";
    if ( $_SESSION[ 'filters' ] < 4 ) {
      ?>
<a class="green" href="<?= $link ?><?= $_SESSION['filters']+1 ?>">better!</a>
<?php
}
if ( $_SESSION[ 'filters' ] > 1 ) {
  ?>
<a class="orange" href="<?= $link ?><?= $_SESSION['filters']-1 ?>">worse!</a>
<?php
}
echo "</div>";
}

function show_header_image() {
  echo "<a href='index.php'><img src='images/header" . $_SESSION[ 'filters' ] . ".png' class='header_image'></a>";
}

function is_valid_staging( $a ) {
  if ( $a == 1 || $a == 2 || $a == 3 || $a == 4 ) return true;
  return false;
}
    
function search_box() {
    echo "<div class='alphagrid search hidemobile'><form method='post' action='index.php'><input type='text' name='search' placeholder='search Lotp' maxlength='25'> <input type='submit' name='submit' value='i feel pretty'></form></div>";
}

function show_pagination($verbose = true) {

    if($verbose !== false) $verbose = true;

  if ( is_a( $this, "AlphaPage" ) ) {
    $link_base = "<a href='index.php?letter=" . $this->letter . "&page=";
    $either_side = 3;
  } else if ( is_a( $this, "Cockfingers" ) ) {
    $link_base = "<a href='index.php?cockfingers=please&page=";
    $either_side = 2;
  } else { $either_side = 3; }
  

  $page_min = max( 1, $this->page - $either_side );
  $page_max = min( $this->pages, $this->page + $either_side );

  if($verbose) echo "<div class='alphagrid pagination'>";

  if($verbose) echo "<div class='pag_nums'>on page $this->page of $this->pages</div>";
    
  echo "<div class='pag_arrows'>";
      if ( $this->page > 1 ) {
        $target = $this->page - 1;
        echo $link_base . "1'>&lt;&lt </a> ";;
        echo $link_base . $target . "'>&lt </a>";
      } else {
        echo "<span class='greyed'>&lt;&lt; </span>";
        echo "<span class='greyed'>&lt; </span>";
      }
      echo " {$this->page}/{$this->pages} ";
      if ( $this->page < $this->pages ) {
        $target = $this->page + 1;
        echo $link_base . $target . "'> &gt</a>";
        echo $link_base . $this->pages . "'> &gt;&gt</a> ";
      } else {
        echo "<span class='greyed'> &gt;</span>";
        echo "<span class='greyed'> &gt;&gt;</span>";
      }
  echo "</div>";

    if($verbose) {
      echo "<div class='pag_nums'>";
          for ( $i = $either_side + 1; $i > $this->page; $i-- ) {
            echo ". ";
          }
          for ( $i = $page_min; $i <= $page_max; $i++ ) {
            echo $link_base . $i . "'>$i </a>";
          }
          for ( $i = $this->page; $i >= $this->pages - ( $either_side - 1 ); $i-- ) {
            echo ". ";
          }
      echo "</div>";
    }
 if($verbose) echo "</div>";
}

function get_blurb( $blurb, $conn ) {
  $sql = "select fldBlurb from tblblurb where tblblurb.fldId = " . $blurb . " LIMIT 1";
  #		echo $sql;
  $res = $conn->query( $sql );
  $row = $res->fetch_assoc();
  return $row[ 'fldBlurb' ];
}


function parse_blurb( $blurb ) {
  $blurb = str_replace( "<cockfingers>", "<p class='adminname'><img src='images/edward.png' alt='Cockfingers says...' />", $blurb );
  $blurb = str_replace( "[cf]", "<p class='adminname'><img src='images/edward.png' alt='Cockfingers says...' />", $blurb );
  $blurb = str_replace( "<ponk>", "<p class='adminname'><img src='images/ponky.png' alt='Ponky says...' />", $blurb );
  $blurb = str_replace( "<ponky>", "<p class='adminname'><img src='images/ponky.png' alt='Ponky says...' />", $blurb );
  $blurb = str_replace( "<matt>", "<p class='adminname'><img src='images/matt.png' alt='Matt says...' />", $blurb );
  $blurb = str_replace( "<rosy>", "<p class='adminname'><img src='images/rosy.png' alt='Rosy says...' />", $blurb );
  $blurb = str_replace( "<susan>", "<p class='adminname'><img src='images/susan.png' alt='Susan says...' />", $blurb );
  $blurb = str_replace( "<sarah>", "<p class='adminname'><img src='images/susan.png' alt='Susan says...' />", $blurb );
  $blurb = str_replace( "<log>", "<p class='adminname'><img src='images/log.png' alt='Log says...' />", $blurb );
  $blurb = str_replace( "<phil>", "<p class='adminname'><img src='images/phil.png' alt='Phil says...' />", $blurb );
  $blurb = str_replace( "<mansh>", "<p class='adminname'><img src='images/mansh.png' alt='Mansh says...' />", $blurb );
  $blurb = str_replace( "<conor>", "<p class='adminname'><img src='images/conor.png' alt='Conor says...' />", $blurb );
  $blurb = str_replace( "<jamie>", "<p class='adminname'><img src='images/jamie.png' alt='Jamie says...' />", $blurb );

  $blurb = str_replace( "</cockfingers>", "</p>", $blurb );
  $blurb = str_replace( "[/cf]", "</p>", $blurb );
  $blurb = str_replace( "</ponk>", "</p>", $blurb );
  $blurb = str_replace( "</ponky>", "</p>", $blurb );
  $blurb = str_replace( "</matt>", "</p>", $blurb );
  $blurb = str_replace( "</rosy>", "</p>", $blurb );
  $blurb = str_replace( "</susan>", "</p>", $blurb );
  $blurb = str_replace( "</sarah>", "</p>", $blurb );
  $blurb = str_replace( "</log>", "</p>", $blurb );
  $blurb = str_replace( "</phil>", "</p>", $blurb );
  $blurb = str_replace( "</mansh>", "</p>", $blurb );
  $blurb = str_replace( "</conor>", "</p>", $blurb );
  $blurb = str_replace( "</jamie>", "</p>", $blurb );

  return stripslashes( $blurb );
}

function star_name( $name ) {
  $i = strlen( $name );
  for ( $a = 2; $a < $i; $a = $a + rand( 3, 6 ) ) {
    $name = substr( $name, 0, $a ) . "*" . substr( $name, $a + 1, $i - $a - 1 );
  }
  return $name;
}

function get_pupils( $blurb, $conn ) {
  $sql = "select tblpupil.fldFirstName as first, tblpupil.fldLastName as last, tblpupil.fldId as pupil
				from tblpupil, tblpupilblurbmap, tblblurb
				where tblpupil.fldId = tblpupilblurbmap.fldPupilId
				and tblpupilblurbmap.fldBlurbId = tblblurb.fldId
				and tblpupilblurbmap.fldBlurbId = " . $blurb;
  #		echo $sql;
  if ( !$res = $conn->query( $sql ) ) {
    echo $conn->error;
    return false;
  } else {
    $return_string = "";
  }

  while ( $row = $res->fetch_assoc() ) {
    if ( $return_string != "" )$return_string .= ", ";
    $name = $this->star_name( $row[ 'first' ] . " " . $row[ 'last' ] );
    if ( trim( $name ) == "" ) {
      $return_string .= "excluded pupil";
    } else {
      $return_string .= "<a href='index.php?pupil=" . $row[ 'pupil' ] . "'>" . $name . "</a>";
    }
  }
  return $return_string;
}

}

class AlphaPage extends Page {
  public $letter = "a"; // Letter we're looking at. Can be # a=z
  public $page;
  public $pages; // The upper page limit - total results / 25, rounded up
  public $content = ""; // The main body of text, stored as an HTML string
  public $on_page; // You are on the letter a,  page 1 of x
  public $on_letter;
  private $sql;

  function __construct( $letter, $page, $conn ) {
    // If letter isn't a-z or #. default to "a"
    $letter = strtolower( substr( $letter, 0, 1 ) );
    if ( !preg_match( "/[1a-z]/", $letter )) {
      $this->letter = "a";
    } else {
      $this->letter = $letter;
    }

    // Get the staging filter so the correct count happens 
    if ( isset( $_SESSION[ 'filters' ] ) && $this->is_valid_staging( $_SESSION[ 'filters' ] ) ) {
      $this->stagingFilter = $_SESSION[ 'filters' ];
    } else {
      $this->stagingFilter = 4;
    }

    // Get number of pages for that letter, so we have the info to see if the page number is valid
    if ( $this->letter == "1" ) {
      $where_clause = " where tblsubject.fldName NOT REGEXP  '^[a-z]' ";
    } else {
      $where_clause = " where tblsubject.fldName LIKE '" . $this->letter . "%' ";
    }


    $countQuery = "select count(*) as count from tblsubject " . $where_clause . " and fldStagingId = " . $this->stagingFilter;
    $res = $conn->query( $countQuery );
    $row = $res->fetch_assoc();
    $this->pages = ceil( $row[ 'count' ] / parent::$pagination );

    // Check if the page requested is a valid page - ie, positive integer within the max pages we just worked out 
    if ( intval( $page ) == $page && $page >= 1 && $page <= $this->pages ) {
      $this->page = $page;
    } else {
      $this->page = 1;
    }


    // "you are on page 1 of x"

#    $this->on_letter = $this->letter . " is for JOKE";
#    $this->on_page = "Page " . $this->page . " of " . $this->pages;

    // Get the page content from the database

    $this->sql = "select min(tblblurb.fldId) as firstBlurbId,
			   count(*) as totalBlurbs,
			   tblsubject.*
				from tblsubject
				inner join tblblurb on tblblurb.fldSubjectId = tblsubject.fldId
				$where_clause
				And tblsubject.fldStagingId >= $this->stagingFilter
				And tblblurb.fldStagingId >= $this->stagingFilter
				group by tblsubject.fldId
				order by tblsubject.fldName ASC
				limit " . ( $this->page - 1 ) * self::$pagination . ", " . self::$pagination;

      
    if ( $res = $conn->query( $this->sql ) ) {
      while ( $row = $res->fetch_assoc() ) {
        $blurb = $this->get_blurb( $row[ 'firstBlurbId' ], $conn );
        $blurb = $this->parse_blurb( $blurb );
        $staging = $row[ 'fldStagingId' ];
        $stagingclass = "subjectstaging" . $staging;
        if ( $staging == 1 ) {
          $staginginfo = "(deleted)";
        } elseif ( $staging == 2 ) {
          $staginginfo = "(rejected)";
        }
        elseif ( $staging == 3 ) {
          $staginginfo = "(pending)";
        }
        else {
          $staginginfo = "";
        }
        $this->content .= "<div class='story_container'>";
        $this->content .= "<div class='subject_title " . $stagingclass . "'><a href='index.php?subject=" . $row[ 'fldId' ] . "'>" . $row[ 'fldName' ] . "</a><span class='subjectstatus'>" . $staginginfo . "</span></div>";
        $this->content .= "<div class='blurb'>" . stripslashes( $blurb ) . "</div>";
        if ( $row[ 'totalBlurbs' ] > 1 )$this->content .= "<div class='theresMore'><a href='index.php?subject=".$row['fldId']."'>We've got " . $row[ 'totalBlurbs' ] . " stories about this...</a></div>";
        $this->content .= "</div>";
      }
    } else {
      $this->content = "No results from the query<br><br>" . $this->sql . "<br><br>" . $conn->error;
    }

  }

  function on_page() {
    echo "<div class='alphagrid onpage'>";
    echo "browsing the letter " . $this->letter . "<br>";
    echo "</div>";

    if ( $this->pages > 1 ) { // pagination box if required
      $this->show_pagination( true );
    }
  }

  private function is_valid_pagination( $pag ) {
    #not valid if not an integer. valid if five or over, or -1 for NO PAGINATION. If none of the above, not valid.
    if ( $pag != intval( $pag ) ) return false;
    if ( $pag > 5 ) return true;
    if ( $pag == -1 ) return true;
    return false;
  }

}

class IntroPage extends Page {
  public $pages = 0;
function __construct() {
$this->content = <<<INTROTEXT
<div class='story_container'>
<div class='subject_title'>welcome back to the 2000s</div>
<div class='blurb'>
Remember the internet? That was good, wasn't it? Anything seemed possible, and frequently did! The Law of the Playground enjoyed a period of happy low-level popularity in that time, as a place where people in their 20s and 30s could pick at their psychic scabs by laughing at the shit we did as children.<br><br>
We got turned into a book, and a TV show <em>that had Vic Reeves in it</em>. That's so amazing it almost makes up for the fact that Justin Lee Collins was in it, too. Sadly, nothing's <em>that</em> amazing.<br><br>
I've put the site back up as a read-only archive, and because we've all become better people over the last two decades, please assume a content warning for <em>everything</em>. LotP is a joke-led nostalgic look at the funny/cruel stuff that we did - and had done to us - as children. I've removed a few entries that were never funny, but I was too much of a chuckling edgelord to realise it. But even with that, in among the inspired whimsy and wild naive genius, there's straight-up bullying, ableism, all of the phobias, injustice, sociopathic cruelty, and kwebbers. Enjoy LotP knowing that you're amongst fellow sufferers.</div>
<div class='subject_title'>have you changed anything?</div>
<div class='blurb'>
I'm glad I asked myself that, because I know the answer:<br><br>
--> I've obscured contributor credits, because a few people were getting in touch to say their entry was appearing in prospective employers' job searches.<br><br>
--> Messing around with the all new Shit Filter&trade; will let you view entries we never approved. Even items we deleted. This possible dross won't leap out at you, and you can't directly link to these items. But you'll be thrilled to hear that you can finally see how many people told us that "<a href='index.php?subject=3180'>dad up a chimney</a>" was from Gremlins. It's the largest boost in content since the site began, and the quality is offensively reciprocal.<br><br>
So, have a rummage and revel in nostalgia for a) childhood, and b) a time when the internet wasn't two websites, and your mum wasn't on it.
</div>
INTROTEXT;
  }

  function on_page() {
    echo "";
  }
}

class SubjectPage extends Page {

  public $subject;
  public $content;
  public $subjectID;
  public $subjectTitle;
  public $numberofblurbs;
  public $staging4count = 0;
  public $staging3count = 0;
  public $staging2count = 0;
  public $staging1count = 0;

  function __construct( $subject, $conn ) {
    if ( intval( $subject ) != $subject ) {
      $this->content = "<div class='subject_title'>That's not a good subject, babes. Can you not try doing that?</div>";
      return;
    }
    $sql = "
				select 
				tblblurb.fldId as blurbid,
				tblsubject.fldName as subject,
				tblsubject.fldStagingId as subjectStaging, 
				tblblurb.fldStagingId as blurbStaging,
				tblblurb.fldBlurb as blurb,
				tblsubject.fldId as subjectid,
				tbladminuser.fldFirstName as admin
				from tblsubject
				inner join tblblurb on tblblurb.fldSubjectId = tblsubject.fldId 
				inner join tbladminuser on tbladminuser.fldId = tblblurb.fldAdminUserId
				where tblsubject.fldId = $subject
                and tblblurb.fldStagingId >= " . $_SESSION[ 'filters' ] . " 
				order by tblblurb.fldStagingId DESC, tblblurb.fldCreatedDate ASC";
    #		echo $sql;
    if ( !$res = $conn->query( $sql ) )echo $conn->error;
    #		$row = $res->fetch_assoc();
    #		$showblurb = $this->parse_blurb($row['blurb']);
    #		$this->subjectTitle = $row['subject'];
    #		$this->content = "<div class='subject_title'>".$row['subject']."</div>";
    #		$this->content .= "<div class='blurb blurblist staging".$row['blurbStaging']."'>".$showblurb."</div>";
    #		$staging = "staging".$row['blurbStaging']."count";
    #		$this->$staging++;
    $this->content = "";
    $firsttime = true;
    $stories   = 0;
    while ( $row = $res->fetch_assoc() ) {
      if ( $firsttime ) {
        $this->subjectTitle = $row[ 'subject' ];
        $this->content .= "<div class='subject_title'>" . stripslashes($this->subjectTitle) . "</div>";
        $firsttime = false;
      } else {
        $this->content .= "<hr class='willy staging" . $row[ 'blurbStaging' ] . "'>";
      }
      $showblurb = $row[ 'blurb' ];
      $showblurb = $this->parse_blurb( $showblurb );
      $this->content .= "<div class='blurb blurblist staging" . $row[ 'blurbStaging' ] . "'>" . $showblurb . "</div>";
      $this->content .= "<div class='credits staging" . $row[ 'blurbStaging' ] . "'>";
      $this->content .= "written by " . $this->get_pupils( $row[ 'blurbid' ], $conn );
      $this->content .= ", " . parent::$admincredit[ $row[ 'blurbStaging' ] ] . " " . $row[ 'admin' ];
      if ( $_SESSION[ 'admin' ] == "yes" ) {
        $this->content .= " - <a href='admin.php?blurb=" . $row[ 'blurbid' ] . "'>edit</a>";
      }
      $this->content .= "</div>";
      $this->content .= "<div class='clear'></div>";
      $staging = "staging" . $row[ 'blurbStaging' ] . "count"; // set the variable for the next line to increment
      $stories++;    
    }
    if($stories == 0) { 
        $this -> subjectTitle="there's nothing here for you";  
        $this->content = "<div class='subject_title'>you're better than this</div><div class='blurb'>Either this is a subject id that doesn't exist, in which case would you kindly stop messing about with the URL? Or, there's some unapproved stories hidden in the filth. You can still see them - you just have to adjust your shit filter. There are four levels of shit, so get digging.</div>";
    }
  }

  function on_page() {
    echo "<div class='alphagrid onpage'>today's class:<br>" . strtolower( stripslashes( $this->subjectTitle ) );
    echo "</div><div class='alphagrid hideme'>" . $this->staging4count . " approved ";
    if ( $this->staging4count == 1 )echo "law";
    else echo "laws";
    if ( $this->staging3count > 0 ) {
      ?>
<br>
<span class="yellow"><a  href='#' id='unapproved' onclick="toggleDisplay('staging3', 'unapproved'); return false;">view unapproved</a></span>
<?php
} else {
  echo "<br><span id='unapproved'></span>";
}
if ( $this->staging2count > 0 ) {
  ?>
<br>
<span class="orange"><a href='#' id='disapproved' onclick="toggleDisplay('staging2', 'disapproved'); return false;">view disapproved</a></span>
<?php
} else {
  echo "<br><span id='disapproved'></span>";
}
if ( $this->staging1count > 0 ) {
  ?>
<br>
<span class="red"><a href='#'  id='deleted' onclick="toggleDisplay('staging1', 'deleted'); return false;">view deleted</a></span>
<?php
} else {
  echo "<br><span id='deleted'></span>";
}
echo "</div>";
}

}

class StagingIntro extends Page {

  public $content = "";

  function __construct( $staging ) {
    if ( $staging == 4 ) {
      $this->content = "<div class='subject_title'>Status: Normal</div><div class='blurb'>Everything is as it was ten years ago. Any dips in quality are entirely the fault of the editors. If it's not funny, be kind and just assume it aged poorly. The people who wrote this don't exist any more, and are all being very left wing on Twitter as we speak (except for Mansh). The amount of time between now and writing these memories is greater than the time between writing these memories and the events we were remembering. Next, senility. Then, death.</div>";
      $_SESSION[ 'filters' ] = 4;
    } elseif ( $staging == 3 ) {
      $this->content = "<div class='subject_title'>Status: Pending</div><div class='blurb'>This is LotP Limbo. The foyer of the <em>unapproved</em>. Maybe it was poor quality? Maybe we had nostalgia fatigue. Maybe there was a massive swamp of unfunny shit to wade through, that drained us of our will to edit. You're about to watch Highlander 2, and it IS going to ruin the first film for you. <br><br>Warning: if we never even saw it, then there might be horrible nonsense in here. So, these pages won't be indexed  If you find anything actionably horrible, please contact <a href='http://www.twitter.com/disappointment'>Log on Twitter</a></div>";
      $_SESSION[ 'filters' ] = 3;
    } elseif ( $staging == 2 ) {
      $this->content = "<div class='subject_title'>Status: Inactive</div><div class='blurb'>You are in the Atrium of the Disapproved. These are posts that were rejected. We had a few in-house rules. No 'yeah we did that at our school but it was a lad called henry'. No cruelty without humour, unless it was cruelty so spectacular that it made you actually think. Like, really think. Say 'hmm' and everything. You might find the posts are broken and conversational - that's because we'd pass them around with comments like CAN YOU FIND THE JOKE IN THIS I'M GOING MENNAL. Enjoy?</div>";
      $_SESSION[ 'filters' ] = 2;
    } elseif ( $staging == 1 ) {
      $this->content = "<div class='subject_title'>you are in the deletion zone</div><div class='blurb'>For whatever reason, when Mr. Glanville coded the original version of this site, he decided we'd never delete a thing. Remember how everyone on Parler got their shit ripped even after they went around trying to delete all their racist posts? Well, we've got the same bucket of bollocks going on around here, only it's poorly formed memories about a fat kid you were needlessly mean to. This is absolutely everything in the database. Fill your boots, you absolute masochist.</div>";
      $_SESSION[ 'filters' ] = 1;
    }
    $link = $_SERVER[ 'REQUEST_URI' ];
    while ( $pos = strpos( $link, "staging" ) ) {
      $link = substr( $link, 0, -10 );
    }
    if ( $staging < 4 ) {
      $this->content .= "<hr class='clear'>
                            <div class='subject_title'>
                                watch out for admin chat
                            </div>
                            <div class='blurb'>
                                Because you're about to read stuff that was never intended to be seen, you might also see the editors chatting among ourselves. If you see Edward Cockfingers, he's the imaginary editor we'd throw to with the worst entries. He has <a href='index.php?cockfingers=please'>his very own page</a>.
                                <p class='adminname'>
                                <img src='images/log.png' />
                                Admin chat looks like this. I'm Log, the nice one. All of the other admins have gone now. On the up-side I've got a second monitor these days so I'm rarely not wanking
                                </p>
                            </div>";
    } else {
      $this->content .= "   <hr class='clear'>
                            <div class='subject_title'>
                                cockfingers has left the building
                            </div>
                            <div class='blurb'>
                                With the restoration of normality, Cockfingers covers his face with his hands and jizzes himself into a mist. He won't bother you any more. You can, however, still <a href='index.php?cockfingers=please'>visit him in his house</a>.
                            </div>";
    }
    $this->content .= "<hr><div class='subject_title'>you have been briefed</div><div class='blurb'>Now <a href='$link'>return to the page you were on</a>, bearing in mind that you've just manipulated the timeline, and things might be different.</div></div>";

  }

  function on_page() {
    echo "<div class='alphagrid onpage'>you are wading into stinky waters</div>";
  }
}

class Cockfingers extends Page {
  public $content = "";
  public $page = 1;
  public $pages;

  function __construct( $page, $conn ) {

    $this->page = $page;

    $sql = "select count(*) as full_count
				from tblsubject, tblblurb, tbladminuser
				where tbladminuser.fldId = tblblurb.fldAdminUserId
				and tblsubject.fldId = tblblurb.fldSubjectId
				and tbladminuser.fldId = 5
				and tblsubject.fldStagingId >= " . $_SESSION[ 'filters' ] . "
				and tblblurb.fldStagingId >= " . $_SESSION[ 'filters' ];
    if ( !$res = $conn->query( $sql ) )echo $sql . "<br>" . $conn->error;
    $row = $res->fetch_assoc();
    $this->pages = ceil( $row[ 'full_count' ] / parent::$pagination );
#    echo $row[ 'full_count' ] . " entries, " . $this->pages . " pages";

    $sql = "select tblsubject.fldId, tblsubject.fldName as subject, tblblurb.fldId as blurbId, tblblurb.fldBlurb as blurb
				from tblsubject, tblblurb, tbladminuser
				where tbladminuser.fldId = tblblurb.fldAdminUserId
				and tblsubject.fldId = tblblurb.fldSubjectId
				and tbladminuser.fldId = 5
				and tblsubject.fldStagingId >= " . $_SESSION[ 'filters' ] . "
				and tblblurb.fldStagingId >= " . $_SESSION[ 'filters' ] . "
				order by tblblurb.fldModifiedDate desc
				limit " . ( $this->page - 1 ) * self::$pagination . ", " . self::$pagination;
    if ( !$res = $conn->query( $sql ) )echo $sql . "<br>" . $conn->error;

    while ( $row = $res->fetch_assoc() ) {
      if ( !isset( $this->pages ) )$this->pages = $row[ 'full_count' ];
      $showblurb = $row[ 'blurb' ];
      $showblurb = $this->parse_blurb( $showblurb );
      $this->content .= "<div class='subject_title'>" . $row[ 'subject' ] . "</div>";
      $this->content .= "<div class='blurb blurblist'>" . $showblurb . "</div>";
      if($_SESSION['admin'] == "yes") $this->content .= "<div class='blurb'><a href='admin.php?blurb={$row['blurbId']}'>edit this</a><div>";
      $this->content .= "<hr>";
    }
  }

  function on_page() {
    echo "<div class='alphagrid onpage'>vous habitez chez cockfingers aujourd'hui</div>";
    $this->show_pagination();
  }
}

class PupilPage extends Page {
  public $content = "";
  public $pupil;

  function __construct( $pupil, $conn ) {
      $pupil = intval($pupil);
      if($pupil < 1) {
           $this->content = "<div class='subject_title'>Pupil doesn't exist</div>";
      } else {
          $detailsql = "select concat(fldFirstName, \" \", fldLastName) as wholename from tblpupil where fldId = {$pupil} limit 1";
          $detailres = $conn->query($detailsql); 
          $row = $detailres->fetch_assoc();
          $this->pupil = $row['wholename'];
          
        
          $reportsql = "select tblblurb.fldStagingId as staging, count(*) as count from tblpupilblurbmap
                                inner join tblblurb on tblpupilblurbmap.fldBlurbId = tblblurb.fldId
                                where tblpupilblurbmap.fldPupilId = {$pupil}
                                group by tblblurb.fldStagingId
                                order by staging desc";
          $reportsql = $conn->query($reportsql);

          if($reportsql->num_rows > 0) {
              $this->content .= "<table class='report'><tr class='subject_title'><th colspan='2'>Report for {$this->pupil}</th></tr>";
              $scoretotal = 0; $scorecount = 0;
              while($row = $reportsql->fetch_assoc()) {
                  $this->content .= "<tr class='blurb'><td>".parent::$stagingdescription[$row['staging']]." stories";
                  if($_SESSION['filters'] > $row['staging']) $this->content .= " (hidden) ";
                  $this->content .= "</td><td>".$row['count']."</td></tr>";
                  $scoretotal += parent::$statingscore[$row['staging']] * $row['count'];
                  $scorecount += $row['count'];
              }
              $scoreavg = $scoretotal / $scorecount;
              if($scoreavg > 4) {$summary = "Perfectly Exquisite"; }
              elseif($scoreavg > 3) { $summary = "Reprehensible Swot"; }
              elseif($scoreavg >= 2) { $summary = "Exemplary Child"; }
              elseif($scoreavg >= 1) { $summary = "Shows promise"; }
              elseif($scoreavg >= 0) { $summary = "Could Try Harder"; }
              elseif($scoreavg < 1) { $summary = "Mean Boy"; }
              elseif($scoreavg < 3) { $summary = "Lurgy-Infested Trevor"; }

              $this->content .= "<tr class='blurb'><td>Summary</td><td>{$summary}</td></tr>";
              $this->content .= "</table><hr>";
          }
      
         $sql = "select tblsubject.fldId as subjectid, tblsubject.fldName as subjectname, tblblurb.fldBlurb as blurb, tblblurb.fldStagingID as staging
                                from tblblurb
                                inner join tblpupilblurbmap on tblpupilblurbmap.fldBlurbId = tblblurb.fldId
                                inner join tblsubject on tblsubject.fldId = tblblurb.fldSubjectId
                                where tblpupilblurbmap.fldPupilId = {$pupil}
                                and tblblurb.fldStagingId >= {$_SESSION['filters']}";
          if(!$res = $conn->query($sql)) echo $conn->error;
          while ($row = $res->fetch_assoc()) {
              $this->content .= "<div class='story_container'><div class='subject_title subjectstaging{$row['staging']}'><a href='index.php?subject={$row['subjectid']}'>{$row['subjectname']}</a></div>";
              $this->content .= "<div class='blurb'>".$this->parse_blurb($row['blurb'])."</div><hr>";
          }
      }
  }

  function on_page() {
      echo "<div class='alphagrid onpage'>report card for {$this->pupil}</div>";
  }
}

class SearchPage extends Page {
    public $content = "";
    public $searchterm;
    function __construct($search, $conn) {
        $this->page = 1;
        $this->pages = 1;
        $this->searchterm = $search;
        
        $stmt = $conn->prepare("SELECT tblsubject.fldId as subjectid, tblblurb.fldBlurb as blurb, tblsubject.fldName as subjectname
                                FROM tblblurb INNER JOIN tblsubject on tblsubject.fldId = tblblurb.fldSubjectId 
                                WHERE 
                                ( MATCH (tblblurb.fldBlurb) AGAINST (? IN NATURAL LANGUAGE MODE) 
                                OR MATCH (tblsubject.fldName) AGAINST (? IN NATURAL LANGUAGE MODE) )
                                AND tblblurb.fldStagingId >= ? LIMIT 25");
        if(!$stmt->bind_param("ssi", $this->searchterm, $this->searchterm, $_SESSION['filters'])) echo "Bind failed";
        if(!$stmt->execute()) echo "Execute failed";
        $res = $stmt->get_result();
        $stmt->close();

        #        $stmt = $conn->prepare("SELECT tblsubject.fldId as subjectid, tblblurb.fldBlurb as blurb, tblsubject.fldName as subjectname
            
#                                FROM tblblurb INNER JOIN tblsubject on tblsubject.fldId = tblblurb.fldSubjectId WHERE MATCH (fldBlurb) AGAINST (? IN NATURAL LANGUAGE MODE) LIMIT 10");
#            if($stmt==false) die("PREPARE FAILED<br>".$conn->error);
#        $bindcheck = $stmt->bind_param("s", $search);
#            if(false===$bindcheck) $this->content .= "<br>blurb parameter bind failed: ".$blurbsql->error;
#        $res = $stmt->execute();  
#            if(false===$res) $this->content .= "<br>blurb execute failed: ".$blurbsql->error;


       $sql2 = "INSERT INTO tblsearchhistory ( fldSearchTerm, fldIP ) VALUES ( '{$search}', '{$_SERVER['REMOTE_ADDR']}' )";
      if(!$res2 = $conn->query($sql2)) echo $sql2."<br>".$conn->error;
       $insertid = $conn->insert_id;
    
        if($res->num_rows >= 1) {
            $this->content = "";
            while($row = $res->fetch_assoc()) {
                $row['blurb'] = strip_tags($this->parse_blurb($row['blurb']));
                $this->content .= "<div class='subject_title'><a href='index.php?subject={$row['subjectid']}&search={$insertid}'>{$row['subjectname']}</a></div>";
                $this->content .= "<div class='blurb'>".$this->highlight($row['blurb'], $this->searchterm)."</div>";
                $this->content .= "<hr>";
            }
        }
        else {
            $this->content = "<div class='subject_title'>no results for {$this->searchterm}</div><div class='blurb'>try searching for something more obvious, like <em>fart</em> or <em>gay</em>. We've got loads of stuff about that.</div>";
        }
#        $stmt->close();       
 #       $pstm->close();
    }
    
    function highlight($blurb, $words) {
        $wordlist = explode(" ", $words);
        foreach($wordlist as $word) {
            $blurb = str_ireplace($word, "<span class='highlight'>".$word."</span>", $blurb);
        }
        return $blurb;
    }
    
    function on_page () {
        echo "<div class='alphagrid onpage'>looking for:<br>".$this->searchterm."</div>";
    }
}

class LatestPage extends Page {

    public $content;
    public $sql;
    public $page;

    function __construct($conn, $page = 1) {
        $this->page = intval($page);
        $this->pages = 20;
        $this->sql = "select tblblurb.fldId as blurbId,
			                 tblblurb.fldBlurb as blurb,
			                 tblsubject.fldId as subjectId,
                             tblsubject.fldName as subjectName,
                             tblblurb.fldModifiedDate as lastmodified
                             from tblsubject
                             inner join tblblurb on tblblurb.fldSubjectId = tblsubject.fldId
                                WHERE tblsubject.fldStagingId >= $this->stagingFilter
                                And tblblurb.fldStagingId >= $this->stagingFilter
                                order by tblblurb.fldModifiedDate DESC
                                limit " . ( $this->page - 1 ) * self::$pagination . ", " . self::$pagination;
        if(!$res = $conn->query($this->sql)) echo "Failed - ".$this->sql."<br>".$conn->error;
        $this->content = "";
        while($row = $res->fetch_assoc()) {
            $this->content .= "<div class='subject_title'><a href='index.php?subject={$row['subjectId']}'>".stripslashes($row['subjectName'])."</a></div>";
            $this->content .= "<div class='blurb'>".$this->parse_blurb($row['blurb'])."</div>";
            $this->content .= "<hr>";
        }
    }
    function on_page() {
        echo "<div class='alphagrid'>showing the latest edits</div>";
    }
}

class RandomPage extends Page {

    public $content;
    public $sql; 
    function __construct($conn) {
        $this->page = 1;
        $this->pages = 1;
        $this->sql = "select tblblurb.fldId as blurbId,
			                 tblblurb.fldBlurb as blurb,
			                 tblsubject.fldId as subjectId,
                             tblsubject.fldName as subjectName,
                             tblblurb.fldModifiedDate as lastmodified
                             from tblsubject
                             inner join tblblurb on tblblurb.fldSubjectId = tblsubject.fldId
                                WHERE tblsubject.fldStagingId >= $this->stagingFilter
                                And tblblurb.fldStagingId >= $this->stagingFilter
                                order by rand()
                                limit 10";
        if(!$res = $conn->query($this->sql)) echo "Failed - ".$this->sql."<br>".$conn->error;
        $this->content = "";
        while($row = $res->fetch_assoc()) {
            $this->content .= "<div class='subject_title'><a href='index.php?subject={$row['subjectId']}'>".stripslashes($row['subjectName'])."</a></div>";
            $this->content .= "<div class='blurb'>".$this->parse_blurb($row['blurb'])."</div>";
            $this->content .= "<hr>";
        }
    }
    function on_page() {
        echo "<div class='alphagrid'>10 random stories for you xxx</div>";
    }
}
?>
