<?php
/**
* @version	$Id: users_item.php 15137 2012-03-04 08:06:21Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class UsersItem extends kDBItem {

		/**
		 * Returns IDs of groups to which user belongs and membership is not expired
		 *
		 * @param bool $force_reload
		 * @return Array
		 * @access public
		 */
		public function getMembershipGroups($force_reload = false)
		{
			$user_groups = $this->Application->RecallVar('UserGroups');

			if ( $user_groups === false || $force_reload ) {
				// primary group goes first
				$sql = 'SELECT GroupId
						FROM ' . TABLE_PREFIX . 'UserGroupRelations
						WHERE (PortalUserId = ' . $this->GetID() . ') AND ( (MembershipExpires IS NULL) OR (MembershipExpires >= ' . adodb_mktime() . ') )
						ORDER BY IF(GroupId = ' . $this->GetDBField('PrimaryGroupId') . ', 1, 0) DESC';
				$groups = $this->Conn->GetCol($sql);

				$user_helper = $this->Application->recallObject('UserHelper');
				/* @var $user_helper UserHelper */

				$user_groups = Array ();
				$ip_restrictions = $user_helper->getGroupsWithIPRestrictions();

				foreach ($groups as $group_id) {
					if ( !isset($ip_restrictions[$group_id]) || kUtil::ipMatch($ip_restrictions[$group_id], "\n") ) {
						$user_groups[] = $group_id;
					}
				}

				return $user_groups;
			}

			return explode(',', $user_groups);
		}

		function SendEmailEvents()
		{
			switch ( $this->GetDBField('Status') ) {
				case STATUS_ACTIVE:
					$event_name = $this->Application->ConfigValue('User_Password_Auto') ? 'USER.VALIDATE' : 'USER.ADD';
					$this->Application->EmailEventAdmin($event_name);
					$this->Application->EmailEventUser($event_name, $this->GetID());
					break;

				case STATUS_PENDING:
					$this->Application->EmailEventAdmin('USER.ADD.PENDING');
					$this->Application->EmailEventUser('USER.ADD.PENDING', $this->GetID());
					break;
			}
		}

		/**
		 * Checks that user is subscriber only
		 *
		 * @return bool
		 */
		public function isSubscriberOnly()
		{
			return $this->GetDBField('PrimaryGroupId') == $this->Application->ConfigValue('User_SubscriberGroup');
		}

		/**
		 * Checks that user is subscribed
		 *
		 * @return bool
		 */
		public function isSubscribed()
		{
			$group_id = $this->Application->ConfigValue('User_SubscriberGroup');

			$sql = 'SELECT GroupId
					FROM ' . TABLE_PREFIX . 'UserGroupRelations
					WHERE (PortalUserId = ' . $this->GetID() . ') AND (GroupId = ' . $group_id . ')';

			return $this->Conn->GetOne($sql);
		}

		/**
		 * Creates a record in the database table with current item' values
		 *
		 * @param mixed $force_id Set to TRUE to force creating of item's own ID or to value to force creating of passed id. Do not pass 1 for true, pass exactly TRUE!
		 * @param bool $system_create
		 * @return bool
		 * @access public
		 */
		public function Create($force_id = false, $system_create = false)
		{
			$ret = parent::Create($force_id, $system_create);
			if ( $ret ) {
				// find out how to synchronize user only when it's copied to live table
				$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array (), Array ('InPortalSyncronize'));
				/* @var $sync_manager UsersSyncronizeManager */

				$sync_manager->performAction('createUser', $this->FieldValues);
			}
			return $ret;
		}

		/**
		 * Updates previously loaded record with current item' values
		 *
		 * @access public
		 * @param int $id Primary Key Id to update
		 * @param bool $system_update
		 * @return bool
		 * @access public
		 */
		public function Update($id = null, $system_update = false)
		{
			$ret = parent::Update($id, $system_update);

			if ( $ret ) {
				// find out how to synchronize user only when it's copied to live table
				$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array (), Array ('InPortalSyncronize'));
				/* @var $sync_manager UsersSyncronizeManager */

				$sync_manager->performAction('updateUser', $this->FieldValues);
			}

			return $ret;
		}

		/**
		 * Deletes the record from database
		 *
		 * @param int $id
		 * @return bool
		 * @access public
		 */
		public function Delete($id = null)
		{
			$ret = parent::Delete($id);

			if ( $ret ) {
				$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array (), Array ('InPortalSyncronize'));
				/* @var $sync_manager UsersSyncronizeManager */

				$sync_manager->performAction('deleteUser', $this->FieldValues);
			}

			return $ret;
		}

		function setName($full_name)
		{
			$full_name = explode(' ', $full_name);

			if (count($full_name) > 2) {
				$last_name = array_pop($full_name);
				$first_name = implode(' ', $full_name);
			}
			else {
				$last_name = $full_name[1];
				$first_name = $full_name[0];
			}

			$this->SetDBField('FirstName', $first_name);
			$this->SetDBField('LastName', $last_name);
		}

		/**
		 * Generates new password for given user
		 *
		 * @param int $length
		 * @return string
		 * @access public
		 */
		public function generatePassword($length = 10)
		{
			$password = kUtil::generatePassword($length);

			$this->SetField('Password', $password);
			$this->SetField('VerifyPassword', $password);

			return $password;
		}
	}