<?php
/**
 * @category 	Atmail
 * @package 	Outlook sync connector
 * @subpackage	Sync Model
 * @copyright 	Copyright (c) 2009-2011 ATMAIL. All rights reserved
 * @license 	See http://atmail.com/license.php for license agreement
 * @author		Atmail (http://atmail.com)
 */
require_once 'application/models/calendar.php';
require_once 'application/models/contacts.php';
require_once 'application/models/users.php';
		

class sync
{
	private $_session;
	private $_account;
	private $_tableNames;
	private $xml;
	private $username;
	private $password;
	private $enabled;
	private $shared_enabled;
	private $global_enabled;
	
	private $contacts;
	private $calendar;
	private $data;
	private $CalDavType;
	
	/*		if($xml)
			header("Content-type: text/xml;");
			*/

	public function __construct($xml)
	{	
		$this->dbAdapter = Zend_Registry::get('dbAdapter');
		$this->log = Zend_Registry::get('log');
	}
	
	public function init($user, $domain, $password)
	{
		// -1 == NOUSER
		// -2 == DISABLED
		
		// First, check the user account exists
		$matches = $this->dbAdapter->select("Account")->from("UserSession")->where("Account=" . $this->dbAdapter->quote("$user@$domain"))->query()->fetchAll();
		if( count($matches) != 1 )
		{
			return -1;
		}
		
		// Next, authorize the account
		// TODO add md5 enabled/disabled switch
		$matches = $this->dbAdapter->select("Account, password")->from("UserSession")->where("Account=" . $this->dbAdapter->quote("$user@$domain") . " and password=" . $this->dbAdapter->quote("$password"))->query()->fetchAll();
		if( count($matches) != 1 )
		{
			// try again with md5
			$matches = $this->dbAdapter->fetchAll("select Account, password from UserSession where Account=? and Password=MD5(?)", array("$user@$domain", $password));

			if( count($matches) != 1 )
			{
				return -1;
			}
		}
		$this->username = $matches[0]['Account'];
		$this->password = $matches[0]['Password'];
		
		
		//create the admin object to access group/user data
		try
		{
			require_once('application/models/api.php');
			$api = new api(array('Username' => $this->username, 'Password' => $this->password, 'directApi' => 1));
		
			$current_user = $api->userView($this->username, '');
			$current_user_group = $current_user['Ugroup'];
			$current_user_status = $current_user['UserStatus'];
		
			// TODO: follow user status
			$current_group = $api->groupGet($current_user_group);
			$current_group = $current_group['response']['results'];
			
			$this->enabled = $current_group['Sync'];
			$this->shared_enabled = $current_group['WebSyncShared'];
			$this->global_enabled = $current_group['WebSyncGlobal'];
			
			// clear the variables
			unset($current_group);
			unset($current_user);
			unset($api);
		}
		catch (Exception $e)
		{
			file_put_contents("php://stderr", "SYNC : Error fetch user/group data for " . $this->username . " (" . $e->getMessage() . ")\n");
			$this->enabled = 0;
		}
		
		// Disallow operation if disabled on server
		if (!$this->enabled)
		{
			return -2;
		}
	}
	
	function setData($data_in)
	{
		$this->data = $data_in;
	}

	function myurlencode ($v)
	{
		$v = urlencode($v);
		$v = str_replace("+", "%20", $v);
		return $v;
	}
	
	function httpheaders()
	{
		echo '<html><head><xml version="1.0" encoding="ISO-8859-1"></head>';
	}
	
	function httpend()
	{
		echo '</html>';
	}


	// LEGACY VERSION STRING
	// This is for old WebSync plug-ins that had a version bug.
	// Basically, if we don't the plugin will suddenly report
	// that the server has lost it's mind,
	// but it's really just a version string change.....
	function sync_version()
	{
		global $SERVER_VERSION;
	
		print $SERVER_VERSION . "\nSERVER CHECK\n";
		print("Shared = " . $this->shared_enabled . "\n");
		print("Global = " . $this->global_enabled . "\n");
	
		// Log the user was successful
	}
	
	function call($func)
	{
		$this->$func();
	}
	
	// version string for new websync that has some version logic...
	function sync_version_check()
	{
		return $this->sync_version();
	}
	
	function sync_updateurl()
	{
		print "http://atmail.com/downloads/getsync.php?v=" . Zend_registry::get('config')->global['version'];
	}

	function xmlbegin()
	{
		if($this->xml)
		{
			print "<Abook>\n";
		}
		return;
	}

	function xmlend()
	{
		if($this->xml)
		{
			print "</Abook>\n";
		}
		return;
	}
}

