<?php

include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
include_once( PLOG_CLASS_PATH."class/template/cachecontrol.class.php" );
include_once( PLOG_CLASS_PATH."class/mail/emailmessage.class.php" );
include_once( PLOG_CLASS_PATH."class/mail/emailservice.class.php" );

include_once( PLOG_CLASS_PATH."plugins/shoutbox/class/dao/shoutboxInstaller.class.php" );


class Shoutbox extends Model {
    var $blogId;
    
    var $config;
    
    var $shout_enabled;
    var $mail_alert;
    var $quick_delete;
    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();
    
        /* Initialization */
        $this->blogId = $blogId;

        $this->shout_enabled = $blogSettings->getValue("plugin_shoutbox_shout_enabled");
        $this->mail_alert = $blogSettings->getValue("plugin_shoutbox_mail_alert");
        $this->mail_alert = $blogSettings->getValue("plugin_shoutbox_mail_alert");
        $this->quick_delete = $blogSettings->getValue("plugin_shoutbox_quick_delete");
        $this->max_length = $blogSettings->getValue( "plugin_shoutbox_max_length");
        $this->shouts_per_view = $blogSettings->getValue( "plugin_shoutbox_shouts_per_view", 0);

        $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();
    }
    
    function setup() {
      $si = new ShoutboxInstaller($this->blogId, $this->blogSettings);
      return $si->checkShoutbox();
    }
    

    function getShoutsArray($page = false) {
      $sql =  "SELECT * FROM " . $this->getPrefix() . "shoutbox_shouts ";
      $sql .= "WHERE blog_id =  {$this->blogId} ORDER BY shout_date DESC ";
      
      if($page)
        $offset = ($page-1) * $this->shouts_per_view;
      else
        $offset = 0;

      $sql .= "LIMIT $offset, " . $this->shouts_per_view;
      
      $this->shoutsResult = $this->Execute($sql);
      if(!$this->shoutsResult)
          return array();

      while($shout = $this->shoutsResult->FetchRow()) {
        $shout['shout_date'] = Date("d/m/Y G:i", strtotime($shout['shout_date']));
        $shouts[] = $shout;
      }

      return $shouts;
    }

    function addShout($nickname, $shoutText) {
        //die("Cool :D Adding shout <b>$shoutText</b> by $nickname ");
        $auth = "";
        for($i=0; $i < 12; $i++) {
            $auth .= chr((mt_rand(1, 36) <= 26) ? mt_rand(97, 122) : mt_rand(48, 57));
        }

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

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

        if(!$result) {
            echo('Sorry, coud not add your shout.');
            return false;
        }
        
        $shoutId = $this->_db->Insert_ID();
        
        if($this->mail_alert) {
          $params = array('id' => $shoutId, 'auth' => $auth);
          $this->notifyUser($nickname, $shoutText, 'new', $params);
        }
        
        return true;
    }

    function deleteShout($id, $auth = false) {
        $sql = "DELETE FROM " . $this->getPrefix() . "shoutbox_shouts WHERE shout_id = $id";
        if($auth)
          $sql .= " AND auth = '$auth' AND shout_date >= DATE_SUB(CURDATE(),INTERVAL 3 DAY)";
        //echo($sql);
        $result = $this->Execute($sql);
        if(!$result) {
          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'] / $this->shouts_per_view);
		}
        return $cnt;
    }

    ####################################################
    # Extra functions
    function notifyUser($nickname, $shout_text, $whichMail = "new", $params = false) {
        $users = new Users();
        $userInfos = $users->getBlogUsers($this->blogId);
        
        foreach($userInfos as $userInfo) {
            $message = new EmailMessage();
            $message->setFrom("LifeType Shoutbox Plugin");
            $message->addTo( $userInfo->getEmail());
            
            if($whichMail == "new") {
                $message->setSubject( "LifeType Notification system: new shout in shoutbox" );
                $body = <<<END
There is a new shout in your shoutbox.
From: $nickname
Text: $shout_text
END;
            
            if($this->quick_delete) {
              $body .= <<<END


You can delete this shout by clicking on this link:
XXX http://www.netpalantir.it/index.php?op=shoutboxQuickDelete&shoutId={$params['id']}&auth={$params['auth']} XXX
Remember there is no undo.
END;
            }
            
            }
            else if($whichMail == "alert") {
                $message->setSubject( "LifeType 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.
    function thinkAndDo() {
        return $this->getShoutsArray();
    }
    
    function defaultNick() {
        return $this->default_nick;
    }
    
    function defaultShout() {
        return $this->default_shout;
    }
}
?>
