<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*
* Author: Atmail
*/

require_once('library/Atmail/Abook/AbookAbstract.php');
	
class Atmail_Abook_SQL extends Atmail_Abook_Abstract
{
	public function __construct(array $args = null)
	{
		parent::__construct($args);
		
		//CONSIDER: adding an instance of this class to the session/cache will include all the data, however is all the data needed, possilby if common (shared/global) contacts being hit alot
		$this->_tableNames = new dbTables();
		$this->AbookTableName = $this->_tableNames->Abook;			// actual table which contains all abook entries for the user
		$this->AbookPermissions = $this->_tableNames->AbookPermissions;		// used for shared abook permissions

		$this->AbookGroupTableName = $this->_tableNames->AbookGroup;
		$this->AbookGroupNames = $this->_tableNames->AbookGroupNames;
		
		$this->allowedFields = array(
             'UserEmail',
             'UserEmail2',
             'UserEmail3',
             'UserEmail4',
             'UserEmail5',
             'UserFirstName',
             'UserMiddleName',
             'UserLastName',
             'UserTitle',
             'UserGender',
             'UserDOB',
             'UserHomeAddress',
             'UserHomeCity',
             'UserHomeState',
             'UserHomeZip',
             'UserHomeCountry',
             'UserHomePhone',
             'UserHomeMobile',
             'UserHomeFax',
             'UserURL',
             'UserWorkCompany',
             'UserWorkTitle',
             'UserWorkDept',
             'UserWorkOffice',
             'UserWorkAddress',
             'UserWorkCity',
             'UserWorkState',
             'UserWorkZip',
             'UserWorkCountry',
             'UserWorkPhone',
             'UserWorkMobile',
             'UserWorkFax',
             'UserType',
             'UserInfo',
             'EntryID',
             'UserInfo',
             'DateModified',
             'UserPhoto',
             'Global',
             'Shared',
             'Favourite',
             'VCardData',
             'CardDAVUrl',
             'SIP',
         );

	}
	
	public function TestServer()
	{
		
		return true;
		
	}
	
	public function Count( $groupID = '')
	{	

		if($groupID == '')
		{

			// total personal
			// TODO: Must be Zend DB query, not manual query string
			$q = 'SELECT count(`id`) as Total FROM ' . $this->AbookTableName . ' WHERE Account = ' . $this->dbAdapter->quote($this->_account);
			$arr = $this->dbAdapter->fetchAll($q);
			return $arr[0]['Total'];

		}
					
		if($groupID == 0)
		{
			//All

			$tableInUse = $this->AbookTableName;
			$q = 'SELECT count(DISTINCT ' . $this->AbookTableName . '.id) as GroupCount FROM ' . $this->AbookTableName . ' left join ' . $this->AbookGroupTableName . ' on AbookID = Abook.id WHERE Abook.Account = ' . $this->dbAdapter->quote($this->_account) . ' AND (shared is null or shared = 0) and (GroupID != -3 or GroupID is NULL) group by ' . $this->AbookTableName . '.id';
		}
		else if( $groupID == -1 ) 
		{
			//global

			$tableInUse = $this->AbookTableName;
			$q = "SELECT COUNT(`Global`) as GroupCount FROM `" . $this->AbookTableName . "` WHERE Global = '1'";
		}
		else
		{
			// Select group contacts

			$tableInUse = $this->AbookGroupTableName;
			$q = 'SELECT count(`AbookID`) as GroupCount FROM ' . $tableInUse . ' WHERE Account = ' . $this->dbAdapter->quote($this->_account) . ' AND GroupID = ' . $this->dbAdapter->quote($groupID, Zend_Db::INT_TYPE);
		}

		if($this->GroupwareZone == GROUPWARE_DOMAIN_ZONE)
		{
			// ********** GLOBAL FROM USER DOMAIN ONLY ***********
			$q = $q . ' AND ' . $tableInUse . '.Account like ' . $this->dbAdapter->quote('%@' . $this->_domain);
		}

		$arr = $this->dbAdapter->fetchAll($q);
		return $arr[0]['GroupCount'];

	}
	
