<?php
/**
 * @package linea21.modules
 * @subpackage project
 * @author linea21 <info@linea21.com>
 * @version $id SVN
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 * Project Management
 */

class project {
  /* @param
   * */
  var $TDB_PROJECT = T_PROJECT; // nom de la table.
  var $ID;
  var $PARENT_ID;
  var $SCALE_ID;
  var $PRIORITY_ID;
  var $THEME_ID;
  var $WORKSHOP_ID;
  var $NAME;
  var $DESCRIPTION;
  var $BODY;
  var $BUDGET;
  var $COORDINATOR;
  var $PARTNERS;
  var $BEGIN_DATE;
  var $ESTIMATED_DATE;
  var $END_DATE;
  var $COMPLETED;
  var $SDI;
  var $PUBLISHED_DATE;
  var $POSTED_BY;
  var $DATE_CREA;
  var $STATUT;
  var $LAST_MODIFY;
  protected $dispatcher = null;

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

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

  /**
   * project::_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
   */
  function _getDate($m = 0, $d = 0, $y = 0)
  {
    $format_date = mktime(date("H"), date("i"), date("s"), date("m") + $m, date("d") , date("Y"), -1);
    $format_date = strftime('%Y-%m-%d %H:%M:%S', $format_date);

    return $format_date;
  }

