<?php
/*********************************************************************************
 * The contents of this file are subject to the TimeTrex Public License Version
 * 1.1.0 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.TimeTrex.com/TPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by TimeTrex" logo and
 *    (ii) the TimeTrex copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: TimeTrex Open Source
 * The Initial Developer of the Original Code is TimeTrex Payroll Services
 * Portions created by TimeTrex are Copyright (C) 2004-2007 TimeTrex Payroll Services;
 * All Rights Reserved.
 *
 ********************************************************************************/
/*
 * $Revision: 2158 $
 * $Id: StationFactory.class.php 2158 2008-09-15 23:26:15Z ipso $
 * $Date: 2008-09-15 16:26:15 -0700 (Mon, 15 Sep 2008) $
 */
include_once('Net/IPv4.php');

/**
 * @package Core
 */
class StationFactory extends Factory {
	protected $table = 'station';
	protected $pk_sequence_name = 'station_id_seq'; //PK Sequence name

	protected $company_obj = NULL;

	function _getFactoryOptions( $name ) {

		$retval = NULL;
		switch( $name ) {
			case 'status':
				$retval = array(
											10 	=> TTi18n::gettext('DISABLED'),
											20	=> TTi18n::gettext('ENABLED')
									);
				break;
			case 'type':
				$retval = array(
											10 	=> TTi18n::gettext('PC'),
									);

				if ( getTTProductEdition() >= 15 ) {
					$retval[20]	= TTi18n::gettext('PHONE');
					$retval[25]	= TTi18n::gettext('WirelessWeb');
					$retval[28]	= TTi18n::gettext('iPhone');
					$retval[30]	= TTi18n::gettext('iBUTTON');
					$retval[40]	= TTi18n::gettext('Barcode');
					$retval[50]	= TTi18n::gettext('FingerPrint');
					$retval[100] = TTi18n::gettext('TimeClock: TT-A8');
					$retval[110] = TTi18n::gettext('TimeClock: TT-F4');
					$retval[120] = TTi18n::gettext('TimeClock: TT-S300');
					$retval[200] = TTi18n::gettext('TimeClock: ACTAtek');
				}
				break;
			case 'station_reserved_word':
				$retval = array('any', '*');
				break;
			case 'source_reserved_word':
				$retval = array('any', '*');
				break;
			case 'branch_selection_type':
				$retval = array(
										10 => TTi18n::gettext('All Branches'),
										20 => TTi18n::gettext('Only Selected Branches'),
										30 => TTi18n::gettext('All Except Selected Branches'),
									);
				break;
			case 'department_selection_type':
				$retval = array(
										10 => TTi18n::gettext('All Departments'),
										20 => TTi18n::gettext('Only Selected Departments'),
										30 => TTi18n::gettext('All Except Selected Departments'),
									);
				break;
			case 'group_selection_type':
				$retval = array(
										10 => TTi18n::gettext('All Groups'),
										20 => TTi18n::gettext('Only Selected Groups'),
										30 => TTi18n::gettext('All Except Selected Groups'),
									);
				break;
			case 'poll_frequency':
				$retval = array(
										60 => TTi18n::gettext('1 Minute'),
										120 => TTi18n::gettext('2 Minutes'),
										300 => TTi18n::gettext('5 Minutes'),
										600 => TTi18n::gettext('10 Minutes'),
										900 => TTi18n::gettext('15 Minutes'),
										1800 => TTi18n::gettext('30 Minutes'),
										3600 => TTi18n::gettext('1 Hour'),
										7200 => TTi18n::gettext('2 Hours'),
										10800 => TTi18n::gettext('3 Hours'),
										21600 => TTi18n::gettext('6 Hours'),
										43200 => TTi18n::gettext('12 Hours'),
										86400 => TTi18n::gettext('24 Hours'),
									);
				break;
			case 'push_frequency':
				$retval = array(
										60 => TTi18n::gettext('1 Minute'),
										120 => TTi18n::gettext('2 Minutes'),
										300 => TTi18n::gettext('5 Minutes'),
										600 => TTi18n::gettext('10 Minutes'),
										900 => TTi18n::gettext('15 Minutes'),
										1800 => TTi18n::gettext('30 Minutes'),
										3600 => TTi18n::gettext('1 Hour'),
										7200 => TTi18n::gettext('2 Hours'),
										10800 => TTi18n::gettext('3 Hours'),
										21600 => TTi18n::gettext('6 Hours'),
										43200 => TTi18n::gettext('12 Hours'),
										86400 => TTi18n::gettext('24 Hours'),
									);
				break;
			case 'time_clock_command':
				$retval = array(
										'test_connection' => TTi18n::gettext('Test Connection'),
										'set_date' => TTi18n::gettext('Set Date'),
										'download' => TTi18n::gettext('Download Data'),
										'upload' => TTi18n::gettext('Upload Data'),
										'update_config' => TTi18n::gettext('Update Configuration'),
										'delete_data' => TTi18n::gettext('Delete all Data'),
										'reset_last_punch_time_stamp' => TTi18n::gettext('Reset Last Punch Time'),
										'clear_last_punch_time_stamp' => TTi18n::gettext('Clear Last Punch Time'),
										'restart' => TTi18n::gettext('Restart'),
										//'firmware' => TTi18n::gettext('Update Firmware'),
									);
				break;
			case 'mode_flag':
				$retval = array(
										1 =>  TTi18n::gettext('-- Default --'),
										2 =>  TTi18n::gettext('Must Select In/Out Status'),
										4 =>  TTi18n::gettext('Enable Work Code (Mode 1)'),
										8 =>  TTi18n::gettext('Enable Work Code (Mode 2)'),
									);
		}

		return $retval;
	}

