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

class news {
  /* @param
   * */
  public $TDB_NEWS = T_NEWS; // nom de la table.
  public $ID;
  public $TITLE;
  public $HEADER;
  public $BODY;
  public $LEVEL;
  public $SCALE;
  public $RANGE;
  public $POSTED_BY;
  public $POST_DATE;
  public $PUBLISHED_DATE;
  public $PEREMPT_DATE;
  public $IS_NATIONAL;
  public $STATUT;
  protected $dispatcher = null;


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

  public function __call($method, $arguments)
  {
    $event = $this->dispatcher->notifyUntil(new sfEvent($this, 'news.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::_getDate()
   * date courante et ajout
   *
   * @access private
   * @param int $m chiffre des mois
   * @param int $d chiffre des jours
   * @param int $y chiffre des années
   * @return string $format_date
   * @return
   */
  private function _getDate($m = 0, $d = 0, $y = 0)
  {
    $format_date = mktime(date("H"), date("i"), date("s"), date("m") + $m, date("d") , date("Y"));
    $format_date = strftime('%Y-%m-%d %H:%M:%S', $format_date);

    return $format_date;
  }


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

  public function CheckDataIntegrity($table)
  {

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

    if (strlen($table[0]) < 3) return _t('news','no_title');
    if (strlen($table[1]) < 3) return _t('news','no_header');
    if (strlen($table[2]) < 3) return _t('news','no_body');
   
    if(isset($table['publication_date'])) {
    	$date_valid = checkdate_validity($table['publication_date'], _t('validation', 'invalid_publication_date').' ');
    	if(is_string($date_valid)) return $date_valid;
    }    	

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

    return true;
  }

  /**
   * news::AddNews()
   * Ajout d'une news
   *
   * @access public
   * @param array $a : contient les composants d'une news
   * @param object $sql_object
   * @return integer $last_id
   */
  public function AddNews($a, $sql_object)
  {

  	global $l21auth;
  	
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'news.before_add', array('data' => $a)), $a);
  	$a = $r->getReturnValue();

  	// image 64 encoded conversion if enabled before escaping content
  	$a[1] = convertBase64Images($a[1], 'news-');
  	$a[2] = convertBase64Images($a[2], 'news-');
  	
    $a=$sql_object->DBescape($a);

    if ($a[0] != '') {
      $this->TITLE = strip_input(trim($a[0]), true);
    }
    if ($a[1] != '') {
      $this->HEADER = strip_input(trim($a[1]), true);
    }
    if ($a[2] != '') {
      $this->BODY = strip_input(trim($a[2]), true);
    }
    if (is_numeric($a[3])) {
      $this->LEVEL = $a[3];
    }
    if (is_numeric($a[4])) {
      $this->SCALE = $a[4];
    }
    if (is_numeric($a[5])) {
      $this->RANGE = $a[5];
    }
    if (is_numeric($a[6])) {
      $this->POSTED_BY = $a[6];
    }
    if ($a[8] != '') {
      $this->IS_NATIONAL = strtoupper($a[8]);
    }
    if ($a[9] != '') {
      $this->STATUT = strtoupper($a[9]);
    }
    if ($this->STATUT == 'P') {
      $this->PUBLISHED_DATE = $this->_getDate();
      if ($a[7] != '') {
        $this->PEREMPT_DATE = $a[7];
      } else {
        $this->PEREMPT_DATE = '0001-01-01';
      }
    } else {
      $this->PUBLISHED_DATE = '0001-01-01';
      $this->PEREMPT_DATE = '0001-01-01';
    }
    $q = "INSERT INTO " . $this->TDB_NEWS . " (news_title, news_header, news_body, news_level, news_scale, " . " news_range, news_posted_by, news_published_date, " . "news_perempt_date, news_is_national, news_statut, news_date_crea) " . "VALUES('" . $this->TITLE . "', '" . $this->HEADER . "', '" . $this->BODY . "', " . $this->LEVEL . ", " . $this->SCALE . ", " . $this->RANGE . ", " . $this->POSTED_BY . ", '" . $this->PUBLISHED_DATE . "' , '" . $this->PEREMPT_DATE . "', '" . $this->IS_NATIONAL . "', '" . $this->STATUT . "', now());";

    $last_id = $sql_object->DBInsert ($q, 1);
    
    // we log add action
    if(is_numeric($last_id))	logfile(LOG_MAINFILE, array('[action] add news', '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, 'news.after_add', array('data' => $a, 'id' => $last_id)));

    return $last_id;
  }

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

  public function DeleteNews($ID, $sql_object)
  {
  	global $l21auth;
  	
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'news.delete', array('id' => $ID)));
 
    $this->ID = $ID;
    $q = "UPDATE  " . $this->TDB_NEWS . " set news_statut='E', news_last_modify=NOW() WHERE news_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery($q);
    
    // we log delete action
    if($result)	logfile(LOG_MAINFILE, array('[action] delete news', 'ID='.$ID, 'by_id='.$l21auth->GetSessionElement('id'), 'by_login='.$l21auth->GetSessionElement('login')));
  	
    return $result;
  }

  /**
   * news::ModifyNews()
   * modification d'une news
   *
   * @access public
   * @param integer $ID : identifiant de la news
   * @param object $sql_object
   * @param array $a : contient les composants d'une news
   * @return boolean $result
   */
  public function ModifyNews($ID, $a, $sql_object)
  {

  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'news.before_modify', array('data' => $a, 'id' => $ID)), $a);
  	$a = $r->getReturnValue();

