<?php
/**
 * Newsletter class
 * 
 * Povides methods related to newsletter module
 * 
 * @package linea21\modules\newsletter
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 * Newsletter Management
 */

class newsletter {
  /* @param
   * */
  var $TDB_NEWSLETTER= T_NEWSLETTER; // nom de la table.
  var $TDB_COLLECTOR = T_EMAIL_COL; // nom de la table.
  var $URI_TEMPLATE = "../newsletter/input/template"; // chemin du template de mail
  var $URI_ELEMENTS = "elements/"; // repertoire stockage élements newsletter
  var $ID;
  var $TITLE;
  var $BODY;
  var $POSTED_BY;
  var $DATE_CREA;
  var $LAST_MODIFY;
  var $PUBLISHED_DATE;
  var $STATUT;

  var $E_ID;
  var $E_EMAIL;
  var $E_STATUT;
  var $E_DATE_CREA;
  var $E_LAST_MODIFY;
  protected $dispatcher = null;

  public function __construct()
  {
    $this->dispatcher = $GLOBALS['dispatcher'];
  }

  public function __call($method, $arguments)
  {
    $event = $this->dispatcher->notifyUntil(new sfEvent($this, 'newsletter.extensible_function', array(
      'method'    => $method,
      'arguments' => $arguments
    )));
    if (!$event->isProcessed())
    {
      throw new Exception(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
    }

    return $event->getReturnValue();
  }

  /**
   * news::CheckDataIntegrity()
   * Vérification intégrité des données
   *
   * @access public
   * @param array $table : contient les composants Nécessaires d'une newsletter
   * @return boolean true
   * si verifié, sinon string 'message d'erreur'
   */

  function CheckDataIntegrity($table)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'newsletter.before_datacheck', array('data' => $table)), $table);
  	$table = $r->getReturnValue();

    if (strlen($table[0]) < 3) return _t('newsletter','no_title');
    if (strlen($table[1]) < 50) return _t('newsletter','no_body');

    // Notify the beginning of the current method
    $this->dispatcher->notify(new sfEvent($this, 'newsletter.after_datacheck', array('data' => $table)));

    return true;
  }

  /**
   * newsletter::_checkEmailValidity()
   * Vérification de la validité d'un email
   *
   * @access private
   * @param string $email
   * @return bool true ou string ( erreur )
   */
  function _checkEmailValidity($email)
  {

    $is_valid = validEmail($email);

    if(!$is_valid) {
      return _t('newsletter','invalid_mail') . " :'" . $email . "'";
    } else {
      return true;
    }
  }

  /**
   * newsletter::AddNewsletter()
   * Ajout d'une newsletter
   *
   * @access public
   * @param array $table_newsletter : contient les composants d'une newsletter
   * @param object $sql_object
   * @return integer $last_id
   */
  function AddNewsletter($table_newsletter, $sql_object)
  {
  	global $l21auth;
  	
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'newsletter.before_add', array('data' => $table_newsletter)), $table_newsletter);
  	$table_newsletter = $r->getReturnValue();

    $table_newsletter=$sql_object->DBescape($table_newsletter);
    if ($table_newsletter[0] != '') {
      $this->TITLE = strip_input(trim($table_newsletter[0]));
    }
    if ($table_newsletter[1] != '') {
      $this->BODY = strip_input(trim($table_newsletter[1]), true);
    }
    if (is_numeric($table_newsletter[2])) {
      $this->POSTED_BY = $table_newsletter[2];
    }
    $this->STATUT = $table_newsletter[3];

    $q = "INSERT INTO " . $this->TDB_NEWSLETTER . " (newsletter_title, newsletter_body, newsletter_posted_by, newsletter_date_crea , newsletter_last_modify, newsletter_statut) VALUES('" . $this->TITLE . "', '" . $this->BODY . "', '" . $this->POSTED_BY . "', NOW() , NOW(), '" . $this->STATUT . "');";

    $last_id = $sql_object->DBInsert ($q, 1);
    
    // we log add action
    if(is_numeric($last_id))	logfile(LOG_MAINFILE, array('[action] add newsletter', 'ID='.$last_id, 'by_id='.$l21auth->GetSessionElement('id'), 'by_login='.$l21auth->GetSessionElement('login')));

    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'newsletter.after_add', array('data' => $table_news, 'id' => $last_id)));

    return $last_id;
  }

  /**
   * newsletter::DeleteNewsletter()
   * suppression d'une newsletter
   *
   * @access public
   * @param int $ID : identifiant de la newsletter
   * @param object $sql_object
   * @return bool $result
   */

  function DeleteNewsletter($ID, $sql_object)
  {
  	global $l21auth;
  	
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'newsletter.delete', array('id' => $ID)));

    $this->ID = $ID;
    $q = "UPDATE  " . $this->TDB_NEWSLETTER . " set newsletter_statut='E', newsletter_last_modify=NOW() WHERE newsletter_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery($q);
    
    // we log delete action
    if($result)	logfile(LOG_MAINFILE, array('[action] delete newsletter', 'ID='.$ID, 'by_id='.$l21auth->GetSessionElement('id'), 'by_login='.$l21auth->GetSessionElement('login')));
     
    return $result;
  }

  /**
   * newsletter::SetNewsletterPublished()
   * rend une newsletter publié
   *
   * @access public
   * @param int $ID : identifiant de la newsletter
   * @param object $sql_object
   * @return bool $result
   */

  function SetNewsletterPublished($ID, $sql_object)
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'newsletter.set_published', array('id' => $ID)));

    $this->ID = $ID;
    $q = "UPDATE " . $this->TDB_NEWSLETTER . " set newsletter_statut='P', newsletter_published_date=NOW() WHERE newsletter_id='" . $this->ID . "' LIMIT 1;";
    $result = $sql_object->DBQuery($q);
    return $result;
  }

  /**
   * newsletter::ModifyNewsletter()
   * modification d'une newsletter
   *
   * @access public
   * @param integer $ID : identifiant de la news
   * @param object $sql_object
   * @param array $table_newsletter : contient les composants d'une newsletter
   * @return boolean $result
   */
  function ModifyNewsletter($ID, $table_newsletter, $sql_object)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'newsletter.before_modify', array('data' => $table_newsletter, 'id' => $ID)), $table_newsletter);
  	$table_newsletter = $r->getReturnValue();

    $table_newsletter=$sql_object->DBescape($table_newsletter);
    if (is_numeric($ID)) {
      $this->ID = $ID;
    }
    if ($table_newsletter[0] != '') {
      $this->TITLE = strip_input(trim($table_newsletter[0]));
    }
    if ($table_newsletter[1] != '') {
      $this->BODY = strip_input(trim($table_newsletter[1]), true);
    }
    $this->STATUT = $table_newsletter[2];

    $q = "UPDATE  " . $this->TDB_NEWSLETTER . " set newsletter_title='" . $this->TITLE . "', newsletter_body='" . $this->BODY . "' , newsletter_statut='" . $this->STATUT . "', newsletter_last_modify=NOW() WHERE newsletter_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery($q);

    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'newsletter.after_modify', array('data' => $table_newsletter, 'id' => $this->ID)));

    return $result;
  }


  /**
   * newsletter::AddEmail()
   * Ajout d'un email dans le collecteur
   * @access public
   * @param  string $email email a ajouter
   * @param object $sql_object
   * @return string $result
   **/
  function AddEmail($email, $sql_object)
  {
    $result = $this -> _checkEmailValidity($email);
    if (is_string($result)) return  array('code' => 'error', 'string' => $result);

    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'newsletter.add_email', array('email' => $email)));

    $this -> E_EMAIL = strtolower($email);
    $q = "SELECT emailcol_id, emailcol_validity FROM " . $this -> TDB_COLLECTOR . " WHERE emailcol_email='" . $this -> E_EMAIL . "';";
    $data = $sql_object -> DBSelect($q);
    if ($data!=0 && count($data) == 1) {
      $this -> E_ID = $data[0]['emailcol_id'];
      if ($data[0]['emailcol_validity']== "Y") {
        return array('code' => 'info', 'string' => _t('newsletter','subscribe_yet'));
      } else {
        $q = "UPDATE " . $this -> TDB_COLLECTOR . " SET emailcol_validity='Y' WHERE emailcol_id=" . $this -> E_ID . ";";
        if ($sql_object -> DBQuery($q)) return array('code' => 'confirm', 'string' => _t('newsletter','confirm_subscribe'));
      }
    } else {
      $q = "INSERT INTO " . $this -> TDB_COLLECTOR . " (emailcol_email,  emailcol_validity, emailcol_date_crea) " . "VALUES('" . $this -> E_EMAIL . "', 'Y', NOW());";
      $last_id = $sql_object -> DBInsert ($q, 1);
      if (is_numeric($last_id)) return array('code' => 'confirm', 'string' => _t('newsletter','confirm_subscribe'));
    }
  }


  /**
   * newsletter::DeleteEmail()
   * Suppression d'un email du collecteur
   * @access public
   * @param  string $email email a supprimer
   * @param object $sql_object
   * @return string $result
   **/
  function DeleteEmail($email, $sql_object)
  {
    $result = $this -> _checkEmailValidity($email);
    if (is_string($result)) return  array('code' => 'error', 'string' => $result);

    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'newsletter.remove_email', array('email' => $email)));

    $this -> E_EMAIL = strtolower($email);
    $q = "SELECT emailcol_id FROM " . $this -> TDB_COLLECTOR . " WHERE emailcol_email='" . $this -> E_EMAIL . "' AND emailcol_validity='Y';";
    $data= $sql_object -> DBSelect($q);
    if ($data!=0 && count($data) == 1) {
      $this -> E_ID = $data[0]['emailcol_id'];
      $q = "UPDATE " . $this -> TDB_COLLECTOR . " SET emailcol_validity='N' WHERE emailcol_id=" . $this -> E_ID . ";";
      if ($sql_object -> DBQuery($q)) return array('code' => 'confirm', 'string' => _t('newsletter','confirm_del'));
    } else {
      return array( 'code' => 'info', 'string' => _t('newsletter','no_suscribe'));
    }
  }

}

?>
