<?php

include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );

/**
* schema of the table, so that we can tell ADOdb to create it
* automatically for us
*/
/*
define( ATOM_PASSWORDS_DB_SCHEMA,
        "user_id I(10) NOTNULL,
            password C(32) NOTNULL DEFAULT ''" );
*/

             
class Shoutbox extends Model {

    var $blogId;
    var $shoutsResult;
    var $resultCounter;
    var $config;
    var $mail_alert;
    var $max_length;
    var $shouts_per_view;
    var $default_nick;
    var $default_shout;
    var $protected_nicks;
    var $protection_password;
    var $current_page;
    
    var $blogSettings;

    function Shoutbox($blogId, $blogSettings) {
        $this->blogSettings = $blogSettings;
    
        /* Modelize it! */
        $this->Model();

        /* Check Setup */
        $this->checkTables();
    
        /* Initialization */
        $this->blogId = $blogId;

        $this->mail_alert = $blogSettings->getValue("plugin_shoutbox_mail_alert");
        $this->max_length = $blogSettings->getValue( "plugin_shoutbox_max_length");
        $this->shouts_per_view = $blogSettings->getValue( "plugin_shoutbox_shouts_per_view");

        $this->default_nick = $blogSettings->getValue( "plugin_shoutbox_default_nick");
        $this->default_shout = $blogSettings->getValue( "plugin_shoutbox_default_shout");

        $this->protected_nicks = $blogSettings->getValue( "plugin_shoutbox_protected_nicks");
        $this->protection_password = $blogSettings->getValue( "plugin_shoutbox_protection_password");

        //Connections and blog data
        //$this->connectDb();
        //$this->blogSettings = new Config();
        //$this->dbPrefix = $this->blogSettings->getValue( "db_prefix" );
        //$this->blogId = $this->blogInfo->getId();
    }

    
    ###########################################################
    # Database setup section. To be migrated to ADODB, but for the moment I can't get
    # it working :(
    /**
    * @private
    * Makes sure that the plog_atom_password table is there
    */
    function checkTables()
    {
	/* Maybe some day :( 
	$schema = "shout_id I(11) AUTOINCREMENT, blog_id I(11) NOTNULL, nickname C(255) NOTNULL, shout_text C(255) NOTNULL, shout_date T NOTNULL";

        $tableName = $this->getPrefix() . "shoutbox_shouts";

        $dict = NewDataDictionary( $this->_db );
        $sqlArray = $dict->ChangeTableSQL( $tableName, $schema);
        $result = $dict->ExecuteSQLArray( $sqlArray );
	if(!$result)
		die("No result :(" . $schema);
	else
		echo("Seems ok ". print_r($result) . " $schema<br>");
 	*/
    }

    function checkTableExists() {
            $dbPrefix = $this->getPrefix();
            $sql = "SELECT * FROM {$dbPrefix}shoutbox_shouts";
            if( !$this->_db->Execute($sql) ) {
                return false;
            }
            return true;
        }

        function createTable() {
             $dbPrefix = $this->getPrefix();
             
            $sql = "SELECT * FROM {$dbPrefix}shoutbox_shouts";
            if( !$this->_db->Execute($sql) ) {
              // Make new setup
              $sql = "
CREATE TABLE {$dbPrefix}shoutbox_shouts (
    shout_id INT(11) NOT NULL auto_increment,
    blog_id INT(11) NOT NULL,
    nickname TEXT NOT NULL,
    shout_text TEXT NOT NULL,
    shout_date DATETIME NOT NULL,
    UNIQUE KEY cashout_id (shout_id)
)
";
                if( !$this->_db->Execute($sql) ) {
                    die("The database setup failed!<br> <pre>". $sql . '</pre>');
                }
            }
        }
    

    function nextShout() {
        if(!$this->shoutsResult) {
            $sql =  "SELECT * FROM " . $this->getPrefix() . "shoutbox_shouts ";
            $sql .= "WHERE blog_id =  {$this->blogId} ORDER BY shout_date DESC ";
            if(!$this->current_page)
                $this->current_page = 0;
            $offset = $this->current_page * 15;
            $maxShouts = 15;
            $sql .= "LIMIT $offset, $maxShouts";
            $this->shoutsResult = $this->Execute($sql);
            if(!$this->shoutsResult)
                return false;
        }

        $shout = $this->shoutsResult->FetchRow();
        if(!$shout) {
            $this->resultCounter = 0;
            $this->shoutsResult = false;
            return false;
        }
        $this->resultCounter++;

        $shout['shout_date'] = Date("d/m/Y G:i", strtotime($shout['shout_date']));

        return $shout;
    }

    function getShoutsArray($maxShouts = false) {
        $shouts = array();
        while($shout = $this->nextShout($maxShouts))
            $shouts[] = $shout;

        return $shouts;
    }

