<?php
     
    include_once( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
    include_once( PLOG_CLASS_PATH."class/plugin/pluginmanager.class.php" );
     
    /**
    * Plugin that generates a form that is used to give a posting a rating
    * or score as a way of identifying a blog's "best posts." Originally intended
    * to be used in conjunction with the PluginAuthentication plugin to give only
    * the person posting to the blog the privilege to identify the "best posts."
    *
    * It is exported with "bestposts" as its identifier.
    *
    * Usage:
    *
    *   {assign var=poster value=$post->getUserInfo()}
    *   {assign var=articleId value=$post->getId()}
    *   {assign var=categoryId value=$post->getCategoryId()}
    *   {if $auth->posterIsLoggedIn($poster)}
    *   Rating: {$bestposts->displayForm($articleId,$categoryId))}
    *   {/if}
    */
    class PluginBestPosts extends PluginBase {
         
        function PluginBestPosts() {
            $this->PluginBase();
             
            $this->desc = "Generates a form that is used to give a posting a rating
                or score as a way of identifying a blog's &quot;best posts.&quot;
                Can be used in conjunction with PluginAuthentication to give only
                the person posting to the blog the privilege to identify the
                &quot;best posts.&quot;
                Usage:<br/><br/>
                {assign var=poster value=\$post->getUserInfo()}<br/>
                {assign var=articleId value=\$post->getId()}<br/>
                {assign var=categoryId value=\$post->getCategoryId()}<br/>
                {if \$auth->posterIsLoggedIn(\$poster)}<br/>
                Rating: {\$bestposts->displayForm(\$articleId,\$categoryId)}<br/>
                {/if}";
            $this->author = "Daniel Kehoe <kehoe@fortuity.com>";
             
            $this->connectDb();
            if ($this->_databaseExists() == true ) {
                $this->_setDefaultConfigMessage();
                return true;
            } else {
                $this->_setCreateDbConfigMessage();
                return true;
            }
        }
         
        /**
        * Returns a form that can be used to give a score or rating to a blog entry.
        *
        * @param article ID (passed from the template)
        * @param category ID (passed from the template)
        * @return HTML string to generate a form
        */
        function displayForm($articleId, $categoryId) {
            $form = '<form action="admin.php" method="post" name="bestposts_form">
                <input type="text" size="5" name="bestposts_score" value=""/>
                <input type="hidden" name="bestposts_articleId" value="'.$articleId.'"/>
                <input type="hidden" name="bestposts_categoryId" value="'.$categoryId.'"/>
                <input type="hidden" name="pluginId" value="bestposts"/>
                <input type="hidden" name="op" value="updatePluginConfig"/>
                <input type="submit" name="bestposts_action" value="Submit"/>
                </form>';
            return $form;
        }
         
        /**
        * Handles submission of the rating form, recording a score for the blog entry.
        *
        * @param form elements
        * @return always true
        */
        function configure($params) {
            $action = $params->getValue('bestposts_action');
            $score = $params->getValue('bestposts_score');
             
            switch ($params->getValue('bestposts_action')) {
                case 'Submit':
                {
                    if ($this->_setScore($params) == true ) {
                        return true;
                    } else {
                        return false;
                    }
                }
                break;
                 
                case 'Create':
                {
                    if ($this->_createDataTable() == true ) {
                        return true;
                    } else {
                        return false;
                    }
                }
                break;
                 
                default:
                {
                    if ($this->_databaseExists() == true ) {
                        $this->_setDefaultConfigMessage();
                        return true;
                    } else {
                        $this->_setCreateDbConfigMessage();
                        return true;
                    }
                }
                 
            }
             
        }
         
        /**
        * This message shows in the admin interface if the database is set up properly.
        *
        * @private
        */
        function _setDefaultConfigMessage() {
            $this->configMessage = '&quot;Best Posts&quot; plugin has been configured.';
        }
         
        /**
        * This message shows in the admin interface after a score has been submitted.
        *
        * @private
        */
        function _setAcknowledgementConfigMessage($score) {
            $this->configMessage = 'Score set to '.$score.'.';
        }
         
        /**
        * This message shows in the admin interface if the necessary data table does not exist.
        *
        * @private
        */
        function _setCreateDbConfigMessage() {
            $this->configMessage = '
                <form name="pluginConfiguration" method="POST" action="admin.php">
                <strong>No &quot;Best Posts&quot; table found... shall I create it?</strong><br>
                <br/>
                <input type="hidden" name="pluginId" value="bestposts"/>
                <input type="hidden" name="op" value="updatePluginConfig"/>
                <input type="submit" name="bestposts_action" value="Create"/>
                <input type="submit" name="bestposts_action" value="Cancel"/>
                </form>
                ';
        }
         
        /**
        * Add a score or rating to the database for this article.
        *
        * @private
        * @return true unless the operation fails
        */
        function _setScore($params) {
            // Get the config values
            $config = new Config();
            $dbPrefix = $config->getValue('db_prefix');
            $table = $dbPrefix.'scores';
             
            // fetch parameters coming from the user
            $score = $params->getValue('bestposts_score');
            $articleId = $params->getValue('bestposts_articleId');
            $categoryId = $params->getValue('bestposts_categoryId');
             
            // check that parameter is set
            if (!isset($score)) {
                $this->setConfigurationErrorMessage('No score or rating value was submitted.');
                return false;
            }
             
            // get the current blog_id
            $blogId = $this->blogInfo->getId();
             
            // if everything is ok, save the score
            $query = "INSERT INTO $table (blog_id, category_id, article_id, score) VALUES ('$blogId','$categoryId','$articleId','$score')";
            $this->db->Execute($query);
            $this->_setAcknowledgementConfigMessage($score);
            return true;
        }
         
        /**
        * Check if the necessary data table exists.
        *
        * @private
        * @return true if the database exists
        */
        function _databaseExists() {
            // Get the config values
            $config = new Config();
            $dbPrefix = $config->getValue("db_prefix");
            $table = $dbPrefix.'scores';
            $query = 'SELECT count(*) FROM '.$table;
            if ($this->db->Execute($query)) {
                return true;
            } else {
                $this->setConfigurationErrorMessage($table.' table does not exist.');
                return false;
            }
        }
         
        /**
        * Create the necessary data table using ADOdb's data dictionary features.
        *
        * @private
        * @return always true
        */
        function _createDataTable() {
            // Get the config values
            $config = new Config();
            $dbPrefix = $config->getValue('db_prefix');
            $table = $dbPrefix.'scores';
            // for background, see http://phplens.com/lens/adodb/docs-datadict.htm
            $fields = "
                blog_id I(10) NOTNULL,
                category_id I(10) NOTNULL,
                article_id I(10) NOTNULL,
                score I(5) NOTNULL
                ";
            // create a data dictionary object
            $dict = NewPDbDataDictionary($this->db);
            // Checks to see if table exists, if table does not exist,
            // adds the table. If table exists, generates appropriate
            // ALTER TABLE MODIFY COLUMN commands if field already exists,
            // or ALTER TABLE ADD $column if field does not exist.
            $sqlarray = $dict->ChangeTableSQL($table, $fields);
            $dict->ExecuteSQLArray($sqlarray);
            $this->configMessage = 'Created new data table '.$table.'.';
            return true;
        }
         
    }
     
    PluginManager::registerPlugin("bestposts", "PluginBestPosts" );
?>
