<?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: Interface.inc.php 2158 2008-09-15 23:26:15Z ipso $
 * $Date: 2008-09-15 16:26:15 -0700 (Mon, 15 Sep 2008) $
 */

/* Use these lines to run scripts from the command line... for debugging.
  $_COOKIE['SessionID'] = '07bc520b3e90835ab586f0c585c4dd8f';
  $_SERVER['REMOTE_ADDR'] = '192.168.1.100';
*/

//Turn caching off.
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
//Can Break IE with downloading PDFs over SSL.
// IE gets: "file could not be written to cache"
// It works on some IE installs though.
// Comment out No-Cache and Pragma: No-Cache to fix issue.
header('Cache-Control: no-cache');
header('Cache-Control: post-check=0,pre-check=0');
header('Cache-Control: max-age=0');
header('Pragma: no-cache');
//Do not overwrite a previously sent content-type header, this breaks WAP.
if ( !isset($enable_wap) ) {
	header('Content-Type: text/html; charset=UTF-8');
}

$permission = new Permission();

$authentication = new Authentication();
if ( isset($authenticate) AND $authenticate === FALSE ) {
	Debug::text('Bypassing Authentication', __FILE__, __LINE__, __METHOD__, 10);
	TTi18n::chooseBestLocale();
} else {
	//Increase timeout on WAP devices, so they don't have to login as often.
	if ( isset($enable_wap) AND $enable_wap == TRUE ) {
		$authentication->setIdle( 32400 ); //9hrs
	} elseif ( isset($config_vars['other']['web_session_timeout']) AND $config_vars['other']['web_session_timeout'] != '' ) {
		$authentication->setIdle( (int)$config_vars['other']['web_session_timeout'] );
	}

	if ( $authentication->Check() === TRUE ) {
		/*
		 * Get default interface data here. Things like User info, Company info etc...
		 */

		$current_user = $authentication->getObject();
		Debug::text('User Authenticated: '. $current_user->getUserName() .' Created Date: '. $authentication->getCreatedDate(), __FILE__, __LINE__, __METHOD__, 10);

		//Check to make sure the logged in user's information is all up to date.
		if ( $current_user->isInformationComplete() == FALSE
				AND ( !stristr( $_SERVER['SCRIPT_NAME'], 'permissiondenied') AND !stristr( $_SERVER['SCRIPT_NAME'], 'logout') AND !stristr( $_SERVER['SCRIPT_NAME'], 'about') AND !stristr( $_SERVER['SCRIPT_NAME'], 'punch.php') AND !stristr( $_SERVER['SCRIPT_NAME'], 'ajax_server') AND !stristr( $_SERVER['SCRIPT_NAME'], 'global.js') AND !stristr( $_SERVER['SCRIPT_NAME'], 'menu.js') )
				AND !isset($_GET['incomplete']) AND !isset($_POST['incomplete']) ) {
			Redirect::Page( URLBuilder::getURL( array('id' => $current_user->getID(), 'incomplete' => 1 ), Environment::GetBaseURL().'users/EditUser.php') );
		}

		$db_time_zone_error = FALSE;
		$current_user_prefs = $current_user->getUserPreferenceObject();

		//If user doesnt have any preferences set, we need to bootstrap the preference object.
		if ( $current_user_prefs->getUser() == '' ) {
			$current_user_prefs->setUser( $current_user->getId() );
		}

		if ( $current_user_prefs->setDateTimePreferences() == FALSE ) {
			//Setting timezone failed, alert user to this fact.
			$db_time_zone_error = TRUE;
		}

		/*
		 *	Check locale cookie, if it varies from UserPreference Language,
		 *	change user preferences to match. This could cause some unexpected behavior
		 *  as the change is happening behind the scenes, but if we don't change
		 *  the user prefs then they could login for weeks/months as a different
		 *  language from their preferences, therefore making the user preference
		 *  setting almost useless. Causing issues when printing pay stubs and in each
		 *  users language.
		 */
		$profiler->startTimer( "setLocale()");
		Debug::text('Locale Cookie: '. TTi18n::getLocaleCookie() , __FILE__, __LINE__, __METHOD__, 10);
		if ( TTi18n::getLocaleCookie() != '' AND $current_user_prefs->getLanguage() !== TTi18n::getLanguageFromLocale( TTi18n::getLocaleCookie() ) ) {
			Debug::text('Changing User Preference Language to match cookie...', __FILE__, __LINE__, __METHOD__, 10);
			$current_user_prefs->setLanguage( TTi18n::getLanguageFromLocale( TTi18n::getLocaleCookie() ) );
			if ( $current_user_prefs->isValid() ) {
				$current_user_prefs->Save(FALSE);
			}
		} else {
			Debug::text('User Preference Language matches cookie!', __FILE__, __LINE__, __METHOD__, 10);
		}
		if ( isset($_GET['language']) AND $_GET['language'] != '' ) {
			TTi18n::setLocale( $_GET['language'] ); //Sets master locale
		} else {
			TTi18n::setLanguage( $current_user_prefs->getLanguage() );
			TTi18n::setCountry( $current_user->getCountry() );
			TTi18n::setLocale(); //Sets master locale
		}
		$profiler->stopTimer( "setLocale()");

		if ( $current_user->isInformationComplete() == TRUE
				AND $current_user_prefs->isPreferencesComplete() == FALSE
				AND ( !stristr( $_SERVER['SCRIPT_NAME'], 'permissiondenied') AND !stristr( $_SERVER['SCRIPT_NAME'], 'logout') AND !stristr( $_SERVER['SCRIPT_NAME'], 'about') AND !stristr( $_SERVER['SCRIPT_NAME'], 'punch.php') AND !stristr( $_SERVER['SCRIPT_NAME'], 'ajax_server') AND !stristr( $_SERVER['SCRIPT_NAME'], 'global.js') AND !stristr( $_SERVER['SCRIPT_NAME'], 'menu.js') )
				AND !isset($_GET['incomplete']) AND !isset($_POST['incomplete']) ) {
			Redirect::Page( URLBuilder::getURL( array('incomplete' => 1 ), Environment::GetBaseURL().'users/EditUserPreference.php') );
		}

		$clf = new CompanyListFactory();
		$current_company = $clf->getByID( $current_user->getCompany() )->getCurrent();
		unset($clf);

		//Get all system settings, so they can be used even if the user isn't logged in, such as the login page.
		$sslf = new SystemSettingListFactory();
		$system_settings = $sslf->getAllArray();
		unset($sslf);

		//Handle station functionality
		if ( isset( $_COOKIE['StationID'] ) ) {
			Debug::text('Station ID Cookie found! '. $_COOKIE['StationID'], __FILE__, __LINE__, __METHOD__, 10);

			$slf = new StationListFactory();
			$slf->getByStationIdandCompanyId( $_COOKIE['StationID'], $current_company->getId() );
			$current_station = $slf->getCurrent();
			unset($slf);
			if ( $current_station->isNew() ) {
				Debug::text('Station ID is NOT IN DB!! '. $_COOKIE['StationID'], __FILE__, __LINE__, __METHOD__, 10);
			}
		}
		//Debug::Arr($current_station, 'Current Station Object: ', __FILE__, __LINE__, __METHOD__, 10);
		//Debug::text('Current Company: '. $current_company->getName(), __FILE__, __LINE__, __METHOD__, 10);

		//Make sure CronJobs are running correctly.
		$cjlf = new CronJobListFactory();
		$cjlf->getMostRecentlyRun();
		if ( $cjlf->getRecordCount() > 0 ) {
			//Is last run job more then 48hrs old?
			$cj_obj = $cjlf->getCurrent();

			if ( PRODUCTION == TRUE
					AND DEMO_MODE == FALSE
					AND $cj_obj->getLastRunDate() < ( time()-172800 )
					AND $cj_obj->getCreatedDate() < ( time()-172800 ) ) {
				$cron_out_of_date = 1;
			} else {
				$cron_out_of_date = 0;
			}
		}
		unset($cjlf, $cj_obj);

	} else {
		Debug::text('User NOT! Authenticated', __FILE__, __LINE__, __METHOD__, 10);

		if ( isset($enable_wap) AND $enable_wap == TRUE ) {
			Redirect::Page( URLBuilder::getURL(NULL, Environment::GetBaseURL().'wap/wap_login.php') );
		} else {
			Redirect::Page( URLBuilder::getURL(NULL, Environment::GetBaseURL().'Login.php') );
		}

		//exit;
	}
}