	function getCompanyObject() {
		if ( is_object($this->company_obj) ) {
			return $this->company_obj;
		} else {
			$clf = new CompanyListFactory();
			$this->company_obj = $clf->getById( $this->getCompany() )->getCurrent();

			return $this->company_obj;
		}
	}

	function getCompany() {
		return $this->data['company_id'];
	}
	function setCompany($id) {
		$id = trim($id);

		$clf = new CompanyListFactory();

		if ( $this->Validator->isResultSetWithRows(	'company',
													$clf->getByID($id),
													TTi18n::gettext('Company is invalid')
													) ) {

			$this->data['company_id'] = $id;

			return TRUE;
		}

		return FALSE;
	}

	function getStatus() {
		if ( isset($this->data['status_id']) ) {
			return $this->data['status_id'];
		}

		return FALSE;
	}
	function setStatus($status) {
		$status = trim($status);

		$key = Option::getByValue($status, $this->getOptions('status') );
		if ($key !== FALSE) {
			$status = $key;
		}

		if ( $this->Validator->inArrayKey(	'status',
											$status,
											TTi18n::gettext('Incorrect Status'),
											$this->getOptions('status')) ) {

			$this->data['status_id'] = $status;

			return TRUE;
		}

		return FALSE;
	}

	function getType() {
		if ( isset($this->data['type_id']) ) {
			return $this->data['type_id'];
		}

		return FALSE;
	}
	function setType($type) {
		$type = trim($type);

		$key = Option::getByValue($type, $this->getOptions('type') );
		if ($key !== FALSE) {
			$type = $key;
		}

		if ( $this->Validator->inArrayKey(	'type',
											$type,
											TTi18n::gettext('Incorrect Type'),
											$this->getOptions('type')) ) {

			$this->data['type_id'] = $type;

			return TRUE;
		}

		return FALSE;
	}

	function isUniqueStation($station) {
		$ph = array(
					'company_id' => $this->getCompany(),
					'station' => $station,
					);

		$query = 'select id from '. $this->table .' where company_id = ? AND station_id = ? AND deleted=0';
		$id = $this->db->GetOne($query, $ph);
		Debug::Arr($id,'Unique Station: '. $station, __FILE__, __LINE__, __METHOD__,10);

		if ( $id === FALSE ) {
			return TRUE;
		} else {
			if ($id == $this->getId() ) {
				return TRUE;
			}
		}

		return FALSE;
	}

	function getStation() {
		if ( isset($this->data['station_id']) ) {
			return $this->data['station_id'];
		}

		return FALSE;
	}
	function setStation($station_id = NULL) {
		$station_id = trim($station_id);

		if ( empty($station_id) ) {
			$station_id = $this->genStationID();
		}

		if (	in_array(strtolower($station_id), $this->getOptions('station_reserved_word'))
				OR
				(
				$this->Validator->isLength(	'station_id',
											$station_id,
											TTi18n::gettext('Incorrect Station ID length'),
											2, 250 )
				AND
				$this->Validator->isTrue(	'station_id',
											$this->isUniqueStation($station_id),
											TTi18n::gettext('Station ID already exists'))
				)
			) {

			$this->data['station_id'] = $station_id;

			return TRUE;
		}

		return FALSE;
	}

	function getSource() {
		if ( isset($this->data['source']) ) {
			return $this->data['source'];
		}

		return FALSE;
	}
	function setSource($source) {
		$source = trim($source);

		if ( 	in_array(strtolower($source), $this->getOptions('source_reserved_word') )
				OR
				(
				$source != NULL
				AND
				$this->Validator->isLength(	'source',
											$source,
											TTi18n::gettext('Incorrect Source ID length'),
											2, 250 )
				)
			) {

			$this->data['source'] = $source;

			return TRUE;
		}

		return FALSE;
	}

	function getDescription() {
		if ( isset($this->data['description']) ) {
			return $this->data['description'];
		}

		return FALSE;
	}
	function setDescription($description) {
		$description = trim($description);

		if ( $this->Validator->isLength(	'description',
											$description,
											TTi18n::gettext('Incorrect Description length'),
											0, 255 ) ) {

			$this->data['description'] = $description;

			return TRUE;
		}

		return FALSE;
	}

	function getDefaultBranch() {
		if ( isset($this->data['branch_id']) ) {
			return (int)$this->data['branch_id'];
		}

		return FALSE;
	}
	function setDefaultBranch($id) {
		$id = trim($id);

		Debug::Text('Branch ID: '. $id, __FILE__, __LINE__, __METHOD__,10);
		$blf = new BranchListFactory();

		if (
				$id == 0
				OR
				$this->Validator->isResultSetWithRows(	'default_branch',
														$blf->getByID($id),
														TTi18n::gettext('Invalid Default Branch')
													) ) {

			$this->data['branch_id'] = $id;

			return TRUE;
		}

		return FALSE;
	}

	function getDefaultDepartment() {
		if ( isset($this->data['department_id']) ) {
			return (int)$this->data['department_id'];
		}

		return FALSE;
	}
	function setDefaultDepartment($id) {
		$id = trim($id);

		Debug::Text('Department ID: '. $id, __FILE__, __LINE__, __METHOD__,10);
		$dlf = new DepartmentListFactory();

		if (
				$id == 0
				OR
				$this->Validator->isResultSetWithRows(	'default_department',
														$dlf->getByID($id),
														TTi18n::gettext('Invalid Default Department')
													) ) {

			$this->data['department_id'] = $id;

			return TRUE;
		}

		return FALSE;
	}

