<?php
    include_once( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
    include_once( PLOG_CLASS_PATH."class/plugin/pluginmanager.class.php" );

    define( "DEFAULT_HAIKUS_FILENAME", "./haiku/haiku.sql" );

    /**
     * Implementation of a very simple haiku plugin
     */
    class PluginHaiku extends PluginBase {

        function PluginHaiku()
        {
        $this->PluginBase();

            $this->desc = "
            This plugin will generate a random Haiku<br/>
        <br/>
        Usage (Place these somewhere in your favorite template:<br/>
            &nbsp;&nbsp;To Display The Haiku:
            &nbsp;&nbsp;{\$haiku->getHaiku()}<br/>
            &nbsp;&nbsp;To Display The Possible Permutations:
            &nbsp;&nbsp;{\$haiku->getHaikuPermutations()}<br/>
            &nbsp;&nbsp;To Display Haiku Status:
            &nbsp;&nbsp;{\$haiku->getHaikuStats()}<br/>
        ";
            $this->author = "Darren Greer";

        // connect to the database
        $this->connectDb();

        if( $this->checkHaikuDatabase($params) == true ) {
          $this->setDefaultConfigMessage();
        } else {
          $this->setCreateConfigMessage();
        }

        }

        function getHaiku()
        {
      // we need to take into account that plog has definable
      // prefixes for the database
      // so it is not sure that the user will have chosen 'plog_'
      // as the prefix... could be anything else!!
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      // get the current blog_id
          $blogId = $this->blogInfo->getId();

      // First 5 syllable line
          $query = "SELECT * FROM {$dbPrefix}haiku where haiku_syl=5 and (haiku_blog_id = $blogId or haiku_blog_id = 0 ) order by rand() LIMIT 1";
      $result = $this->db->Execute( $query );
      if( !$result ) 
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "Could Not Get A 5 Syllable Entry" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);
          $return = "<i> $haiku_text </i><b> <=> </b>";

      // 7 syllable line
          $query = "SELECT * FROM {$dbPrefix}haiku where haiku_syl=7 and (haiku_blog_id = $blogId or haiku_blog_id = 0 ) order by rand() LIMIT 1";
      $result = $this->db->Execute( $query );
      if( !$result )
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "Could Not Get A 7 Syllable Entry" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);
          $return = $return . "<i> $haiku_text </i><b> <=> </b>";

      // Second 5 syllable line
          $query = "SELECT * FROM {$dbPrefix}haiku where haiku_syl=5 and (haiku_blog_id = $blogId or haiku_blog_id = 0 ) order by rand() LIMIT 1";
      $result = $this->db->Execute( $query );
      if( !$result )
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "Could Not Get A 5 Syllable Entry" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);
          $return = $return . "<i> $haiku_text </i>";
          return $return;
        }

        function getHaikuPermutations()
        {
      // we need to take into account that plog has definable
      // prefixes for the database
      // so it is not sure that the user will have chosen 'plog_'
      // as the prefix... could be anything else!!
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      // get the current blog_id
          $blogId = $this->blogInfo->getId();

      // Get Possible Combinations
          $query = "SELECT count(*) as count5 FROM {$dbPrefix}haiku where haiku_syl=5 and (haiku_blog_id = $blogId or haiku_blog_id = 0 )";
      $result = $this->db->Execute( $query );
      if( !$result )
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "No Records Found" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);

          $query = "SELECT count(*) as count7 FROM {$dbPrefix}haiku where haiku_syl=7 and (haiku_blog_id = $blogId or haiku_blog_id = 0 )";
      $result = $this->db->Execute( $query );
      if( !$result )
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "No Records Found" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);

      $total_combs = ($count5 * $count7 * $count5);
      $return = "<b>$total_combs</b>";

          return $return;
        }

        function getHaikuStats()
        {
      // we need to take into account that plog has definable
      // prefixes for the database
      // so it is not sure that the user will have chosen 'plog_'
      // as the prefix... could be anything else!!
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      // get the current blog_id
      $blogId = $this->blogInfo->getId();

      // Get Possible Combinations
          $query = "SELECT count(*) as count5 FROM {$dbPrefix}haiku where haiku_syl=5 and (haiku_blog_id = $blogId or haiku_blog_id = 0 )";
      $result = $this->db->Execute( $query );
      if( !$result )
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "No Records Found" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);

          $query = "SELECT count(*) as count7 FROM {$dbPrefix}haiku where haiku_syl=7 and (haiku_blog_id = $blogId or haiku_blog_id = 0 )";
      $result = $this->db->Execute( $query );
      if( !$result )
        return false;
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "No Records Found" );
        return false;
      }
      $row=$result->FetchRow();
          extract($row);

      $return = "5 Syllable: <b>$count5</b><br/>";
      $return = $return . "7 Syllable: <b>$count7</b>";

          return $return;
        }

        function configure( $params )
        {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      $haikuFunction = $params->getValue( "Update" );

      if($haikuFunction == 'Add') {

        // execute the add function
        if( $this->addHaiku($params) == true ) {
          return true;
        } else {
          return false;
        }

      } else if( $haikuFunction == "Search" ) {

        // execute the search function
        if( $this->searchHaiku($params) == true ) {
          return true;
        } else {
          return false;
        }

      } else if( $haikuFunction == "Update" ) {

        // execute the update function
        if( $this->updateHaiku($params) == true ) {
          return true;
        }    else {
          return false;
        }

      } else if( $haikuFunction == "Delete" ) {

        // execute the delete function
        if( $this->deleteHaiku($params) == true ) {
          return true;
        }    else {
          return false;
        }

      } else if( $haikuFunction == "Edit" ) {

        // execute the edit function
        if( $this->editHaiku($params) == true ) {
          return true;
        }    else {
          return false;
        }

      } else if( $haikuFunction == "Create" ) {

        // execute the create function
        if( $this->createHaikuDatabase($params) == true ) {
          return true;
        }    else {
          return false;
        }

      } else {
        if( $this->checkHaikuDatabase($params) == true ) {
          $this->setDefaultConfigMessage();
          return true;
        } else {
          $this->setCreateConfigMessage();
          return true;
        }
      }

        }

        function setCreateConfigMessage()
    {
      $this->configMessage = '
      <form name="haikuPluginConfiguration" method="POST" action="admin.php">
        <strong>No Haiku Table Found ... Shall I Create It?</strong><br>
        <br/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Create"/>
        <input type="submit" name="Update" value="Cancel"/>
      </form>
      ';
    }

        function setDefaultConfigMessage()
    {
      $this->configMessage = '
      <form name="haikuPluginConfiguration" method="POST" action="admin.php">
        <strong>Enter Haiku Below</strong><br>
        Haiku Text: <input type="text" size="50" name="haikuPluginText" value=""/><br/>
        Haiku Syllable: <select name="haikuPluginSyllable">
          <option value="5">5</option>
          <option value="7">7</option>
        </select>
        <br/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Add"/>
      </form>
      <hr>
      <form name="haikuPluginConfiguration" method="POST" action="admin.php">
        Search: <input type="text" size="50" name="haikuSearch" value=""/><br/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Search"/>
      </form>
      ';
    }

        function setAddConfigMessage()
    {
      $this->configMessage = '
      <form name="haikuPluginConfiguration" method="POST" action="admin.php">
        <strong>Enter Haiku Below</strong><br>
        Haiku Text: <input type="text" size="50" name="haikuPluginText" value=""/><br/>
        Haiku Syllable: <select name="haikuPluginSyllable">
          <option value="5">5</option>
          <option value="7">7</option>
        </select>
        <br/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Add"/>
      </form>
      ';
    }

        function setSearchConfigMessage()
    {
      $this->configMessage = $this->configMessage . '
      <form name="haikuPluginConfiguration" method="POST" action="admin.php">
        Search: <input type="text" size="50" name="haikuSearch" value=""/><br/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Search"/>
      </form>
      ';
    }

        function setEditConfigMessage($row)
    {
          extract($row);
      $this->configMessage = '
      <form name="haikuPluginConfiguration" method="POST" action="admin.php">
        <strong>Edit Haiku Below</strong><br>
        Haiku Text <i>['.$haiku_syl.']</i>: <input type="text" size="50" name="haikuPluginText" value="'.$haiku_text.'"/><br/>
        <br/>
        <input type="hidden" name="haikuId" value="'.$haiku_id.'"/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Update"/>
        <input type="submit" name="Update" value="Cancel"/>
      </form>
      ';
    }

    function searchHaiku( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      // Add the add haiku form
      $this->setAddConfigMessage();
      $this->configMessage = $this->configMessage . "<hr>\n";

      // What are we searching for?
      $haikuSearch = $params->getValue( "haikuSearch" );

      // Execute the query
      $blogId = $this->blogInfo->getId();
          $query = "SELECT * FROM {$dbPrefix}haiku where haiku_text like '%$haikuSearch%' and (haiku_blog_id = $blogId or haiku_blog_id = 0)";
      $result = $this->db->Execute( $query );
      if( !$result ) {
        $this->setConfigurationErrorMessage( "No Results" );
        return false;
      }
      if( $result->RecordCount() == 0 )
        return false;
      // Loop through the rows and print out the results
      while( $row = $result->FetchRow($result)) {
            extract($row);
        $this->configMessage = $this->configMessage . 
        '<form name="haikuPluginConfiguration" method="POST" action="admin.php"><i>['.
        $haiku_syl . ']</i>&nbsp;' . $haiku_text . '
        <input type="hidden" name="haikuId" value="'.$haiku_id.'"/>
        <input type="hidden" name="pluginId" value="haiku"/>
        <input type="hidden" name="op" value="updatePluginConfig"/>
        <input type="submit" name="Update" value="Edit"/>
        <input type="submit" name="Update" value="Delete"/>
        </form>
        ';
      }

      $this->configMessage = $this->configMessage . "<br/><hr>\n";
      $this->setSearchConfigMessage();

      return true;
    }

    function updateHaiku( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      $haikuId = $params->getValue( "haikuId" );
      $haikuPluginText = $params->getValue( "haikuPluginText" );

      // Update the entry    
          $query = "UPDATE {$dbPrefix}haiku set haiku_text = '{$haikuPluginText}' where haiku_id={$haikuId}";
      if( $this->db->Execute( $query ) ) {
        return true;
      } else {
        $this->setConfigurationErrorMessage( "Record Not Updated" );
        return false;
      }

      return true;
    }

    function deleteHaiku( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      $haikuId = $params->getValue( "haikuId" );

      // Delete the entry    
          $query = "DELETE FROM {$dbPrefix}haiku where haiku_id={$haikuId}";
      if( $this->db->Execute( $query ) ) {
        return true;
      } else {
        $this->setConfigurationErrorMessage( "Record Not Found" );
        return false;
      }

      return true;
    }

    function editHaiku( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      $haikuId = $params->getValue( "haikuId" );

      // Grab the Haiku
          $query = "SELECT * FROM {$dbPrefix}haiku where haiku_id={$haikuId}";
      $result = $this->db->Execute( $query );
      if( !$result ) {
        $this->setConfigurationErrorMessage( "Record Not Found" );
        return false;
      }
      if( $result->RecordCount() == 0 ) {
        $this->setConfigurationErrorMessage( "Record Not Found" );
        return false;
      }
      $row = $result->FetchRow($result);

      $this->setEditConfigMessage($row);

      return true;
    }

    function addHaiku( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

          // fetch parameters coming from the user
      $haikuParameter = $params->getValue( "haikuPluginText" );
      $syllableParameter = $params->getValue( "haikuPluginSyllable" );

      // check that they are valid
      if( $haikuParameter == "" || $syllableParameter == "" ) {
        // If not valid, tell the plugin manager (by returning false, and set error)
        $this->setConfigurationErrorMessage( "You need to enter the Haiku text, and select a syllable entry" );
        return false;
      }

      // get the current locale
      $locale = $this->blogSettings->getValue( "default_locale" );

      // verify locale was retrieved
      if( $locale == "" )
        $locale = "en_UK";
    
      // get the current date/time
      $l = new Locale($locale);
      $t = new Timestamp($your_sql_date);
      $dateString = $l->formatDate($t, "%Y-%m-%d %H:%M:%S");

      // get the current blog_id and user_id
      $blogId = $this->blogInfo->getId();
          $userId = $this->userInfo->getId();
      $ownerId = $this->blogInfo->getOwner();

      // if everything is ok, save the Haiku
          $query = "INSERT INTO {$dbPrefix}haiku (haiku_syl, haiku_text, haiku_date, haiku_owner_id, haiku_blog_id) VALUES ('$syllableParameter','$haikuParameter','$dateString','$userId','$blogId')";
      $this->db->Execute( $query );
    
      return true;
    }

    function createHaikuDatabase( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

      // Create the Haiku Database
          $query = "
        CREATE TABLE {$dbPrefix}haiku (
        haiku_id int(11) NOT NULL auto_increment,
        haiku_syl int(11) NOT NULL default '0',
        haiku_text varchar(255) NOT NULL default '',
        haiku_date datetime NOT NULL default '0000-00-00 00:00:00',
        haiku_owner_id int(11) NOT NULL default '0',
        haiku_blog_id int(11) NOT NULL default '0',
        UNIQUE KEY haiku_text (haiku_text),
        UNIQUE KEY haiku_id (haiku_id)
        )
      ";
      if( $this->db->Execute( $query ) ) {
        $this->insertDefaultHaikus();
        $this->setDefaultConfigMessage();
        return true;
      } else {
        $this->setConfigurationErrorMessage( "Could Not Create Table" );
        return false;
      }

      return true;
    }

    function insertDefaultHaikus()
    {
    	// if the file does not exists or if it's not readable, forget about it
    	if( !File::isReadable( DEFAULT_HAIKUS_FILENAME ))
        	return true;

        // otherwise, import it and add the haikus to the db
        $blogId = $this->blogInfo->getId();
        include_once( DEFAULT_HAIKUS_FILENAME );

        foreach( $haikus as $haiku ) {
        	print("adding ".$haiku."<br/>");
        	$this->db->Execute( $haiku );
        }

        return true;
    }

    function checkHaikuDatabase( $params )
    {
             // Get the config values
      $config = new Config();
      $dbPrefix = $config->getValue( "db_prefix" );

          $query = "SELECT count(*) FROM {$dbPrefix}haiku";
      if($this->db->Execute( $query )) {
        return true;
      } else {
        $this->setConfigurationErrorMessage( "DB Does Not Exist" );
        return false;
      }
    }

    }

    PluginManager::registerPlugin( "haiku", "PluginHaiku" );
?>