require_once( Environment::getBasePath() .'classes'. DIRECTORY_SEPARATOR .'smarty'. DIRECTORY_SEPARATOR .'libs'. DIRECTORY_SEPARATOR .'Smarty.class.php');

$smarty = new Smarty;
$smarty->compile_check = TRUE;
$smarty->template_dir = Environment::getTemplateDir();
$smarty->compile_dir = Environment::getTemplateCompileDir();

$smarty->assign('css_file', 'global.css.php' );
$smarty->assign('IMAGES_URL', Environment::getImagesURL() );
$smarty->assign('BASE_PATH', Environment::getBasePath() );

$smarty->assign('APPLICATION_NAME', APPLICATION_NAME );
$smarty->assign('APPLICATION_VERSION', APPLICATION_VERSION );
$smarty->assign('DEPLOYMENT_ON_DEMAND', DEPLOYMENT_ON_DEMAND );

if ( isset($cron_out_of_date) ) {
	$smarty->assign('CRON_OUT_OF_DATE', $cron_out_of_date );
}

if ( isset($db_time_zone_error) ) {
	$smarty->assign('DB_TIME_ZONE_ERROR', $db_time_zone_error );
}

if ( isset($config_vars['other']['installer_enabled']) ) {
	$smarty->assign('INSTALLER_ENABLED', $config_vars['other']['installer_enabled'] );
}

