Apmgr / application / modules / calendar / models / Events.php

<?php
/**
 * Event model to handle the calendar events.
 * This handles a parent event
 * @author Jorge Omar Vazquez <jvazquez@debserverp4.com.ar>
 */

class Calendar_Model_Events extends Calendar_Model_Calendar {

	/**
	 * The date that this event happens
	 * @var date
	 */
	protected $eventDateFrom;

	/**
	 * The Date To that this event happens
	 * @var date
	 */
	protected $eventDateTo;

	/**
	 * The userId that creates an event
	 * @var int
	 */
	protected $userId;

	/**
	 * The data that is in the event.
	 * @var String
	 */
	protected $data;

	/**
	 * Period that represents the number of days / months / years that this element is recursive
	 * @var int
	 */
	protected $recursive;

	/**
	 * Enum that contains the days that we are repeating a recursive event
	 * @var ENUM
	 */
	protected $recursivePeriod;

	/**
	 * @var array
	 */
	protected $recursiveDates;

	/**
	 * @param array $options
	 * @return
	 */
	public function __construct(array $options = null) {
		parent::__construct( $options );
		$this->setDbTable('Calendar_Model_DbTable_Events');
		//	Start this object
		$this->setConfigFile();
		$this->initDateFormat();
	}

	/**
	 * Retrieve the userId that created this event
	 * @return integer
	 */
	public function getUserId() {
		return $this->userId;
	}

	/**
	 * @return string
	 */
	public function getEventDatefrom($mode=self::FORMATVIEW) {
		Zend_Date::setOptions(array('format_type' => 'php'));
		$date = '';
		switch($mode) {
			default : case self::FORMATSQL:
				$zendDate =  new Zend_Date($this->eventDateFrom,null,Zend_Registry::get('Zend_Locale'));
				$date = $zendDate->toString($this->dateSqlFormat);
				break;
			case self::FORMATVIEW:
				$zendDate =  new Zend_Date($this->eventDateFrom,null,Zend_Registry::get('Zend_Locale'));
				$date = $zendDate->toString($this->dateFormat);
				break;
			case self::REGULAR:
				$date = $this->eventDateFrom;
				break;
		}
		return $date;
	}

	/**
	 * Set the date, the specified $date must be an array, whith the following keys.
	 * @example 'eventDateFrom'=>array('month'=>date('m'),'day'=>date('d'),'year'=>date('Y'))
	 * @param array $date
	 * @return Calendar_Model_Calendar
	 */
	public function setEventDateFrom(array $date=null) {
		if( $date==null or !is_array($date) or empty($date) ) {
			throw new InvalidArgumentException('Unhandled date format');
		}
		$this->eventDateFrom = $date;
		return $this;
	}

	/**
	 * Sets the user id that is generating this event
	 * @param integer $userId
	 * @return Calendar_Model_Calendar
	 */
	public function setUserId($userId) {
		$this->userId = $userId;
		return $this;
	}

	/**
	 * Set the date, the specified $date must be an array, whith the following keys.
	 * @example 'eventDateFrom'=>array('month'=>date('m'),'day'=>date('d'),'year'=>date('Y'))
	 * @param array $date
	 * @return Calendar_Model_Calendar
	 */
	public function setEventDateTo(array $date=null) {
		if( $date==null or !is_array($date) or empty($date) ) {
			throw new InvalidArgumentException('Unhandled date format');
		}
		$this->eventDateTo = $date;
		return $this;
	}

	/**
	 * Return the last day of this event
	 * @return date
	 */
	public function getEventDateTo($mode=self::FORMATVIEW) {
		$date = null;
		if(isset( $this->eventDateTo ) ) {
			Zend_Date::setOptions(array('format_type' => 'php'));
			switch($mode) {
				default : case self::FORMATSQL:
					$zendDate =  new Zend_Date($this->eventDateTo,null,Zend_Registry::get('Zend_Locale'));
					$date = $zendDate->toString($this->dateSqlFormat);
					break;
				case self::FORMATVIEW:
					$zendDate =  new Zend_Date($this->eventDateTo,null,Zend_Registry::get('Zend_Locale'));
					$date = $zendDate->toString($this->dateFormat);
					break;
				case self::REGULAR:
					$date = $this->eventDateTo;
					break;
			}
		}
		return $date;
	}

	/**
	 * Set the information, ie text, about this event
	 * @param String $data
	 */
	public function setData($data) {
		$this->data = $data;
		return $this;
	}

	/**
	 * The textual information about this event.
	 * @return String
	 */
	public function getData() {
		return $this->data;
	}

	/**
	 * Set the recursivnes of this event
	 * @param int $recursive
	 */
	public function setRecursive($recursive) {
		if( !is_numeric($recursive) or $recursive<0 ) {
			$recursive = 0;
		}

		$this->recursive = $recursive;
	}

	/**
	 * Return the period that this event happens
	 * @return int
	 */
	public function getRecursive() {
		return $this->recursive;
	}

	/**
	 * An enum composed of the periods that an event can be recursive
	 * @return String
	 */
	public function getRecursivePeriod() {
		$this->logger->notify($this,'The period is:'.$this->recursivePeriod);
		return $this->recursivePeriod;
	}

	/**
	 * sets the recursivness of an event
	 * @param string $period
	 * @return Calendar_Model_Calendar
	 */
	public function setRecursivePeriod($period=null) {
		$this->logger->notify($this,'Setting the period to:'.$period);
		switch($period) {
			default: case self::DAY : $this->recursivePeriod = self::DAY;
			break;
			case self::MONTH: $this->recursivePeriod = self::MONTH;
			break;
			case self::WEEK: $this->recursivePeriod = self::WEEK;
			break;
			case self::YEAR: $this->recursivePeriod = self::YEAR;
			break;
		}
		return $this;
	}