    function addShout($nickname, $shoutText) {
        $nickname = strip_tags($nickname);

        $protected_nicks = $this->protected_nicks;
        $protection_password = $this->protection_password;

        //echo("Controllo :$protection_password contro $nickname<br>");
        $usesProtectedNick = false;
        $parts = explode(' ', $protected_nicks);
        //echo("PN: $protected_nicks <pre>" . print_r($parts) ."</pre>");

        foreach($parts as $part) {
            //echo("Controllo $part contro $nickname<br>");
            if(preg_match("/$part/i", $nickname)) {
                $usesProtectedNick = true;
                continue;
            }
        }

        if($usesProtectedNick) {
            if(!preg_match("/:$protection_password\$/", $nickname)) {
                echo('<font color="red"><b>');
                echo('This nickname is reserved. Please, use another one<br/>');
                echo('</b></font>');
                if($this->mail_alert) {
                    $this->notifyUser($nickname, $shoutText, "alert");
                }
                return false;
            }
            else {
                $nickname = preg_replace("/:$protection_password\$/", "", $nickname);
            }
        }

        $shoutText = strip_tags($shoutText, '<a><br><b><i><strong>');
        if (!get_magic_quotes_gpc()) {
            $nickname = addslashes($nickname);
            $shoutText = addslashes($shoutText);
        }
        if(strlen($nickname) == 0 || strlen($shoutText) == 0) {
            echo('<font color="red"><b>');
            echo('You need to insert a nickname and a message.</br>');
            echo('</b></font>');
            return false;
        }
        else if($nickname == $this->default_nick || $shoutText == $this->default_shout) {
            echo('<font color="red"><b>');
            echo('Shout something more original ;-)<br/>');
            echo('</b></font>');
            return false;
        }
        else if(strlen($shoutText) > $this->max_length) {
            echo('<font color="red"><b>');
            echo("Your shout is too long! It can be at most {$this->max_length} characters long<br/>");
            echo('</b></font>');
            return false;
        }
        else if(strlen($nickname) > 20) {
            echo('<font color="red"><b>');
            echo("Your nickname is too long! It can be at most 20 characters long<br/>");
            echo('</b></font>');
            return false;
        }

        $sql =  "INSERT INTO " . $this->getPrefix() . "shoutbox_shouts (nickname, shout_text, blog_id, shout_date) VALUES" .
                "('$nickname', '$shoutText',  {$this->blogId}, '".Date('Y-m-d H:i:s')."')";
        $result = $this->Execute($sql);

        if($this->mail_alert) {
            $this->notifyUser($nickname, $shoutText);
        }

        //die("<pre>$sql</pre>");

        if(!$result) {
            echo('Sorry, coud not add your shout.');
            return false;
        }
        return true;
    }

    function deleteShout($id) {
        $sql = "DELETE FROM " . $this->getPrefix() . "shoutbox_shouts WHERE shout_id = $id";
        $result = $this->Execute($sql);
        if(!$result) {
            die('Could not delete the shouts!');
            return false;
        }
        return true;
    }

    function alterShout($id, $nickname, $shoutText) {
        $sql = "UPDATE " . $this->getPrefix() . "shoutbox_shouts SET nickname = '$nickname' , shout_text = '$shoutText' WHERE shout_id = $id";
        $result = $this->Execute($sql);
        if(!$result) {
            die('Could not slter the shout!');
            return false;
        }
        return true;
    }

    function getLastPage() {
        $sql =  "SELECT COUNT(*) as cnt FROM " . $this->getPrefix() . "shoutbox_shouts ";
        $res = $this->Execute($sql);
        if(!$res)
            return 0;
        $cnt = $res->FetchRow();
        if($cnt['cnt'] > 0)
            $cnt = floor($cnt['cnt'] / 15);
        return $cnt;
    }

    ####################################################
    # Extra functions
    function notifyUser($nickname, $shout_text, $whichMail = "new") {
        $users = new Users();
        $userInfos = $users->getBlogUsers($this->blogId);
        
        foreach($userInfos as $userInfo) {
            $message = new EmailMessage();
            $message->setFrom("Plog Shoutbox Plugin");
            $message->addTo( $userInfo->getEmail());
            
            if($whichMail == "new") {
                $message->setSubject( "pLog Notification system: new shout in shoutbox" );
                $body = <<<END
There is a new shout in your shoutbox.
From: $nickname
Text: $shout_text
END;
            }
            else if($whichMail == "alert") {
                $message->setSubject( "pLog Notification system: shoutbox nickname protection alert" );
                $body = <<<END
Someone has tried to use your nickname in the shoutbox. The following message has been discarded:
Text: $shout_text
END;
            }
            
            $message->setBody($body);

            $service = new EmailService();
            $service->sendMessage( $message );
            //echo('Sent mail to ' . $userInfo->getEmail() . '<br>');
        }
    }

    ####################################################
    # Public section. This is more a hack than anything, because things should be
    # done using user actions and such... well... maybe next release...
    function thinkAndDo() {
        if(isset($_POST['shoutbox_submit'])) {
            $this->addShout($_POST['shoutbox_nickname'], $_POST['shoutbox_text']);
            //TODO: reload to discard used post
        }
        return $this->getShoutsArray($this->shouts_per_view);
    }
    
    function defaultNick() {
        return $this->default_nick;
    }
    
    function defaultShout() {
        return $this->default_shout;
    }
}
?>