  	// image 64 encoded conversion if enabled before escaping content
  	$a[1] = convertBase64Images($a[1], 'news-');
  	$a[2] = convertBase64Images($a[2], 'news-');
  	
    $a=$sql_object->DBescape($a);
    if (is_numeric($ID)) {
      $this->ID = $ID;
    }
    if ($a[0] != '') {
      $this->TITLE = strip_input(trim($a[0]), true);
    }
    if ($a[1] != '') {
      $this->HEADER = strip_input(trim($a[1]), true);
    }
    if ($a[2] != '') {
      $this->BODY = strip_input(trim($a[2]), true);
    }
    if (is_numeric($a[3])) {
      $this->LEVEL = $a[3];
    }
    if (is_numeric($a[4])) {
      $this->SCALE = $a[4];
    }
    if ($a[5] != '') {
      $this->STATUT = $a[5];
    }

    $this->PUBLISHED_DATE = $a['publication_date'];

    $mask = $this->_hasPublishedDate($a[6]);

    $q = "UPDATE  " . $this->TDB_NEWS . " set news_title='" . $this->TITLE . "', news_header='" . $this->HEADER . "', news_body='" . $this->BODY . "' , news_level='" . $this->LEVEL . "', news_scale='" . $this->SCALE . "', news_statut='" . $this->STATUT . "', news_last_modify=NOW() " . $mask . " WHERE news_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery($q);

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

    return $result;
  }

  /**
   * news::changeRanges()
   * changes News range
   *
   * @access public
   * @param array : Id (key) and ranges (value)
   * @param object $sql_object
   * @return bool $result
   */

  function changeRanges($array, $sql_object)
  {

    foreach ($array as $key => $value) {
      $query = "UPDATE " . $this->TDB_NEWS . " set news_range='".$value."' WHERE news_id='" . $key . "';";
      $result = $sql_object->DBQuery($query);
    }

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

    return $result;
  }

  /**
   * news::_hasPublishedDate()
   * Détermine la date de publication a inserer dans la bdd
   *
   * @access private
   * @param string $current_status : statut actuel de l'actualité
   * @return string $sql_mask
   */
  private function _hasPublishedDate($current_status)
  {
    switch ($this->STATUT) {
      case 'P':
        if ($current_status == 'D') $sql_mask = ", news_published_date = NOW()";
        else $sql_mask = ", news_published_date = '". formatDate($this->PUBLISHED_DATE, true)." ".date('h:i:s') ."'";
        break;
      case 'D':
        $sql_mask = ", news_published_date= '0001-01-01'";
        break;
      default:
      	// handle 'AA' & 'AP' status
      	if(!empty($this->PUBLISHED_DATE)) $sql_mask = ", news_published_date = '". formatDate($this->PUBLISHED_DATE, true)." ".date('h:i:s') ."'";
        else $sql_mask = '';
    }
    return $sql_mask;
  }
}

?>
