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

class publication {
  /* @param
   * */
  var $TDB_PUBLI = T_PUBLI; // nom de la table.
  var $ID;
  var $TITLE;
  var $RESUME;
  var $LEVEL;
  var $SCALE;
  var $POSTED_BY;
  var $PUBLISHED_DATE;
  var $COMMENT;
  var $DATE_CREA;
  var $LAST_MODIFY;
  var $STATUT;
  protected $dispatcher = null;

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

  public function __call($method, $arguments)
  {
    $event = $this->dispatcher->notifyUntil(new sfEvent($this, 'publication.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();
  }

  /**
   * publication::CheckDataIntegrity()
   * Vérification intégrité des données
   *
   * @access public
   * @param array $table : contient les composants d'une publication
   * @return boolean true
   * si verifié, sinon string 'message d'erreur'
   */
  function CheckDataIntegrity($table, $sql_object)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'publication.before_datacheck', array('data' => $table)), $table);
  	$table = $r->getReturnValue();

    if (strlen($table[0]) < 3) return _t('publication','no_title');
    if (strlen($table[1]) < 3) return _t('publication','no_resume');
    if (strlen(trim($table[4])) < 2) return _t('publication','no_author');
    $result = $this->_CheckUserValidity($table[4], $sql_object);
    if (!is_numeric($result['user_id'])) return _t('publication','author_not_valid');
    if ($result['publi_right'] == 'U') return _t('publication','author_not_rights');
    
    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, 'publication.after_datacheck', array('data' => $table)));

    return $result;

  }

  /**
   * publication::_CheckUserValidity()
   * Vérification validité de l'utilisateur
   *
   * @access private
   * @param string $login
   * @param object $sql_object
   * @return array contenant $user_id et droit si login associé à la publication
   * sinon renvoie false
   */
  function _CheckUserValidity($login, $sql_object)
  {
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'publication.check_user', array('login' => $login)));

    $user = array('user_id' => '', 'publi_right' => '');

    $q = "SELECT user_id, rights_publication FROM " . T_USER . " LEFT OUTER JOIN " . T_RIGHT . " ON user_rights=rights_id WHERE user_login= '" . $login . "' AND user_validity='Y';";
    $result = $sql_object->DBSelect($q);

    if ($result == 0) return false;
    if (count($result) > 1) exit();
    else {
      $user['user_id'] = $result[0]['user_id'];
      $user['publi_right'] = $result[0]['rights_publication'];
    }

    return $user;
  }

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

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

    $this->TITLE = strip_input(trim($table_publi[0]), true);
    $this->RESUME = strip_input(trim($table_publi[1]), true);
    $this->LEVEL = $table_publi[2];
    $this->SCALE = $table_publi[3];
    $this->POSTED_BY = $table_publi[4];
    $this->COMMENT = strip_input(trim($table_publi[5], true));

    if ($table_publi[6] != '') {
      $this->STATUT = strtoupper($table_publi[6]);
    }
    if ($this->STATUT == 'P') {
      $this->PUBLISHED_DATE = "NOW()";
    } else {
      $this->PUBLISHED_DATE = "'0001-01-01'";
    }
    $q = "INSERT INTO " . $this->TDB_PUBLI . " (publi_title, publi_resume, publi_level, publi_scale, publi_posted_by, publi_published_date, publi_comment, publi_statut, publi_date_crea) VALUES('" . $this->TITLE . "', '" . $this->RESUME . "', " . $this->LEVEL . ", " . $this->SCALE . ", " . $this->POSTED_BY . ", " . $this->PUBLISHED_DATE . ", '" . $this->COMMENT . "', '" . $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 publication', '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, 'publication.after_add', array('data' => $table_publi, 'id' => $last_id)));

    return $last_id;
  }

  /**
   * publication::ModifyPublication()
   * modification d'une publication
   *
   * @access public
   * @param int $ID identifiant de la publication
   * @param array $table_publi contient les composants d'une publication
   * @param object $sql_object
   * @return bool $result
   */
  function ModifyPublication($ID, $table_publi, $sql_object)
  {

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

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

    if (is_numeric($ID)) {
      $this->ID = $ID;
    } else exit;
    $this->TITLE = strip_input(trim($table_publi[0]), true);
    $this->RESUME = strip_input(trim($table_publi[1]), true);
    $this->LEVEL = $table_publi[2];
    $this->SCALE = $table_publi[3];
    $this->POSTED_BY = $table_publi[4];
    $this->COMMENT = strip_input(trim($table_publi[5], true));
    $this->STATUT = $table_publi[6];
    
    $this->PUBLISHED_DATE = $table_publi['publication_date'];

    $mask = $this->_hasPublishedDate($table_publi[7]);

    $q = "UPDATE  " . $this->TDB_PUBLI . " set publi_title='" . $this->TITLE . "', publi_resume='" . $this->RESUME . "' , publi_level='" . $this->LEVEL . "', publi_scale='" . $this->SCALE . "', publi_comment='" . $this->COMMENT . "', publi_posted_by='" . $this->POSTED_BY . "', publi_last_modify=NOW(), publi_statut='" . $this->STATUT . "'" . $mask . " WHERE publi_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery($q);

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

    return $result;
  }


  /**
   * publication::changeRanges()
   * changes Workshop 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_PUBLI . " set publi_range='".$value."' WHERE publi_id='" . $key . "';";
      $result = $sql_object->DBQuery($query);
    }

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

    return $result;
  }

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

  /**
   * publication::DeletePublication()
   * suppression d'une publication
   *
   * @access public
   * @param int $ID identifiant de la publication a supprimer
   * @param object $sql_object
   * @return bool $result
   */
  function DeletePublication($ID, $sql_object)
  {
  	global $l21auth;
  	
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'publication.delete', array('id' => $ID)));

    $this->ID = $ID;
    $q = "UPDATE  " . $this->TDB_PUBLI . " set publi_statut='E', publi_last_modify=NOW() WHERE publi_id=" . $this->ID . ";";
    $result = $sql_object->DBQuery($q);

    // we log delete action
    if($result)	logfile(LOG_MAINFILE, array('[action] delete project', 'ID='.$ID, 'by_id='.$l21auth->GetSessionElement('id'), 'by_login='.$l21auth->GetSessionElement('login')));
    
    return $result;
  }
}

?>