  /**
   * project::CheckDataIntegrity()
   * Vérification intégrité des données
   *
   * @access public
   * @param array $table : contient les composants Nécessaires d'un projet
   * @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, 'project.before_datacheck', array('data' => $table)), $table);
  	$table = $r->getReturnValue();
  	_debug("budget::".$table[15]);
    if (strlen($table[0]) < 3) return _t('project','no_name');
    if (strlen($table[1]) < 3) return _t('project','no_description');
    if (strlen($table[2]) < 3) return _t('project','no_body');
    if ($table[5] <= 0 || !is_numeric($table[5])) return _t('project','no_priority');
    if ($table[4] <= 0 || !is_numeric($table[4])) return _t('project','no_scale');
    
    if(!empty($table[6])) {
    	$r = checkdate_validity($table[6], _t('project','begin_date_err'));
    	if(is_string($r)) return $r;
    }
    if(!empty($table[7])) {
    	$r = checkdate_validity($table[7], _t('project','estimated_date_err'));
    	if(is_string($r)) return $r;
    }
    if(!empty($table[8])) {
    	$r = checkdate_validity($table[8], _t('project','end_date_err'));
    	if(is_string($r)) return $r;
    }
    
    if(!is_numeric($table[14]) || $table[14]>100 || $table[14]<0 ) return _t('project','progression_error');
    if(!empty($table[15]) && !is_numeric($table[15])) return _t('project','budget_integer');
    
    // Notify the beginning of the current method
    $this->dispatcher->notify(new sfEvent($this, 'project.after_datacheck', array('data' => $table)));

    return true;
  }

  /**
   * project::AddProject()
   * Ajout d'un projet
   *
   * @access public
   * @param array $array : contient les composants d'un projet
   * @param object $sql_object
   * @return integer $last_id
   */
  function AddProject($array, $sql_object)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'project.before_add', array('data' => $array)), $array);
  	$array = $r->getReturnValue();
  	
    $array=$sql_object->DBescape($array);

    if ($array[0] != '') {
      $this->NAME = strip_input(trim($array[0]), true);
    }
    if ($array[1] != '') {
      $this->DESCRIPTION = strip_input(trim($array[1]), true);
    }
    if ($array[2] != '') {
      $this->BODY = strip_input(trim($array[2]), true);
    }
    if (is_numeric($array[3]) && $array[3] != -1) {
      $this->PARENT_ID = $array[3];
    } else {
      $this->PARENT_ID = 0;
    }
    if (is_numeric($array[4])) {
      $this->SCALE_ID = $array[4];
    }
    if (is_numeric($array[5])) {
      $this->PRIORITY_ID = $array[5];
    }
    if ($array[6] != '') {
      $this->BEGIN_DATE = formatDate($array[6], true);
    } else {
      $this->BEGIN_DATE = '0001-01-01';
    }
    if ($array[7] != '') {
      $this->ESTIMATED_DATE = formatDate($array[7], true);
    } else {
      $this->ESTIMATED_DATE = '0001-01-01';
    }
    if ($array[8] != '') {
      $this->END_DATE = formatDate($array[8], true);
    } else {
      $this->END_DATE = '0001-01-01';
    }
    if (is_numeric($array[9])) {
      $this->POSTED_BY = $array[9];
    }
    if ($array[10] != '') {
      $this->STATUT = strtoupper($array[10]);
    }
    if (is_numeric($array[11]) && $array[11] != -1) {
      $this->THEME_ID = $array[11];
    } else {
      $this->THEME_ID = 0;
    }
    if (is_numeric($array[12]) && $array[12] != -1) {
      $this->WORKSHOP_ID = $array[12];
    } else {
      $this->WORKSHOP_ID = 0;
    }
    $this->SDI = $array[13];
    if ($this->STATUT == 'P') {
      $this->PUBLISHED_DATE = $this->_getDate();
    } else {
      $this->PUBLISHED_DATE = '0001-01-01';
    }

     $this->COMPLETED = $array[14];
     
     if(!empty($array[15])) {
     	$this->BUDGET = str_replace(' ', '', $array[15]);
     } else {
     	$this->BUDGET = "NULL";
     }
     
     $this->COORDINATOR = $array[16];
     
     $this->PARTNERS = $array[17];

    $query = "INSERT INTO " . $this->TDB_PROJECT . " (project_name, project_description, project_body, ".
    "project_budget, " .
    "project_parent_id, project_priority_id, project_scale_id, " .
    "project_begin_date, project_estimated_date, project_end_date, ".
    "project_completed, project_theme_id, project_workshop_id, ".
    "project_posted_by, project_published_date, " .
    "project_statut, project_date_crea) " .
    "VALUES('" . $this->NAME . "', '" . $this->DESCRIPTION . "', '" . $this->BODY .
    "', " . $this->BUDGET . ", " . $this->PARENT_ID . ", " . $this->PRIORITY_ID . ", " . $this->SCALE_ID .
    ", '" . $this->BEGIN_DATE . "', '" . $this->ESTIMATED_DATE . "', '" . $this->END_DATE .
    "', " . $this->COMPLETED . ", " . $this->THEME_ID . ", " . $this->WORKSHOP_ID .
    ", " . $this->POSTED_BY . ", '" . $this->PUBLISHED_DATE . "' , '" . $this->STATUT .
    "', now());";
     
    $this->ID = $sql_object->DBInsert ($query, 1);
    $this->_addSDI($sql_object);
    $this->addActors($this->ID, $this->COORDINATOR, 'coordinator');
    $this->addActors($this->ID, $this->PARTNERS, 'partner');
    
    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'project.after_add', array('data' => $array, 'id' => $this->ID)));

    return $this->ID;
  }
  
  
  /**
   * project::modifyActors()
   * Ajout d'un ou plusieurs acteurs au projet
   *
   * @access private
   * @param int $id identifiant du projet
   * @param string $content acteurs séparés par des virgules
   * @param string $type
   * @return integer $last_id
   */
  private function modifyActors($id, $content, $type) {
  	
  	global $sql_object;
  	 
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'project.modify_actor', array('id' => $id, 'content' => $content, 'type' => $type)));
  	 
  	$query = "DELETE FROM " . J_PROJECT_ACTOR . " WHERE jpa_project_id='".$id."' AND jpa_type='" . $type . "';";
  	$result = $sql_object->DBQuery($query);
  	
  	if(!empty($content)) {
  		$result = $this->addActors($id, $content, $type);
  	}
  
  	return $result;
  }
  
  /**
   * project::addActors()
   * Ajout d'un ou plusieurs acteurs au projet
   *
   * @access private
   * @param int $id identifiant du projet
   * @param string $content acteurs séparés par des virgules
   * @param string $type
   * @return integer $last_id
   */
  private function addActors($id, $content, $type)
  {
  	global $sql_object;
  	
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'project.add_actor', array('id' => $id, 'content' => $content, 'type' => $type)));
  	 
  	// we remove latest comma
  	if (substr($content, -1) == ',') {
  		$content = substr($content, 0, -1);
  	}
  	// we explode string to array
  	$array = @explode(',', $content);
  	$array = array_map('trim', $array);
  	$array = $sql_object->DBEscape($array);
  	
  	for ($i = 0;$i < count($array);$i++) {
  		// we check if actor already exists
  		$q = "SELECT actor_id FROM " . T_ACTOR . " WHERE lower(actor_name) = '" . strtolower($array[$i]) . "';";
  		$data = $sql_object->DBSelect($q);
  		
  		// if already exists, we retrieve id
  		if(isset($data[0]['actor_id'])) {
  			$actor_id = $data[0]['actor_id'];
  		} else {
  			// else we create it and retrieve id
  			$q = "INSERT INTO " . T_ACTOR . " (actor_name) VALUES('" . $array[$i] . "');";
  			$last_id = $sql_object->DBInsert ($q, 1);
  			$actor_id = $last_id;
  		}
  		// finally we insert tuple in table
  		$q = "INSERT INTO " . J_PROJECT_ACTOR . " (jpa_project_id, jpa_actor_id, jpa_type) VALUES(" . $id . ", " . $actor_id . ",'" . $type . "');";

  		$last_id = $sql_object->DBInsert ($q, 1);
  	}
  
  	return $last_id;
  }

  /**
   * project::DeleteProject()
   * suppression d'un projet
   *
   * @access public
   * @param int $ID : identifiant du projet
   * @param object $sql_object
   * @return bool $result
   */

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

    $query = "UPDATE " . $this->TDB_PROJECT . " set project_statut='E', project_last_modify=NOW() WHERE project_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery($query);
    if($result) {
      $query = "DELETE FROM " . J_PROJECT_SDI . " WHERE jps_project_id='".$this->ID."';";
      $res = $sql_object->DBQuery($query);
    }
    if($result) {
    	$query = "DELETE FROM " . J_PROJECT_ACTOR . " WHERE jpa_project_id='".$this->ID."';";
    	$res = $sql_object->DBQuery($query);
    }
    if($result) {
      $query = "UPDATE " . $this->TDB_PROJECT . " set project_parent_id=0 WHERE project_parent_id='" . $this->ID . "';";
      $result = $sql_object->DBQuery($query);
    }
    return $result;
  }

  /**
   * project::ModifyProject()
   * modification d'un projet
   *
   * @access public
   * @param integer $ID : identifiant du projet
   * @param object $sql_object
   * @param array $array : contient les composants d'un projet
   * @return boolean $result
   */
  function ModifyProject($ID, $array, $sql_object)
  {

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

    if (is_numeric($ID)) {
      $this->ID = $ID;
    }

    if ($array[0] != '') {
      $this->NAME = strip_input(trim($array[0]), true);
    }
    if ($array[1] != '') {
      $this->DESCRIPTION = strip_input(trim($array[1]), true);
    }
    if ($array[2] != '') {
      $this->BODY = strip_input(trim($array[2]), true);
    }
    if (is_numeric($array[3]) && $array[3] != -1) {
      $this->PARENT_ID = $array[3];
    } else {
      $this->PARENT_ID = 0;
    }
    if (is_numeric($array[4])) {
      $this->SCALE_ID = $array[4];
    }
    if (is_numeric($array[5])) {
      $this->PRIORITY_ID = $array[5];
    }
    if ($array[6] != '') {
      $this->BEGIN_DATE = formatDate($array[6], true);
    } else {
      $this->BEGIN_DATE = '0001-01-01';
    }
    if ($array[7] != '') {
      $this->ESTIMATED_DATE = formatDate($array[7], true);
    } else {
      $this->ESTIMATED_DATE = '0001-01-01';
    }
    if ($array[8] != '') {
      $this->END_DATE = formatDate($array[8], true);
    } else {
      $this->END_DATE = '0001-01-01';
    }
    if ($array[9] != '') {
      $this->STATUT = strtoupper($array[9]);
    }
    if (is_numeric($array[11]) && $array[11] != -1) {
      $this->THEME_ID = $array[11];
    } else {
      $this->THEME_ID = 0;
    }
    if (is_numeric($array[12]) && $array[12] != -1) {
      $this->WORKSHOP_ID = $array[12];
    } else {
      $this->WORKSHOP_ID = 0;
    }
    $this->SDI = $array[13];
    if ($this->STATUT == 'P') {
      $this->PUBLISHED_DATE = $this->_getDate();
    } else {
      $this->PUBLISHED_DATE = '0001-01-01';
    }
    
    $this->COMPLETED = $array[14];

    if(!empty($array[15])) {
    	$this->BUDGET = str_replace(' ', '', $array[15]);
    } else {
    	$this->BUDGET = "NULL";
    }
    
    $this->COORDINATOR = $array[16];
     
    $this->PARTNERS = $array[17];
     
    $this->modifyActors($this->ID, $this->COORDINATOR, 'coordinator');
    $this->modifyActors($this->ID, $this->PARTNERS, 'partner');

    $mask = $this->_HavePublishedDate($array[10]);

		$query = "UPDATE  " . $this->TDB_PROJECT . " SET project_name='" . $this->NAME . "', project_description='" . $this->DESCRIPTION. "', project_body='" . $this->BODY . "', project_budget=" . $this->BUDGET . ", project_parent_id='" . $this->PARENT_ID . "', project_scale_id='" . $this->SCALE_ID . "', project_theme_id='" . $this->THEME_ID ."', project_workshop_id='" . $this->WORKSHOP_ID ."', project_priority_id='" . $this->PRIORITY_ID . "', project_begin_date='" . $this->BEGIN_DATE . "', project_estimated_date='" . $this->ESTIMATED_DATE . "', project_end_date='".$this->END_DATE."', project_completed=".$this->COMPLETED.", project_statut='" . $this->STATUT . "', project_last_modify=NOW() " . $mask . " WHERE project_id='" . $this->ID . "';";    $result = $sql_object->DBQuery($query);
    $result = $this->_modifySDI($sql_object);
    
    // Notify the end of the current method
    $this->dispatcher->notify(new sfEvent($this, 'project.after_modify', array('data' => $array, 'id' => $this->ID)));

    return $result;
  }
  
  /**
   * project::changeRanges()
   * changes Project 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_PROJECT . " set project_range='".$value."' WHERE project_id='" . $key . "';";
      $result = $sql_object->DBQuery($query);
    }
    
    // Notify the beginning of the current method
    $this->dispatcher->notify(new sfEvent($this, 'project.change_ranges', array('data' => $array)));

    return $result;
  }

  /**
   * project::_addSDI()
   * associate indicators to project
   *
   * @access private
   */
  function _addSDI($sql_object) {
  	
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'project.add_sdi', array('data' => $this->SDI)));
  	
    foreach ($this->SDI as &$value) {
      $query = "INSERT INTO ". J_PROJECT_SDI . " VALUES(".$this->ID.", ".$value.");";
      $result = $sql_object->DBQuery($query);
    }
    return $result;
  }

  /**
   * project::_modifySDI()
   * associate indicators to project
   *
   * @access private
   */
  function _modifySDI($sql_object) {
  	
  	// Notify the beginning of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'project.modify_sdi', array('data' => $this->SDI)));
  	
    $query = "DELETE FROM " . J_PROJECT_SDI . " WHERE jps_project_id='".$this->ID."';";
    $result = $sql_object->DBQuery($query);
    if(count($this->SDI)>0) {
      $result = $this->_addSDI($sql_object);
    }

    return $result;
  }

  /**
   * project::_HavePublishedDate()
   * 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
   */
  function _HavePublishedDate($current_status)
  {
    switch ($this->STATUT) {
      case 'P':
        if ($current_status == 'D') $sql_mask = ", project_published_date= NOW()";
        else $sql_mask = '';
        break;
      case 'D':
        $sql_mask = ", project_published_date= '0001-01-01'";
        break;
      default:
        $sql_mask = '';
    }
    return $sql_mask;
  }
}

?>