	public function StorePhoto(array $arguments = null)
	{
	
		$data = array();
		$data['UserPhoto'] = $arguments['UserPhoto'];

		if($arguments['GroupID'] >= 0 && !$this->_admin )
			$where = ' AND Account = ' . $this->dbAdapter->quote($this->_account);
		else
			$where = ' AND Global=1';
		
		if( array_key_exists('DateAdded', $arguments) )
			$data['DateModified'] = Unix_to_Outlook_Timestamp_GMT( MySQL_Locale_to_Unix_GMT($arguments['DateAdded']) );
		else
			$data['DateModified'] = $this->outlookDate();
		return $this->dbAdapter->update($this->AbookTableName, $data, 'id = ' . $this->dbAdapter->quote($arguments['id'], Zend_Db::INT_TYPE) . $where );	
	
	}
	
	private function generatePermissions($id)
	{

		// Select from both the Abook and Abookpermissions table
		$rows = $this->dbAdapter->select()
				->from("AbookPermissions", array("Account"))
				->where("AbookID = " . $this->dbAdapter->quote($id, Zend_Db::INT_TYPE))
				->query()->fetchAll();
		// make a flat array of the permissions found
		$permissions = array();	
		foreach($rows as $row) {
			$permissions[] = $row['Account'];
		}
		
		return implode(',', $permissions);
	}
	
	public function GetPhoto(array $arguments = null)
	{
		parent::Get($arguments);
		
		$select = $this->dbAdapter->select('UserPhoto')
			->distinct()
			->from($this->AbookTableName, 'UserPhoto')
			->where('id = ' . $this->dbAdapter->quote($arguments['id'], Zend_Db::INT_TYPE) );

		/*
		// Alow global abook photos to appear - Security in controller for groupware on/off
		if( !$this->_admin && (!isset($arguments['admin']) || $arguments['admin'] != true) )
		{	
			$select->where('Account = ' . $this->dbAdapter->quote( $this->_account ));	
		}
        */

		return $select->query()->fetchAll();	
	
	}
	