if ( isset($system_settings['system_version']) AND DEPLOYMENT_ON_DEMAND == FALSE AND APPLICATION_VERSION != $system_settings['system_version'] ) {
	$smarty->assign('VERSION_MISMATCH', TRUE );
}

if ( isset($system_settings) ) {
	$smarty->assign_by_ref('system_settings', $system_settings );
}

if ( isset($current_company) ) {
	$smarty->assign_by_ref('current_company', $current_company );
}

if ( isset($config_vars) ) {
	$smarty->assign_by_ref('config_vars', $config_vars );
}

if ( TTi18n::getLanguage() != '' ) {
	$smarty->assign('CALENDAR_LANG', TTi18n::getLanguage() );
}else{
	$smarty->assign('CALENDAR_LANG', 'en');
}


if ( isset($current_user) )  {
	$smarty->assign_by_ref('current_user', $current_user );
	$smarty->assign_by_ref('current_user_prefs', $current_user_prefs );

	if ( !isset($skip_message_check) ) {
		$profiler->startTimer( "Interface.inc - Check for UNREAD messages...");

		//CHeck for unread messages
		$mlf = new MessageListFactory();
		$unread_messages = $mlf->getNewMessagesByUserId( $current_user->getId() );
		Debug::text('UnRead Messages: '. $unread_messages, __FILE__, __LINE__, __METHOD__, 10);
		$smarty->assign_by_ref('unread_messages', $unread_messages );
		if ( isset($_COOKIE['newMailPopUp']) ) {
			$smarty->assign_by_ref('newMailPopUp', $_COOKIE['newMailPopUp'] );
		}
		unset($mlf);

		$profiler->stopTimer( "Interface.inc - Check for UNREAD messages...");

		$profiler->startTimer( "Interface.inc - Check for Exceptions");

		$elf = new ExceptionListFactory();
		$elf->getFlaggedExceptionsByUserIdAndPayPeriodStatus( $current_user->getId(), 10 );
		if ( $elf->getRecordCount() > 0 ) {
			foreach($elf as $e_obj) {
				if ( $e_obj->getColumn('severity_id') == 30 ) {
					$display_exception_flag = 'red';
				} elseif ( $e_obj->getColumn('severity_id') == 20 ) {
					$display_exception_flag = 'yellow';
				}

				break;
			}

		}
		unset($elf, $e_obj);

		if ( isset($display_exception_flag) ) {
			Debug::text('Exception Flag to Display: '. $display_exception_flag, __FILE__, __LINE__, __METHOD__, 10);
			$smarty->assign_by_ref('display_exception_flag', $display_exception_flag );
			unset($display_exception_flag);
		}

		$profiler->stopTimer( "Interface.inc - Check for Exceptions");
	}
}
if ( isset($current_station) ) {
	$smarty->assign_by_ref('current_station', $current_station );
}

$smarty->assign('BASE_URL', Environment::getBaseURL() );
$smarty->assign('global_script_start_time', $global_script_start_time );
$smarty->assign('profiler', $profiler );
$smarty->assign_by_ref('permission', $permission );
?>