<?php
	/**
	* View and manipulate account records using the contacts class
	* @author Miles Lott <milosch@phpgroupware.org>
	* @copyright Copyright (C) 2000,2001 Miles Lott
    * @copyright Portions Copyright (C) 2004 Free Software Foundation, Inc. http://www.fsf.org/
	* @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
	* @package phpgwapi
	* @subpackage accounts
	* @version $Id: class.accounts_contacts.inc.php,v 1.1.1.3 2004/07/20 15:43:35 kazuyan Exp $
	*/

	/**
	* View and manipulate account records using the contacts class
	* @package phpgwapi
	* @subpackage accounts
	* @internal Milosch: THIS NEEDS WORK!!! 
	* @internal skwashd: But it is a lot closer now... This needs to go imho
	* @ignore
	*/
	class accounts extends accounts_
	{
		/**
		* Private contacts object
		* @var object phpgwapi.contacts object
		* @access private
		*/
		var $contacts;
		/**
		* Private account id
		* @var integer Account id
		* @access private
		*/
		var $account_id;
		/**
		* Private debug flag
		* @var boolean Debug mode for this class
		* @access private
		*/
		var $debug = False;
		/**
		* Private array filter for read operations
		* @var array Filter for read operations
		* @access private
		*/
		var $qcols = array(
			'fn'                     => 'fn',
			'n_given'                => 'n_given',
			'n_family'               => 'n_family',
			'account_lastlogin'      => 'account_lastlogin',
			'account_lastloginfrom'  => 'account_lastloginfrom',
			'account_lastpwd_change' => 'account_lastpwd_change',
			'account_status'         => 'account_status',
			'account_expires'        => 'account_expires'
		);

		/**
		* Constructor
		*/
		function accounts()
		{
			$this->accounts_($account_id = '', $account_type = '');
		}

		/**
		* Initialize contacts (singleton)
		*/
		function makeobj()
		{
			if(!$this->contacts)
			{
				$this->contacts = CreateObject('phpgwapi.contacts','0');
			}
		}

		/**
		* Read the contact entry for this account.
		* @return array Array with indices: userid, accound_id, account_lid, account_type, firstname, lastname, fullname, lastlogin, lastloginfrom, lastpasswd_change, status, expires
		*/
		function read_repository()
		{
			$this->makeobj();

			$allValues = $this->contacts->read_single_entry($this->account_id,$this->qcols);

			/* Now dump it into the array */
			$this->data['userid']            = $allValues[0]['lid'];
			$this->data['account_id']	     = $allValues[0]['id'];
			$this->data['account_lid'] 	     = $allValues[0]['lid'];
			$this->data['account_type']      = $allValues[0]['tid'];
			$this->data['firstname']   	     = $allValues[0]['n_given'];
			$this->data['lastname']    	     = $allValues[0]['n_family'];
			$this->data['fullname']    	     = $allValues[0]['fn'];
			$this->data['lastlogin']         = $allValues[0]['account_lastlogin'];
			$this->data['lastloginfrom']     = $allValues[0]['account_lastloginfrom'];
			$this->data['lastpasswd_change'] = $allValues[0]['account_lastpwd_change'];
			$this->data['status']            = $allValues[0]['account_status'];
			$this->data['expires']           = $allValues[0]['account_expires'];

			return $this->data;
		}

		/**
		* Save account information in contacts
		*/
		function save_repository()
		{
			$this->makeobj();

			$entry['id']                        = $this->data['account_id'];
			$entry['lid']                       = $this->data['account_lid'];
			$entry['tid']                       = $this->data['account_type'];
			$entry['fn']                        = sprintf("%s %s", $this->data['firstname'], $this->data['lastname']);
			$entry['n_family']                  = $this->data['lastname'];
			$entry['n_given']                   = $this->data['firstname'];
			$entry['account_lastlogin']         = $this->data['lastlogin'];
			$entry['account_lastloginfrom']     = $this->data['lastloginfrom'];
			$entry['account_lastpasswd_change'] = $this->data['lastpwd_change'];
			$entry['account_status']            = $this->data['status'];
			$entry['account_expires']           = $this->data['expires'];

			if($this->debug) { echo '<br />Updating entry:<br />' . var_dump($entry); }
			$this->contacts->update($entry['id'],0,$entry,'public','',$entry['tid']);
		}

		/**
		* Add a new account
		* @param string $account_name New account name
		* @param string $account_type Type of new account
		* @param string $first_name Firstname of new account owner
		* @param string $last_name Lastname of new account owner
		* @param string $passwd Password for the new account
		* @see create()
		*/
		function add($account_name, $account_type, $first_name, $last_name, $passwd = False) 
		{
			$this->create($account_name, $account_type, $first_name, $last_name, $passwd);
		}

		/**
		* Delete an account
		* @param string $accountid Id of the account to delete
		*/
		function delete($accountid = '')
		{
			$this->makeobj();

			if($this->debug) { echo '<br />Deleting entry:<br />' . $account_id; }
			$account_id = get_account_id($accountid);
			$this->contacts->delete($account_id);
		}

		/**
		* Get a list with information for each user/group
		* @param string $_type Could be 'account', 'groups' or the default 'both'
		*/
		function get_list($_type='both')
		{
			$this->makeobj();

			switch($_type)
			{
				case 'accounts':
					$filter = 'tid=u';
					break;
				case 'groups':
					$filter = 'tid=g';
					break;
				default:
					$filter = 'tid=u,tid=g';
			}

			$allValues = $this->contacts->read(0,0,$this->qcols,'',$filter);

			/* get user information for each user/group */
			for($i=0;$i<count($allValues);++$i)
			{
				$accounts[] = Array(
					'account_id'        => $allValues[$i]['id'],
					'account_lid'       => $allValues[$i]['lid'],
					'account_type'      => $allValues[$i]['tid'],
					'account_firstname' => $allValues[$i]['n_given'],
					'account_lastname'  => $allValues[$i]['n_family'],
					'account_status'    => $allValues[$i]['account_status'],
					'account_expires'   => $allValues[$i]['account_expires']
				);
			}

			return $accounts;
		}

		/**
		* Convert account name into account id
		* @param string $account_lid Account name
		* @return integer|boolean Account id or false
		*/
		function name2id($account_lid)
		{
			$qcols = array('id' => 'id');
			$this->makeobj();
			$allValues = $this->contacts->read(0,0,$qcols,'',"lid=".$account_lid);

			if($allValues[0]['id'])
			{
				return intval($allValues[0]['id']);
			}
			else
			{
				return False;
			}
		}

		/**
		* Convert account id into account name
		* @param integer $account_id Account id
		* @return string|boolean Account name or false
		*/
		function id2name($account_id)
		{
			global $phpgw, $phpgw_info;
			$this->makeobj();

			$allValues = $this->contacts->read_single_entry($account_id);
			if($this->debug) { echo '<br />id2name: '.$allValues[0]['lid']; }

			if($allValues[0]['lid'])
			{
				return $allValues[0]['lid'];
			}
			else
			{
				return False;
			}
		}

		/**
		* Get account type information
		* @param integer $accountid Account id
		* @return string|boolean Account type or false
		*/
		function get_type($accountid = '')
		{
			$this->makeobj();
			$account_id = get_account_id($accountid);

			$allValues = $this->contacts->read_single_entry($account_id);

			if ($allValues[0]['tid'])
			{
				return $allValues[0]['tid'];
			}
			else
			{
				return False;
			}
		}

		/**
		* Test if an account already exists
		* @param string $account_lid Account name
		* @return boolean True when the account already exists otherwise false
		*/
		function exists($account_lid)
		{
			$this->makeobj();
			if(gettype($account_lid) == 'integer')
			{
				$account_id = $account_lid;
				settype($account_lid,'string');
				$account_lid = $this->id2name($account_id);
			}

			$allValues = $this->contacts->read(0,0,array('n_given' => 'n_given'),'','lid='.$account_lid);

			if ($allValues[0]['id'])
			{
				return True;
			}
			else
			{
				return False;
			}
		}

		/**
		* Create an new account
		* @param array $account_info Information about the new account including account_id, account_lid, account_firstname, account_lastname, account_passwd, account_status, account_expires
		*/
		function create($account_info)
		{
			global $phpgw_info, $phpgw;
			$this->makeobj();

			if (!$$account_info['account_id'])
			{
				$account_info['account_id'] = $this->get_nextid();
			}
			$owner = $phpgw_info['user']['account_id'];
			$entry['id']       = $account_info['account_id'];
			$entry['lid']      = $account_info['account_lid'];
			$entry['n_given']  = $account_info['account_firstname'];
			$entry['n_family'] = $account_info['account_lastname'];
			$entry['password'] = $account_info['account_passwd'];
			$entry['account_status']   = $account_info['account_status'];
			$entry['account_expires']  = $account_info['account_expires'];

			if($this->debug) { echo '<br />Adding entry:<br />' . var_dump($entry); }
			/* 'public' access, no category id, tid set to account_type */
			$this->contacts->add(0,$entry,'public','',$account_info['account_type']);
		}

		/**
		* Automatically add an new account
		* @param string $accountname Name of the new account
		* @param string $passwd Password of the new account
		* @param boolean $default_prefs Use default preferences
		* @param boolean $default_acls Use default acl's
		* @param string $expiredate Date when this account expires
		* @param string $account_status Status of this account
		* @return integer Account id
		*/
		function auto_add($accountname, $passwd, $default_prefs = False, $default_acls = False, $expiredate = 0, $account_status = 'A')
		{
			global $phpgw, $phpgw_info;

			if (! $expiredate)
			{
				// expire in 30 days by default
				$expiredate = time() + ( ( 60 * 60 ) * (30 * 24) );
			}

			$acct_info = array(
				'account_lid'       => $accountname,
				'account_type'      => 'u',
				'account_passwd'    => $passwd,
				'account_firstname' => '',
				'account_lastname'  => '',
				'account_status'    => $account_status,
				'account_expires'   => mktime(2,0,0,date('n',$expiredate), intval(date('d',$expiredate)), date('Y',$expiredate))
			);
			$this->create($acct_info);
			$accountid = $this->name2id($accountname);

			$this->db->transaction_begin();
			if (!$default_prefs)
			{
				$default_prefs = 'a:5:{s:6:"common";a:10:{s:9:"maxmatchs";s:2:"15";s:12:"template_set";s:8:"verdilak";s:5:"theme";s:6:"purple";s:13:"navbar_format";s:5:"icons";s:9:"tz_offset";N;s:10:"dateformat";s:5:"m/d/Y";s:10:"timeformat";s:2:"12";s:4:"lang";s:2:"en";s:11:"default_app";N;s:8:"currency";s:1:"$";}s:11:"addressbook";a:1:{s:0:"";s:4:"True";}:s:8:"calendar";a:4:{s:13:"workdaystarts";s:1:"7";s:11:"workdayends";s:2:"15";s:13:"weekdaystarts";s:6:"Monday";s:15:"defaultcalendar";s:9:"month.php";}}';
//				$defaultprefs = 'a:5:{s:6:"common";a:1:{s:0:"";s:2:"en";}s:11:"addressbook";a:1:{s:0:"";s:4:"True";}s:8:"calendar";a:1:{s:0:"";s:13:"workdaystarts";}i:15;a:1:{s:0:"";s:11:"workdayends";}s:6:"Monday";a:1:{s:0:"";s:13:"weekdaystarts";}}';
				$this->db->query("insert into phpgw_preferences (preference_owner, preference_value) values ('".$accountid."', '$default_prefs')",__LINE__,__FILE__);
			}

			if (!$default_acls)
			{
				$apps = Array(
					'addressbook',
					'calendar',
					'email',
					'notes',
					'todo',
					'phpwebhosting',
					'manual'
				);

				$this->db->query("insert into phpgw_acl (acl_appname, acl_location, acl_account, acl_rights)values('preferences', 'changepassword', ".$accountid.", 1)",__LINE__,__FILE__);
				$this->db->query("insert into phpgw_acl (acl_appname, acl_location, acl_account, acl_rights) values('phpgw_group', '1', ".$accountid.", 1)",__LINE__,__FILE__);
				@reset($apps);
				while(list($key,$app) = each($apps))
				{
					$this->db->query("INSERT INTO phpgw_acl (acl_appname, acl_location, acl_account, acl_rights) VALUES ('".$app."', 'run', ".$accountid.", 1)",__LINE__,__FILE__);
				}
			}
			$this->db->transaction_commit();
			return $accountid;
		}
	}