	/**
	 * Prepare the statement that is going to be executed.
	 * TODO Flag properly each exception, and generate a code to handle all this cases
	 * @return boolean
	 * @throws RunTimeException
	 */
	public function validateInsert() {
		$valid = false;
		if( $this->getEventDateTo('sql')!=null and $this->getEventDateFrom('sql')!=null ) {
			$dateFrom =  new Zend_Date($this->getEventDateFrom($this->dateSqlFormat),null,Zend_Registry::get('Zend_Locale'));
			$dateTo =  new Zend_Date($this->getEventDateTo($this->dateSqlFormat),null,Zend_Registry::get('Zend_Locale'));
			if( $dateTo->isEarlier( $dateFrom,Calendar_Model_Calendar::DAY ) == false) {
				$valid  = true;
			}
		} else {
			//	Error
			$this->setMessageState('datesMissing');
		}
		
		return $valid;
	}

	/**
	 * Create a single event
	 * @return boolean
	 */
	public function createEvent() {
		$result = false;
		$data = $this->toArray();
		if ( isset($data['id']) ) {
			$result = $this->getDbTable()->find( $data['id'] );

			if( $result) {
				$tmp = array(
                        'userId'=>$this->getUserId(),
                        'eventDateFrom'=>$this->getEventDateFrom('sql'),
                        'eventDateTo'=>$this->getEventDateTo('sql'),
                        'data'=>$this->getData(),
                        'recursive'=>$this->getRecursive(),
                        'recursivePeriod'=>$this->getRecursivePeriod()
				);
				$record = array_shift( $result->toArray() );
				$data = array_merge($record,$tmp);
				$data['dateUpdated'] = date('Y-m-d H:i:s');
				$db = $this->getDbTable()->getAdapter();
				$where = $db->quoteInto("id=?", $data['id'] );
				$result = $this->getDbTable()->update($data, $where);
			}
		} else {
			$data['dateCreated'] = date('Y-m-d H:i:s');
			$data['eventDateFrom'] = $this->getEventDateFrom('sql');
			$data['eventDateTo'] = $this->getEventDateTo('sql');
			$result = $this->getDbTable()->insert($data);
		}
		return $result;
	}

	/**
	 * Set up the specified date range entries
	 * @param $date array The last day of the event
	 * @param $recursivePeriod int
	 * @param $format constant
	 * @return array
	 */
	public function generateRecursiveDates($date,$recursivePeriod,$format) {
		$periods = array();
		$result = array();
		try {
			if( empty($date) )
			throw new Exception('Date can\'t be empty');
			if( empty($recursivePeriod) )
			throw new Exception('The dates that we will be adding are not defined');
			if( empty($format) )
			throw new Exception('Format is not defined, and the code refuses to continue');

			Zend_Date::setOptions(array('format_type' => 'php'));
			//	Generate the next date
			$nextDate =  new Zend_Date($date,null,Zend_Registry::get('Zend_Locale'));
			$this->logger->notify($this,"We have :" .$nextDate->toString($this->dateFormat));
			while( $nextDate->compare($this->getEventDateTo($this->dateSqlFormat , $format) ) ==-1 ) {
				$nextDate->add($recursivePeriod,$format);
				if( $nextDate->isEarlier( new Zend_Date($this->getEventDateTo($this->dateSqlFormat,null,Zend_Registry::get('Zend_Locale') ) )  ) ) {
					$buffer = explode("-",$nextDate->toString($this->dateSqlFormat));

					if ( count($buffer)!=3 ) {
						throw new Exception("Unexpected result obatained while iterating with a date.This was the last output for nextDate: ". $nextDate->toString($this->dateSqlFormat). " and this was the dateFrom: ".$this->getEventDateFrom( $this->dateSqlFormat , $format));
					}
					$result[]=  $nextDate->toString($this->dateSqlFormat);
					$nextDate->setYear($buffer[0],Zend_Registry::get('Zend_Locale'))
							->setMonth($buffer[1],Zend_Registry::get('Zend_Locale'))
							->setDay($buffer[2],Zend_Registry::get('Zend_Locale'));
				}
			}
		} catch(Zend_Date_Exception $e) {
			$this->logger->notify($this,'Zend_Date_Exception caught!!!. '.$e->getMessage().' at line # '.$e->getLine());
		} catch(Exception $e) {
			$this->logger->notify($this,'Exception caught at '.$e->getLine().' due to '.$e->getMessage());
		}
		return $result;
	}

        /**
         * Retrieve the events for the user
         * @param integer $auth
         * @param string $start
         * @param string $end
         */
        public function retrieveMyEvents(Zend_Auth $auth,$start,$end) {
            $data = $auth->getIdentity();
            $result = array();
            if( !empty($data) ) {
                $userId = $data->id;
                $db = $this->getDbTable();
                $select = $db->select();
                $select->where("userId=?",$userId,'integer')
                        ->where('eventDateFrom>=?',$this->timeStampToDateFormat($start,$this->dateSqlFormat),'string')
                        ->where('eventDateTo<=?',$this->timeStampToDateFormat($end,$this->dateSqlFormat),'string');
                $result = $db->query($select);
                if( count($result) > 0 ) {

                }
            }
        }
        
	/**
	 *
	 * @return string
	 */
	public function __toString() {
		return "Events";
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.