	public function Get(array $arguments = array() )
	{
		parent::Get($arguments);
		
		$groupwareZone = GROUPWARE_PERSONAL_ZONE;
		$id = CONTACT_INVALID_ID;
		$GroupID = CONTACT_INVALID_GROUP_ID;
		$sharedAbookEnabled = GROUPWARE_SHARED_ABOOK_ENABLED;
		$GroupName = '';
		$admin = 0;
		$sort = -1;
		$order = -1;
		$returnArray = 0;
		$sortUsage = 0;
        $carddavUrl = null;
		
		if(isset($arguments['sharedAbookEnabled'])) $sharedAbookEnabled = $arguments['sharedAbookEnabled'];
		if(isset($arguments['groupwareZone'])) $groupwareZone = $arguments['groupwareZone'];
		if(isset($arguments['id'])) $id = $arguments['id'];
        if(isset($arguments['CardDAVUrl'])) $carddavUrl = $arguments['CardDAVUrl'];
		if(isset($arguments['GroupID'])) $GroupID = $arguments['GroupID'];
		if(isset($arguments['GroupName'])) $GroupName = $arguments['GroupName'];
		if(isset($arguments['admin'])) $admin = $arguments['admin'];
		if(isset($arguments['sort'])) $sort = $arguments['sort'];
		if(isset($arguments['order'])) $order = $arguments['order'];
		if(isset($arguments['returnArray'])) $returnArray = $arguments['returnArray'];
		
		// grab the contacts table, all request use it
		$select = $this->dbAdapter->select()
				->from($this->AbookTableName, array('contactId' => $this->AbookTableName . '.id', 'Abook.*'));
		// TODO: Investigate $groupwareZone == GROUPWARE_DISABLED && sharedAbookEnabled != GROUPWARE_SHARED_ABOOK_ENABLED - they the same?!

		if( $id != CONTACT_INVALID_ID || !is_null($carddavUrl))
		{

            if ($id != CONTACT_INVALID_ID) {
                $primarySelector = 'id = ' . $this->dbAdapter->quote($id, Zend_Db::INT_TYPE);
            } else {
                $primarySelector = 'CardDAVUrl = ' . $this->dbAdapter->quote($carddavUrl);
            }

			// ************* SINGLE CONTACT *************	
			if(	$groupwareZone != GROUPWARE_DISABLED 
			&&	$groupwareZone != GROUPWARE_PERSONAL_ZONE
			&& 	$GroupID == GROUP_GLOBAL 
			&&	$sharedAbookEnabled == GROUPWARE_SHARED_ABOOK_ENABLED ) 
			{
				// ********** GLOBAL ***********
				$select	= $select->where($primarySelector)
						->where('Global = 1');
							
				if($groupwareZone == GROUPWARE_DOMAIN_ZONE)
				{
					// ********** GLOBAL FROM USER DOMAIN ONLY ***********
					$select = $select->where('Account like ' . $this->dbAdapter->quote('%@' . $this->_domain) );
				}
			
			}
			else if($GroupID == GROUP_SHARED) 
			{	
				// ********** SHARED ***********
	
				// Select the Shared Addressbook
				// TODO: Add permissions/lookup table like Atmail5
				// Select from both the Abook and Abookpermissions table
				$select = $select->from($this->AbookPermissions, array('Permissions', ''))
						->where($this->AbookTableName . '.' . $primarySelector)
						->where($this->AbookTableName . '.id = ' . $this->AbookPermissions . '.AbookID')
						->where("AbookPermissions.Account = ? OR AbookPermissions.Account = ? OR AbookPermissions.Account = 'All Users' OR AbookPermissions.Account = 'Default'", array($this->_account));
																				
			}
			else
			{
				// ********** PERSONAL ***********
	
				$select = $select->where($primarySelector);
	
				if( !$admin )
				{
					$select = $select->where($this->AbookTableName . '.Account = ' . $this->dbAdapter->quote($this->_account) );
				}
			}
						
			$contacts = $select->query()->fetchAll();
	
			// there should be at least one!
			if( count($contacts) != 1)
			{	
				return NULL;	
			}
				
			// If a Shared element exists, query the list of Permissions
			if(!empty($contacts[0]['Shared']))
				$contacts[0]['Permissions'] = $this->generatePermissions($contacts[0]['id']);
			if(!$returnArray)
			{
				$contacts = $contacts[0];
			}
		}
		else
		{

			// ************* MULTI CONTACTS ************

			if( 	$GroupID == GROUP_GLOBAL 
			&& 	$sharedAbookEnabled == GROUPWARE_SHARED_ABOOK_ENABLED 
			&& 	$groupwareZone == GROUPWARE_SYSTEM_ZONE	) 
			{
				// Select the Global addressbook
				// Select all records that match the groupID reference ( Do not refer to the Groupname )
				$select = $select->where($this->AbookTableName . '.Global = 1');
			} 
			elseif( $GroupID == GROUP_GLOBAL 
			&& 	$sharedAbookEnabled == GROUPWARE_SHARED_ABOOK_ENABLED 
			&& 	$groupwareZone == GROUPWARE_DOMAIN_ZONE	) 
			{
				// Select the Global addressbook
				// Select all records that match the groupID reference ( Do not refer to the Groupname )
				$select = $select->where($this->AbookTableName . '.Global = 1')
				   	  	  ->where($this->AbookTableName . '.Account like ' . $this->dbAdapter->quote('%@' . $this->_domain));
			} 
			elseif( $GroupID == GROUP_SHARED) 
			{
				// Select the Shared addressbook
				// Select all records that match the groupID reference ( Do not refer to the Groupname )
				// TODO: Find a solution for multiple placeholders on the "where"
				// TODO: Create a global instance to get the account name, user-group, domain name
				// e.g $this->session->Account, $this->session->Ugroup, $this->session->username, $this->session->domain
				$select = $select->from($this->AbookPermissions, array('Permissions', ''))
						->where($this->AbookTableName . '.id = ' . $this->AbookPermissions . '.AbookID')
						->where("AbookPermissions.Account = ? OR AbookPermissions.Account = ? OR AbookPermissions.Account = 'All Users' OR AbookPermissions.Account = 'Default'", array($this->_account));
			}
			elseif( $GroupID == GROUP_AUTO) 
			{
				// Select all records that match the groupID reference ( Do not refer to the Groupname )
				$select = $select->from($this->AbookGroupTableName)
						->where($this->AbookTableName . '.id = ' . $this->AbookGroupTableName . '.AbookID')
						->where($this->AbookGroupTableName . '.GroupID = ' . $this->dbAdapter->quote($GroupID, Zend_Db::INT_TYPE));
				if( !$this->_admin )
					$select->where($this->AbookTableName . '.Account = ' . $this->dbAdapter->quote($this->_account) );	
			}
			elseif( $GroupID == GROUP_FAV) 
			{
				// Select all records that match the groupID reference ( Do not refer to the Groupname )
				$select = $select->where('(UsageCount > 0 and Favourite is NULL) or (UsageCount = 0 and Favourite = 1) or Favourite = 1');
				if( !$this->_admin )
					$select->where('Account = ' . $this->dbAdapter->quote($this->_account) );

				$arguments[Atmail_Enum::ID_LIMIT] = 20;
				$sort = $arguments['sort'] = 'UsageCount';
				$order = $arguments['order'] = 'desc';
			}
			elseif( $GroupID != CONTACT_INVALID_GROUP_ID && $GroupID != 0)		// original code used !empty which includes GroupID == 0
			{

				// Select all records that match the groupID reference ( Do not refer to the Groupname )
				$select = $select->from($this->AbookGroupTableName)
						->from($this->AbookGroupNames)
						->where($this->AbookTableName . '.id = ' . $this->AbookGroupTableName . '.AbookID')
						->where($this->AbookGroupNames . '.id = ' . $this->dbAdapter->quote($GroupID, Zend_Db::INT_TYPE))
						->where($this->AbookGroupNames . '.id = ' . $this->AbookGroupTableName . '.GroupID');
				if( !$this->_admin )
					$select->where($this->AbookTableName . '.Account = ' . $this->dbAdapter->quote($this->_account) );

			}
			else
			{

				// just personal accounts
				$select = $select->joinLeft($this->AbookGroupTableName, $this->AbookGroupTableName . '.AbookID = ' . $this->AbookTableName . '.id', array('gid' => $this->AbookGroupTableName . '.id'));
				$select = $select->where($this->AbookTableName . '.Shared = 0 or ' . $this->AbookTableName . '.Shared is null')->where($this->AbookGroupTableName . '.GroupID != ' . GROUP_AUTO . ' OR ' . $this->AbookGroupTableName . '.GroupID is null');
				$select = $select->group('Abook.id');

				if( !$this->_admin )
					$select->where($this->AbookTableName . '.Account = ' . $this->dbAdapter->quote($this->_account) );
				
				if( $GroupName == CONTACT_UNDEFINED_GROUP)
				{

					$select->joinLeft($this->AbookGroupTableName, 'GroupEmail = UserEmail', array('gid' => $this->AbookGroupTableName . '.id'));
					$select->where('GroupName IS NULL');

				}

			}
			
			if( array_key_exists('emailOnly', $arguments) )
					$select->where('(UserEmail is not NULL and UserEmail != "") or (UserEmail2 is not NULL and UserEmail2 != "") or (UserEmail3 is not NULL and UserEmail3 != "") or (UserEmail4 is not NULL and UserEmail4 != "") or (UserEmail5 is not NULL and UserEmail5 != "")');

			// Add a limit if specified
			//N.B.: ZF ->limit($count, $offset)
			if( array_key_exists(Atmail_Enum::ID_LIMIT, $arguments) )
				if( array_key_exists('offset', $arguments) )
					$select->limit( $arguments[Atmail_Enum::ID_LIMIT], $arguments['offset']  );
				else
					$select->limit( $arguments[Atmail_Enum::ID_LIMIT] );
		
			if($sort != -1 && $order != -1)
				$contacts = $select->order($this->AbookTableName . '.' . $sort . ' ' . $order)->query()->fetchAll();
			else
				$contacts = $select->query()->fetchAll();	

		}

		return  $returnArray? $this->updateOnlineStatus($contacts) : $contacts;

	}