	function getTimeZone() {
		if ( isset($this->data['time_zone']) ) {
			return $this->data['time_zone'];
		}

		return FALSE;
	}
	function setTimeZone($time_zone) {
		$time_zone = trim($time_zone);

		$upf = new UserPreferenceFactory();

		$key = Option::getByValue($time_zone, $upf->getOptions('time_zone') );
		if ($key !== FALSE) {
			$time_zone = $key;
		}

		if ( $time_zone == 0
				OR
				$this->Validator->inArrayKey(	'time_zone',
											$time_zone,
											TTi18n::gettext('Incorrect Time Zone'),
											$upf->getOptions('time_zone')) ) {

			$this->data['time_zone'] = $time_zone;

			return TRUE;
		}

		return FALSE;
	}

	function getGroupSelectionType() {
		if ( isset($this->data['user_group_selection_type_id']) ) {
			return $this->data['user_group_selection_type_id'];
		}

		return FALSE;
	}
	function setGroupSelectionType($value) {
		$value = trim($value);

		if ( $this->Validator->inArrayKey(	'user_group_selection_type',
											$value,
											TTi18n::gettext('Incorrect Group Selection Type'),
											$this->getOptions('group_selection_type')) ) {

			$this->data['user_group_selection_type_id'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getGroup() {
		$lf = new StationUserGroupListFactory();
		$lf->getByStationId( $this->getId() );
		foreach ($lf as $obj) {
			$list[] = $obj->getGroup();
		}

		if ( isset($list) ) {
			return $list;
		}

		return FALSE;
	}
	function setGroup($ids) {
		Debug::text('Setting IDs...', __FILE__, __LINE__, __METHOD__, 10);
		if ( is_array($ids) ) {
			if ( !$this->isNew() ) {
				//If needed, delete mappings first.
				$lf_a = new StationUserGroupListFactory();
				$lf_a->getByStationId( $this->getId() );

				$tmp_ids = array();
				foreach ($lf_a as $obj) {
					$id = $obj->getGroup();
					Debug::text('Group ID: '. $obj->getGroup() .' ID: '. $id, __FILE__, __LINE__, __METHOD__, 10);

					//Delete users that are not selected.
					if ( !in_array($id, $ids) ) {
						Debug::text('Deleting: '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$obj->Delete();
					} else {
						//Save ID's that need to be updated.
						Debug::text('NOT Deleting : '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$tmp_ids[] = $id;
					}
				}
				unset($id, $obj);
			}

			//Insert new mappings.
			$lf_b = new UserGroupListFactory();

			foreach ($ids as $id) {
				if ( isset($ids) AND !in_array($id, $tmp_ids) ) {
					$f = new StationUserGroupFactory();
					$f->setStation( $this->getId() );
					$f->setGroup( $id );

					$obj = $lf_b->getById( $id )->getCurrent();

					if ($this->Validator->isTrue(		'group',
														$f->Validator->isValid(),
														TTi18n::gettext('Selected Group is invalid').' ('. $obj->getName() .')' )) {
						$f->save();
					}
				}
			}

			return TRUE;
		}

		Debug::text('No IDs to set.', __FILE__, __LINE__, __METHOD__, 10);
		return FALSE;
	}

	function getBranchSelectionType() {
		if ( isset($this->data['branch_selection_type_id']) ) {
			return $this->data['branch_selection_type_id'];
		}

		return FALSE;
	}
	function setBranchSelectionType($value) {
		$value = trim($value);

		if ( $this->Validator->inArrayKey(	'branch_selection_type',
											$value,
											TTi18n::gettext('Incorrect Branch Selection Type'),
											$this->getOptions('branch_selection_type')) ) {

			$this->data['branch_selection_type_id'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getBranch() {
		$lf = new StationBranchListFactory();
		$lf->getByStationId( $this->getId() );
		foreach ($lf as $obj) {
			$list[] = $obj->getBranch();
		}

		if ( isset($list) ) {
			return $list;
		}

		return FALSE;
	}
	function setBranch($ids) {
		Debug::text('Setting IDs...', __FILE__, __LINE__, __METHOD__, 10);
		if ( is_array($ids) ) {
			if ( !$this->isNew() ) {
				//If needed, delete mappings first.
				$lf_a = new StationBranchListFactory();
				$lf_a->getByStationId( $this->getId() );

				$tmp_ids = array();
				foreach ($lf_a as $obj) {
					$id = $obj->getBranch();
					Debug::text('Branch ID: '. $obj->getBranch() .' ID: '. $id, __FILE__, __LINE__, __METHOD__, 10);

					//Delete users that are not selected.
					if ( !in_array($id, $ids) ) {
						Debug::text('Deleting: '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$obj->Delete();
					} else {
						//Save ID's that need to be updated.
						Debug::text('NOT Deleting : '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$tmp_ids[] = $id;
					}
				}
				unset($id, $obj);
			}

			//Insert new mappings.
			$lf_b = new BranchListFactory();

			foreach ($ids as $id) {
				if ( isset($ids) AND !in_array($id, $tmp_ids) ) {
					$f = new StationBranchFactory();
					$f->setStation( $this->getId() );
					$f->setBranch( $id );

					$obj = $lf_b->getById( $id )->getCurrent();

					if ($this->Validator->isTrue(		'branch',
														$f->Validator->isValid(),
														TTi18n::gettext('Selected Branch is invalid').' ('. $obj->getName() .')' )) {
						$f->save();
					}
				}
			}

			return TRUE;
		}

		Debug::text('No IDs to set.', __FILE__, __LINE__, __METHOD__, 10);
		return FALSE;
	}

	function getDepartmentSelectionType() {
		if ( isset($this->data['department_selection_type_id']) ) {
			return $this->data['department_selection_type_id'];
		}

		return FALSE;
	}
	function setDepartmentSelectionType($value) {
		$value = trim($value);

		if ( $this->Validator->inArrayKey(	'department_selection_type',
											$value,
											TTi18n::gettext('Incorrect Department Selection Type'),
											$this->getOptions('department_selection_type')) ) {

			$this->data['department_selection_type_id'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getDepartment() {
		$lf = new StationDepartmentListFactory();
		$lf->getByStationId( $this->getId() );
		foreach ($lf as $obj) {
			$list[] = $obj->getDepartment();
		}

		if ( isset($list) ) {
			return $list;
		}

		return FALSE;
	}
	function setDepartment($ids) {
		Debug::text('Setting IDs...', __FILE__, __LINE__, __METHOD__, 10);
		if ( is_array($ids) ) {
			if ( !$this->isNew() ) {
				//If needed, delete mappings first.
				$lf_a = new StationDepartmentListFactory();
				$lf_a->getByStationId( $this->getId() );

				$tmp_ids = array();
				foreach ($lf_a as $obj) {
					$id = $obj->getDepartment();
					Debug::text('Department ID: '. $obj->getDepartment() .' ID: '. $id, __FILE__, __LINE__, __METHOD__, 10);

					//Delete users that are not selected.
					if ( !in_array($id, $ids) ) {
						Debug::text('Deleting: '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$obj->Delete();
					} else {
						//Save ID's that need to be updated.
						Debug::text('NOT Deleting : '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$tmp_ids[] = $id;
					}
				}
				unset($id, $obj);
			}

			//Insert new mappings.
			$lf_b = new DepartmentListFactory();

			foreach ($ids as $id) {
				if ( isset($ids) AND !in_array($id, $tmp_ids) ) {
					$f = new StationDepartmentFactory();
					$f->setStation( $this->getId() );
					$f->setDepartment( $id );

					$obj = $lf_b->getById( $id )->getCurrent();

					if ($this->Validator->isTrue(		'department',
														$f->Validator->isValid(),
														TTi18n::gettext('Selected Department is invalid').' ('. $obj->getName() .')' )) {
						$f->save();
					}
				}
			}

			return TRUE;
		}

		Debug::text('No IDs to set.', __FILE__, __LINE__, __METHOD__, 10);
		return FALSE;
	}

	function getIncludeUser() {
		$lf = new StationIncludeUserListFactory();
		$lf->getByStationId( $this->getId() );
		foreach ($lf as $obj) {
			$list[] = $obj->getIncludeUser();
		}

		if ( isset($list) ) {
			return $list;
		}

		return FALSE;
	}
	function setIncludeUser($ids) {
		Debug::text('Setting IDs...', __FILE__, __LINE__, __METHOD__, 10);
		if ( is_array($ids) ) {
			if ( !$this->isNew() ) {
				//If needed, delete mappings first.
				$lf_a = new StationIncludeUserListFactory();
				$lf_a->getByStationId( $this->getId() );

				$tmp_ids = array();
				foreach ($lf_a as $obj) {
					$id = $obj->getIncludeUser();
					Debug::text('IncludeUser ID: '. $obj->getIncludeUser() .' ID: '. $id, __FILE__, __LINE__, __METHOD__, 10);

					//Delete users that are not selected.
					if ( !in_array($id, $ids) ) {
						Debug::text('Deleting: '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$obj->Delete();
					} else {
						//Save ID's that need to be updated.
						Debug::text('NOT Deleting : '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$tmp_ids[] = $id;
					}
				}
				unset($id, $obj);
			}

			//Insert new mappings.
			$lf_b = new UserListFactory();

			foreach ($ids as $id) {
				if ( isset($ids) AND !in_array($id, $tmp_ids) ) {
					$f = new StationIncludeUserFactory();
					$f->setStation( $this->getId() );
					$f->setIncludeUser( $id );

					$obj = $lf_b->getById( $id )->getCurrent();

					if ($this->Validator->isTrue(		'include_user',
														$f->Validator->isValid(),
														TTi18n::gettext('Selected Employee is invalid').' ('. $obj->getFullName() .')' )) {
						$f->save();
					}
				}
			}

			return TRUE;
		}

		Debug::text('No IDs to set.', __FILE__, __LINE__, __METHOD__, 10);
		return FALSE;
	}
	function getExcludeUser() {
		$lf = new StationExcludeUserListFactory();
		$lf->getByStationId( $this->getId() );
		foreach ($lf as $obj) {
			$list[] = $obj->getExcludeUser();
		}

		if ( isset($list) ) {
			return $list;
		}

		return FALSE;
	}
	function setExcludeUser($ids) {
		Debug::text('Setting IDs...', __FILE__, __LINE__, __METHOD__, 10);
		if ( is_array($ids) ) {
			if ( !$this->isNew() ) {
				//If needed, delete mappings first.
				$lf_a = new StationExcludeUserListFactory();
				$lf_a->getByStationId( $this->getId() );

				$tmp_ids = array();
				foreach ($lf_a as $obj) {
					$id = $obj->getExcludeUser();
					Debug::text('ExcludeUser ID: '. $obj->getExcludeUser() .' ID: '. $id, __FILE__, __LINE__, __METHOD__, 10);

					//Delete users that are not selected.
					if ( !in_array($id, $ids) ) {
						Debug::text('Deleting: '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$obj->Delete();
					} else {
						//Save ID's that need to be updated.
						Debug::text('NOT Deleting : '. $id, __FILE__, __LINE__, __METHOD__, 10);
						$tmp_ids[] = $id;
					}
				}
				unset($id, $obj);
			}

			//Insert new mappings.
			$lf_b = new UserListFactory();

			foreach ($ids as $id) {
				if ( isset($ids) AND !in_array($id, $tmp_ids) ) {
					$f = new StationExcludeUserFactory();
					$f->setStation( $this->getId() );
					$f->setExcludeUser( $id );

					$obj = $lf_b->getById( $id )->getCurrent();

					if ($this->Validator->isTrue(		'exclude_user',
														$f->Validator->isValid(),
														TTi18n::gettext('Selected Employee is invalid').' ('. $obj->getFullName() .')' )) {
						$f->save();
					}
				}
			}

			return TRUE;
		}

		Debug::text('No IDs to set.', __FILE__, __LINE__, __METHOD__, 10);
		return FALSE;
	}



	/*

		TimeClock specific fields

	*/
	function getPort() {
		if ( isset($this->data['port']) ) {
		return $this->data['port'];
		}

		return FALSE;
	}
	function setPort($value) {
		$value = trim($value);

		if ( $value == ''
				OR
				$this->Validator->isNumeric(	'port',
											$value,
											TTi18n::gettext('Incorrect port')
											) ) {

			$this->data['port'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getUserName() {
		if ( isset($this->data['user_name']) ) {
			return $this->data['user_name'];
		}

		return FALSE;
	}
	function setUserName($value) {
		$value = trim($value);

		if ( $this->Validator->isLength(	'user_name',
											$value,
											TTi18n::gettext('Incorrect User Name length'),
											0, 255 ) ) {

			$this->data['user_name'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getPassword() {
		if ( isset($this->data['password']) ) {
			return $this->data['password'];
		}

		return FALSE;
	}
	function setPassword($value) {
		$value = trim($value);

		if ( $this->Validator->isLength(	'password',
											$value,
											TTi18n::gettext('Incorrect Password length'),
											0, 255 ) ) {

			$this->data['password'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getPollFrequency() {
		if ( isset($this->data['poll_frequency']) ) {
			return $this->data['poll_frequency'];
		}

		return FALSE;
	}
	function setPollFrequency($value) {
		$value = trim($value);

		if ( $this->Validator->inArrayKey(	'poll_frequency',
											$value,
											TTi18n::gettext('Incorrect Download Frequency'),
											$this->getOptions('poll_frequency')) ) {

			$this->data['poll_frequency'] = $value;

			return TRUE;
		}

		return FALSE;
	}


	function getPushFrequency() {
		if ( isset($this->data['push_frequency']) ) {
			return $this->data['push_frequency'];
		}

		return FALSE;
	}
	function setPushFrequency($value) {
		$value = trim($value);

		if ( $this->Validator->inArrayKey(	'push_frequency',
											$value,
											TTi18n::gettext('Incorrect Upload Frequency'),
											$this->getOptions('push_frequency')) ) {

			$this->data['push_frequency'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getPartialPushFrequency() {
		if ( isset($this->data['partial_push_frequency']) ) {
			return $this->data['partial_push_frequency'];
		}

		return FALSE;
	}
	function setPartialPushFrequency($value) {
		$value = trim($value);

		if ( $this->Validator->inArrayKey(	'partial_push_frequency',
											$value,
											TTi18n::gettext('Incorrect Partial Upload Frequency'),
											$this->getOptions('push_frequency')) ) {

			$this->data['partial_push_frequency'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getEnableAutoPunchStatus() {
		return $this->fromBool( $this->data['enable_auto_punch_status'] );
	}
	function setEnableAutoPunchStatus($bool) {
		$this->data['enable_auto_punch_status'] = $this->toBool($bool);

		return TRUE;
	}

	function getModeFlag() {
		if ( isset($this->data['mode_flag']) ) {
			return Option::getArrayByBitMask( $this->data['mode_flag'], $this->getOptions('mode_flag'));
		}

		return FALSE;
	}
	function setModeFlag($arr) {
		$bitmask = Option::getBitMaskByArray( $arr, $this->getOptions('mode_flag') );

		if ( $this->Validator->isNumeric(	'mode_flag',
											$bitmask,
											TTi18n::gettext('Incorrect Mode') ) ) {

			$this->data['mode_flag'] = $bitmask;

			return TRUE;
		}

		return FALSE;
	}

	function parseWorkCode( $work_code ) {
		$definition = $this->getWorkCodeDefinition();

		$work_code = str_pad( $work_code, 9, 0, STR_PAD_LEFT);

		$retarr = array( 'branch_id' => 0, 'department_id' => 0, 'job_id' => 0, 'job_item_id' => 0 );

		$start_digit = 0;
		if ( isset($definition['branch']) AND $definition['branch'] > 0 ) {
			$retarr['branch_id'] = (int)substr( $work_code, $start_digit, $definition['branch']);
			$start_digit += $definition['branch'];
		}

		if ( isset($definition['department']) AND $definition['department'] > 0 ) {
			$retarr['department_id'] = (int)substr( $work_code, $start_digit, $definition['department']);
			$start_digit += $definition['department'];
		}

		if ( isset($definition['job']) AND $definition['job'] > 0 ) {
			$retarr['job_id'] = (int)substr( $work_code, $start_digit, $definition['job']);
			$start_digit += $definition['job'];
		}

		if ( isset($definition['job_item']) AND $definition['job_item'] > 0 ) {
			$retarr['job_item_id'] = (int)substr( $work_code, $start_digit, $definition['job_item']);
			$start_digit += $definition['job_item'];
		}

		Debug::Arr($retarr, 'Parsed Work Code: ', __FILE__, __LINE__, __METHOD__, 10);

		return $retarr;
	}

	function getWorkCodeDefinition() {
		if ( isset($this->data['work_code_definition']) ) {
			return unserialize( $this->data['work_code_definition'] );
		}

		return FALSE;
	}
	function setWorkCodeDefinition($arr) {
		$arr = Misc::preSetArrayValues( $arr, array('branch', 'department', 'job', 'job_item'), 0);

		if ( is_array( $arr )
				AND ($arr['branch']+$arr['department']+$arr['job']+$arr['job_item']) == 9 ) {
			$this->data['work_code_definition'] = serialize( $arr );

			return TRUE;
		} else {
			$this->Validator->isTRUE(	'work_code_definition',
										FALSE,
										TTi18n::gettext('Incorrect work code field lengths, they must all add up to 9') );
		}

		return FALSE;
	}

	function getLastPunchTimeStamp( $raw = FALSE) {
		if ( isset($this->data['last_punch_time_stamp']) ) {
			if ( $raw === TRUE ) {
				return $this->data['last_punch_time_stamp'];
			} else {
				return TTDate::strtotime( $this->data['last_punch_time_stamp'] );
			}
		}

		return FALSE;
	}
	function setLastPunchTimeStamp($epoch = NULL) {
		$epoch = trim($epoch);

		if ($epoch == NULL) {
			$epoch = TTDate::getTime();
		}

		if 	(	$this->Validator->isDate(		'last_punch_time_stamp',
												$epoch,
												TTi18n::gettext('Incorrect Date')) ) {

			$this->data['last_punch_time_stamp'] = $epoch;

			return TRUE;
		}

		return FALSE;

	}

	function getLastPollDate() {
		if ( isset($this->data['last_poll_date']) ) {
			return $this->data['last_poll_date'];
		}

		return FALSE;
	}
	function setLastPollDate($epoch = NULL) {
		$epoch = trim($epoch);

		if ($epoch == NULL) {
			$epoch = TTDate::getTime();
		}

		if 	(	$this->Validator->isDate(		'last_poll_date',
												$epoch,
												TTi18n::gettext('Incorrect Date')) ) {

			$this->data['last_poll_date'] = $epoch;

			return TRUE;
		}

		return FALSE;

	}

	function getLastPollStatusMessage() {
		if ( isset($this->data['last_poll_status_message']) ) {
			return $this->data['last_poll_status_message'];
		}

		return FALSE;
	}
	function setLastPollStatusMessage($value) {
		$value = trim($value);

		if ( $this->Validator->isLength(	'last_poll_status_message',
											$value,
											TTi18n::gettext('Incorrect Status Message length'),
											0, 255 ) ) {

			$this->data['last_poll_status_message'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getLastPushDate() {
		if ( isset($this->data['last_push_date']) ) {
			return $this->data['last_push_date'];
		}

		return FALSE;
	}
	function setLastPushDate($epoch = NULL) {
		$epoch = trim($epoch);

		if ($epoch == NULL) {
			$epoch = TTDate::getTime();
		}

		if 	(	$this->Validator->isDate(		'last_push_date',
												$epoch,
												TTi18n::gettext('Incorrect Date')) ) {

			$this->data['last_push_date'] = $epoch;

			return TRUE;
		}

		return FALSE;

	}

	function getLastPushStatusMessage() {
		if ( isset($this->data['last_push_status_message']) ) {
			return $this->data['last_push_status_message'];
		}

		return FALSE;
	}
	function setLastPushStatusMessage($value) {
		$value = trim($value);

		if ( $this->Validator->isLength(	'last_push_status_message',
											$value,
											TTi18n::gettext('Incorrect Status Message length'),
											0, 255 ) ) {

			$this->data['last_push_status_message'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getLastPartialPushDate() {
		if ( isset($this->data['last_partial_push_date']) ) {
			return $this->data['last_partial_push_date'];
		}

		return FALSE;
	}
	function setLastPartialPushDate($epoch = NULL) {
		$epoch = trim($epoch);

		if ($epoch == NULL) {
			$epoch = TTDate::getTime();
		}

		if 	(	$this->Validator->isDate(		'last_partial_push_date',
												$epoch,
												TTi18n::gettext('Incorrect Date')) ) {

			$this->data['last_partial_push_date'] = $epoch;

			return TRUE;
		}

		return FALSE;

	}

	function getLastPartialPushStatusMessage() {
		if ( isset($this->data['last_partial_push_status_message']) ) {
			return $this->data['last_partial_push_status_message'];
		}

		return FALSE;
	}
	function setLastPartialPushStatusMessage($value) {
		$value = trim($value);

		if ( $this->Validator->isLength(	'last_partial_push_status_message',
											$value,
											TTi18n::gettext('Incorrect Status Message length'),
											0, 255 ) ) {

			$this->data['last_partial_push_status_message'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getUserValue1() {
		if ( isset($this->data['user_value_1']) ) {
			return $this->data['user_value_1'];
		}

		return FALSE;
	}
	function setUserValue1($value) {
		$value = trim($value);

		if (	$value == ''
				OR
				$this->Validator->isLength(	'user_value_1',
											$value,
											TTi18n::gettext('User Value 1 is invalid'),
											1,255) ) {

			$this->data['user_value_1'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getUserValue2() {
		if ( isset($this->data['user_value_2']) ) {
			return $this->data['user_value_2'];
		}

		return FALSE;
	}
	function setUserValue2($value) {
		$value = trim($value);

		if (	$value == ''
				OR
				$this->Validator->isLength(	'user_value_2',
											$value,
											TTi28n::gettext('User Value 2 is invalid'),
											2,255) ) {

			$this->data['user_value_2'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getUserValue3() {
		if ( isset($this->data['user_value_3']) ) {
			return $this->data['user_value_3'];
		}

		return FALSE;
	}
	function setUserValue3($value) {
		$value = trim($value);

		if (	$value == ''
				OR
				$this->Validator->isLength(	'user_value_3',
											$value,
											TTi38n::gettext('User Value 3 is invalid'),
											3,255) ) {

			$this->data['user_value_3'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getUserValue4() {
		if ( isset($this->data['user_value_4']) ) {
			return $this->data['user_value_4'];
		}

		return FALSE;
	}
	function setUserValue4($value) {
		$value = trim($value);

		if (	$value == ''
				OR
				$this->Validator->isLength(	'user_value_4',
											$value,
											TTi48n::gettext('User Value 4 is invalid'),
											4,255) ) {

			$this->data['user_value_4'] = $value;

			return TRUE;
		}

		return FALSE;
	}

	function getUserValue5() {
		if ( isset($this->data['user_value_5']) ) {
			return $this->data['user_value_5'];
		}

		return FALSE;
	}
	function setUserValue5($value) {
		$value = trim($value);

		if (	$value == ''
				OR
				$this->Validator->isLength(	'user_value_5',
											$value,
											TTi58n::gettext('User Value 5 is invalid'),
											5,255) ) {

			$this->data['user_value_5'] = $value;

			return TRUE;
		}

		return FALSE;
	}



	private function genStationID() {
		return md5( uniqid( dechex( mt_srand() ) ) );
	}

	function setCookie() {
		if ( $this->getStation() ) {

			setcookie('StationID', $this->getStation(), time()+999999999, Environment::getBaseURL() );

			return TRUE;
		}

		return FALSE;
	}

	function destroyCookie() {
		setcookie('StationID', NULL, time()+9999999, Environment::getBaseURL() );

		return TRUE;
	}
/*
	function getUser() {
		$sulf = new StationUserListFactory();
		$sulf->getByStationId( $this->getId() );
		foreach ($sulf as $station_user) {
			$user_list[] = $station_user->getUser();
		}

		if ( isset($user_list) ) {
			return $user_list;
		}

		return FALSE;
	}
	function setUser($ids) {
		if (is_array($ids) and count($ids) > 0) {
			if ( in_array(0, $ids ) ) {
				Debug::text('All Users is selected: ', __FILE__, __LINE__, __METHOD__, 10);
				$ids = array(0);
			}

			//If needed, delete mappings first.
			$sulf = new StationUserListFactory();
			$sulf->getByStationId( $this->getId() );

			$user_ids = array();
			foreach ($sulf as $station_user) {
				$user_id = $station_user->getUser();
				Debug::text('Station ID: '. $station_user->getStation() .' User: '. $user_id, __FILE__, __LINE__, __METHOD__, 10);

				//Delete users that are not selected.
				if ( !in_array($user_id, $ids) ) {
					Debug::text('Deleting StationUser: '. $user_id, __FILE__, __LINE__, __METHOD__, 10);
					$station_user->Delete();
				} else {
					//Save branch ID's that need to be updated.
					Debug::text('NOT Deleting StationUser: '. $user_id, __FILE__, __LINE__, __METHOD__, 10);
					$user_ids[] = $user_id;
				}
			}

			//Insert new mappings.
			$suf = new StationUserFactory();
			foreach ($ids as $id) {
				if ( !in_array($id, $user_ids) ) {
					$suf->setStation( $this->getId() );
					$suf->setUser( $id );

					if ($this->Validator->isTrue(		'user',
														$suf->Validator->isValid(),
														TTi18n::gettext('Incorrect Employee selection'))) {
						$suf->save();
					}
				}
			}

			return TRUE;
		}

		return FALSE;
	}
*/

	function getAllowedDate() {
		if ( isset($this->data['allowed_date']) ) {
			return $this->data['allowed_date'];
		}

		return FALSE;
	}
	function setAllowedDate($epoch = NULL) {
		$epoch = trim($epoch);

		if ($epoch == NULL) {
			$epoch = TTDate::getTime();
		}

		if 	(	$this->Validator->isDate(		'allowed_date',
												$epoch,
												TTi18n::gettext('Incorrect Date')) ) {

			$this->data['allowed_date'] = $epoch;

			return TRUE;
		}

		return FALSE;

	}

	function checkSource( $source, $current_station_id ) {
		$source = trim($source);

		if ( isset($_SERVER['REMOTE_ADDR']) ) {
			$remote_addr = $_SERVER['REMOTE_ADDR'];
		} else {
			$remote_addr = NULL;
		}
		if ( isset($_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$x_forwarded_for = NULL;
		}

		//IGNORE x_forwarded_for for now, because anyone could spoof this.
		//Add a switch that will enable/disable this feature.

		//$remote_addr = '192.168.2.10';
		//$remote_addr = '192.168.1.10';
		//$remote_addr = '127.0.0.1';

		if ( in_array( $this->getType(), array(10,25) ) AND preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(\/[0-9]{1,2})*/', $source) ) {
			Debug::text('Source is an IP address!', __FILE__, __LINE__, __METHOD__, 10);
		} elseif ( in_array( $this->getType(), array(10,25) ) )  {
			Debug::text('Source is NOT an IP address, do hostname lookup: '. $source , __FILE__, __LINE__, __METHOD__, 10);

			$hostname_lookup = $this->getCache( $remote_addr.$source );
			if ( $hostname_lookup === FALSE ) {
				$hostname_lookup = gethostbyname( $source );

				$this->saveCache($hostname_lookup, $remote_addr.$source );
			}

			if ($hostname_lookup == $source ) {
				Debug::text('Hostname lookup failed!', __FILE__, __LINE__, __METHOD__, 10);
			} else {
				Debug::text('Hostname lookup succeeded: '. $hostname_lookup, __FILE__, __LINE__, __METHOD__, 10);
				$source = $hostname_lookup;
			}
			unset($hostname_lookup);
		} else {
			Debug::text('Source is not internet related', __FILE__, __LINE__, __METHOD__, 10);
		}

		Debug::text('Source: '. $source .' Remote IP: '. $remote_addr .' Behind Proxy IP: '. $x_forwarded_for, __FILE__, __LINE__, __METHOD__, 10);
		if ( 	(
					$current_station_id == $this->getStation()
						OR in_array( strtolower( $this->getStation() ), $this->getOptions('station_reserved_word') )
				)
				AND
				(
					in_array( strtolower( $this->getSource() ), $this->getOptions('source_reserved_word') )
					OR
						( $source == $remote_addr
							/*OR $source == $x_forwarded_for*/ )
					OR
						( $current_station_id == $this->getSource() )
					OR
						( Net_IPv4::ipInNetwork( $remote_addr, $source) )
					OR
						in_array( $this->getType(), array(100,110,120,200) )
				)

			) {

			Debug::text('Returning TRUE', __FILE__, __LINE__, __METHOD__, 10);

			return TRUE;
		}

		Debug::text('Returning FALSE', __FILE__, __LINE__, __METHOD__, 10);
		return FALSE;
	}

	function isAllowed($user_id = NULL, $current_station_id = NULL, $id = NULL) {
		if ($user_id == NULL OR $user_id == '') {
			global $current_user;
			$user_id = $current_user->getId();
		}
		Debug::text('User ID: '. $user_id, __FILE__, __LINE__, __METHOD__, 10);

		if ($current_station_id == NULL OR $current_station_id == ''){
			global $current_station;
			$current_station_id = $current_station->getStation();
		}
		Debug::text('Station ID: '. $current_station_id, __FILE__, __LINE__, __METHOD__, 10);

		Debug::text('Status: '. $this->getStatus(), __FILE__, __LINE__, __METHOD__, 10);
		if ( $this->getStatus() != 20 ) { //Enabled
			return FALSE;
		}

		$retval = FALSE;

		Debug::text('Current Station: '. $this->getStation() , __FILE__, __LINE__, __METHOD__, 10);

		//Handle IP Addresses/Hostnames
		if ( $this->getType() == 10
				AND !in_array( strtolower( $this->getSource() ), $this->getOptions('source_reserved_word') ) ) {

			if ( strpos( $this->getSource(), ',') !== FALSE ) {
				//Found list
				$source = explode(',', $this->getSource() );
			} else {
				//Found single entry
				$source[] = $this->getSource();
			}

			if ( is_array($source) ) {
				foreach( $source as $tmp_source ) {
					if ( $this->checkSource( $tmp_source, $current_station_id ) == TRUE ) {
						$retval = TRUE;
						break;
					}
				}
				unset($tmp_source);
			}
		} else {
			$source = $this->getSource();

			$retval = $this->checkSource( $source, $current_station_id );
		}

		Debug::text('Retval: '. (int)$retval, __FILE__, __LINE__, __METHOD__, 10);
		//Debug::text('Current Station ID: '. $current_station_id .' Station ID: '. $this->getStation(), __FILE__, __LINE__, __METHOD__, 10);

		if ( $retval === TRUE ) {
			Debug::text('Station IS allowed! ', __FILE__, __LINE__, __METHOD__, 10);

			//Set last allowed date, so we can track active/inactive stations.
			if ( $id != NULL AND $id != '' ) {
				$slf = new StationListFactory();
				$slf->getById( $id );
				foreach ($slf as $station_obj) {
					$station_obj->setAllowedDate();
					$station_obj->Save();
					Debug::text('Updating last allowed time for station.', __FILE__, __LINE__, __METHOD__, 10);
				}
				unset($slf, $station_obj);

				TTLog::addEntry( $id, 'Allow',  TTi18n::getText('Access from station Allowed'), $user_id, $this->getTable() );
			}

			return TRUE;
		}

		Debug::text('Station IS NOT allowed! ', __FILE__, __LINE__, __METHOD__, 10);

		return FALSE;
	}

	//A fast way to check many stations if the user is allowed.
	function checkAllowed($user_id = NULL, $station_id = NULL, $type = 'PC') {
		if ($user_id == NULL OR $user_id == '') {
			global $current_user;
			$user_id = $current_user->getId();
		}
		Debug::text('User ID: '. $user_id, __FILE__, __LINE__, __METHOD__, 10);

		if ($station_id == NULL OR $station_id == ''){
			global $current_station;
			if ( is_object($current_station) ) {
				$station_id = $current_station->getStation();
			} elseif ( $this->getId() != '' ) {
				$station_id = $this->getId();
			} else {
				Debug::text('Unable to get Station Object! Station ID: '. $station_id, __FILE__, __LINE__, __METHOD__, 10);
				return FALSE;
			}
		}
		Debug::text('Station ID: '. $station_id, __FILE__, __LINE__, __METHOD__, 10);

		$slf = new StationListFactory();
		$slf->getByUserIdAndStatusAndType($user_id, 'ENABLED', $type);
		foreach($slf as $station) {
			Debug::text('Checking Station ID: '. $station->getId(), __FILE__, __LINE__, __METHOD__, 10);

			if ( $station->isAllowed( $user_id, $station_id, $station->getId() ) === TRUE) {
				Debug::text('Station IS allowed! '. $station_id .' - ID: '. $station->getId() , __FILE__, __LINE__, __METHOD__, 10);
				return TRUE;
			}
		}

		return FALSE;
	}

	function preSave() {
		//New stations are deny all by default, so if they haven't
		//set the selection types, default them to only selected, so
		//everyone is denied, because none are selected.
		if ( $this->getGroupSelectionType() == FALSE ) {
			$this->setGroupSelectionType( 20 ); //Only selected.
		}
		if ( $this->getBranchSelectionType() == FALSE ) {
			$this->setBranchSelectionType( 20 ); //Only selected.
		}
		if ( $this->getDepartmentSelectionType() == FALSE ) {
			$this->setDepartmentSelectionType( 20 ); //Only selected.
		}

		return TRUE;
	}

	function postSave() {
		$this->removeCache( $this->getStation() );
/*
		foreach ($this->getUser() as $user_id ) {
			$cache_id = 'station::checkAllowed_'.$this->getId().$user_id;
			$this->removeCache( $cache_id );
		}
*/
		return TRUE;
	}

	function addLog( $log_action ) {
		return TTLog::addEntry( $this->getId(), $log_action,  TTi18n::getText('Station'), NULL, $this->getTable() );
	}
}
?>