	public function updateOnlineStatus($contacts)
	{
		$where_in = "";

		foreach($contacts as $contact)
		{
			if(!empty($contact['UserEmail']))
			{
				$where_in .= $this->dbAdapter->quote($contact['UserEmail']) . ',';
			}
		}

		if(empty($where_in)) {
			return $contacts;
		}


		$where_in = substr($where_in, 0, -1);
		$sql = "select Account from UserSession where modified>unix_timestamp(now())-600 and Account in (" . $where_in . ")";

		$activeAccounts = $this->dbAdapter->fetchAll( $sql );

		foreach($contacts as $key=>$contact)
		{	
			if(array_key_exists('UserEmail', $contact))
			{
				foreach ($activeAccounts as $activeAccount)
				{
					if($contact['UserEmail'] == $activeAccount['Account'])
					{
						$contacts[$key]['online'] = true;
					}
				}				
			}
		}

		return $contacts;
	}
	
	public function Put(array $arguments = null)
	{	
		$data = array();
		foreach($arguments['contact'] as $k => $v ) 
		{
			
			if($k == 'UserDOB' && empty($v))
				continue;
				
			if( in_array($k, $this->allowedFields ) )
				$data[$k] = $v;		
		}
		
		$data['Account'] = $this->_account;
		
		//need to be able to specify DateAdded for SyncML to prevent duplications.
		if( array_key_exists('DateAdded', $arguments) )
		{
			
			$data['DateAdded'] = $arguments['DateAdded']; // DateAdded is MySQL Locale format
			$data['DateModified'] = Unix_to_Outlook_Timestamp_GMT( MySQL_Locale_to_Unix_GMT($arguments['DateAdded']) );
		
		}
		else
		{
			
			$data['DateAdded'] = new Zend_Db_Expr('NOW()'); //TODO: Warning: this will make MySQL Local based Timestamp
			$data['DateModified'] = $this->outlookDate();
			
		}
		if(!isset($data['Shared']) || $data['Shared'] == '')
			$data['Shared'] = 0;
		
		// Update for SQL strict mode, Shared must be 1 || 0
		if(empty($data['Shared']))
			$data['Shared'] = 0;
	
		// Before inserting, check this record is unique
		$this->dbAdapter->insert($this->AbookTableName, $data);
		$id = $this->dbAdapter->lastInsertId();
		
		if($data['Shared'] == 1)
		{
			//update the Permissions table
			if(isset($arguments['Permissions']))
			{
				$users = explode(',', $arguments['Permissions']);
			}
			else
			{
				$users = array();
			}
			// Always add our global account
			$users[] = $this->_account;
			// Check permissions first
			// $permissions = $this->checkPermissions($args['id])
				
			// Step 1: Delete abookpermissions
			$this->dbAdapter->delete("AbookPermissions", 'AbookID = ' . $this->dbAdapter->quote($arguments['id'], Zend_Db::INT_TYPE));
				
			$chk = array();	
			foreach($users as $user)
			{
				if(!empty($user) && empty($chk[$user]))
				{
					$this->dbAdapter->insert("AbookPermissions", array('Account' => $user, 'Permissions' => 1, 'AbookID' => $id) );
				}
				$chk[$user] = 1;
			}
			
		}

		return $id;
	}

	public function Delete(array $arguments = null)
	{
		parent::Delete($arguments);
	
		//TODO: add code to preserve shared contacts when ACL gets added
		//CONSIDER: delete group respecting the logical referential integrity (i.e. other users may still have access to this group)
		//BEN-NOTE: Rather then passing the entire $args record, do a query for the UserEmail and then delete from groups, then the final entry in the personal Abook table

		$where = array();        
		$where[] = $this->dbAdapter->quoteInto('id = ?', $arguments['id'], Zend_Db::INT_TYPE );
        
		$matches = $this->dbAdapter->select()->from('Abook')->where($where[0])->query()->fetchAll();
		if( count($matches) == 0 )
			throw new Exception('Abook::Delete - Error: Contact not found');
		
		if( $matches[0]['Global'] == '1' )
			return;
		// Do not throw an exception, its handled in the JS within the UI
		//throw new Exception('Abook::Delete - Error: You can\'t delete a Global contact');
		
		if( !$this->_admin )
		{
			// If a personal user, do not allow the deletion of the primary Global Abook entry
			$where[] = $this->dbAdapter->quoteInto('Account = ?', $this->_account );
			$where[] = new Zend_Db_Expr('(Global = 0 OR Global IS NULL)');
		}
		
		$affected = $this->dbAdapter->delete('Abook', $where );
		
		// Next, remove the user from any "Groups" created
		$where = array();        
		$where[] = $this->dbAdapter->quoteInto('AbookID = ?', $arguments['id'], Zend_Db::INT_TYPE );
        
		if( !$this->_admin )
			$where[] = $this->dbAdapter->quoteInto('Account = ?', $this->_account );
		
		$result = $this->dbAdapter->delete($this->AbookGroupTableName,  $where);
		
		return $affected;
		
	}

	public function Modify(array $arguments = null)
	{
		parent::Modify($arguments);
		
		$data = array();
	
		foreach($arguments as $k => $v ) {
	
			if($k == 'UserDOB' && ( empty($v) || $v == '0000-00-00') ) //if invalid date then blank
			$v = null;
	
			if( in_array($k, $this->allowedFields ) )
			$data[$k] = $v;
		}

		$where = array();
		$where[] = $this->dbAdapter->quoteInto('id = ?', $arguments['id'], Zend_Db::INT_TYPE);
	
		//if is Admin then implies only wanting to update a users' self record, so must only update the user self account, and not ALL users owned Abook contacts (unique compound key is && Global = 1)
		//WARNING: with current schema and rules, if user is able to add additional Global = 1 contacts then will contaminate unique key integrity if user adds additional Abook contacts for existing users
		if( $this->_admin )
		$where[] = 'Global = 1';
	
		if( empty($data['Shared']) )
			$where[] = $this->dbAdapter->quoteInto('Account = ?', $this->_account );
	
		$result = $this->dbAdapter->update($this->AbookTableName, $data, $where );
	
		if( isset($data['Shared']) )
		{
	
			// only if we are doing a full update
	
			//update the Permissions table
			if(isset($arguments['Permissions']))
			{
				$users = explode(',', $arguments['Permissions']);
			}
			else
			{
				$users = array();
			}
			// Always add our global account
			$users[] = $this->_account;
	
			// Check permissions first
			// $permissions = $this->checkPermissions($args['id])
	
			// Step 1: Delete abookpermissions
			$this->dbAdapter->delete("AbookPermissions", $this->dbAdapter->quoteInto('AbookID = ?', $arguments['id'], Zend_Db::INT_TYPE));
	
			if($data['Shared']==1)
			{
				$chk = array();
				foreach($users as $user)
				{
					if(!empty($user) && empty($chk[$user]))
					{
						$this->dbAdapter->insert("AbookPermissions", array('Account' => trim($user), 'Permissions' => 1, 'AbookID' => $arguments['id']) );
					}
					$chk[$user] = 1;
				}
			}
		}
	}

	public function outlookDate()
	{
		return sprintf("%.6f", gmdate("U", time()) / 60 / 1440 + 25569);
	}	

	public function Search(array $arguments = null)
	{
		if(isset($arguments['fuzzy']) && $arguments['fuzzy'] == 1)
		{
			$GroupID = (isset($arguments['GroupID']) ? $arguments['GroupID'] : (isset($arguments['groupID']) ? $arguments['groupID'] : 0));
			$query = "";
			foreach($arguments as $k => $v )
			{
										
				if( in_array($k, $this->allowedFields ) )
				{
					$query .= " $k like " . $this->dbAdapter->quote('%' . $v . '%') . " OR ";
				}
			}
	
			$query = preg_replace('/ OR $/', '', $query);
			// TODO: Must be Zend DB query, not manual query string
			
			if($GroupID == GROUP_GLOBAL && $this->GroupwareZone != GROUPWARE_DISABLED)
			{

				$q = 'SELECT id FROM ' . $this->AbookTableName . ' WHERE Global=1 AND ('. $query . ')';
				if($this->GroupwareZone == GROUPWARE_DOMAIN_ZONE)
				{
					// ********** GLOBAL FROM USER DOMAIN ONLY ***********
					$q = $q . ' AND Account like ' . $this->dbAdapter->quote('%@' . $this->_domain);
				}

			}
			else if ($GroupID == GROUP_SHARED && $this->GroupwareZone != GROUPWARE_DISABLED)
			{
				$q = 'SELECT id FROM ' . $this->AbookTableName . ' WHERE Shared=1 AND ('. $query . ')';
			
				if($this->GroupwareZone == GROUPWARE_DOMAIN_ZONE)
				{
					// ********** GLOBAL FROM USER DOMAIN ONLY ***********
					$q = $q . ' AND Account like ' . $this->dbAdapter->quote('%@' . $this->_domain);
				}
			}
			else
			{
				$q = 'SELECT id FROM ' . $this->AbookTableName . ' WHERE Account = ' . $this->dbAdapter->quote($this->_account) . ' AND ('. $query . ')';
			}
			
			if(isset($arguments[Atmail_Enum::ID_LIMIT]) && $arguments[Atmail_Enum::ID_LIMIT] != -1)
			{
				$q .= ' limit ' . $this->dbAdapter->quote($arguments[Atmail_Enum::ID_LIMIT], Zend_Db::INT_TYPE);
			}

			$arr = $this->dbAdapter->fetchAll($q);
	
			return $arr;		
		}
		else
		{
			$select = $this->dbAdapter->select('id')->from($this->AbookTableName, 'id');
	
			foreach($arguments AS $k => $v )
			{
				if( $k != 'UserPhoto' && (in_array($k, $this->allowedFields ) || $this->_admin))
				{
					$select->where("$k = " . $this->dbAdapter->quote($v)); //calling where like this is equivalent to AND
				}
			}
	
			if( !$this->_admin )
			{
				$select->where('Account = ' . $this->dbAdapter->quote($this->_account) );
			}
			
			$data = $select->query()->fetchAll();
	        
			if( isset($data[0]) && array_key_exists(0, $data) && !empty($data[0]['id']) )
			{
				return $data[0]['id'];
			}

			return 0;
		}
	}
}

