<?php
/**
* @version	$Id: groups_event_handler.php 16513 2017-01-20 14:10:53Z 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 GroupsEventHandler extends kDBEventHandler {

		/**
		 * Adds grouping by user id
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 * @see kDBEventHandler::OnListBuild()
		 */
		protected function SetCustomQuery(kEvent $event)
		{
			parent::SetCustomQuery($event);

			/** @var kDBList $object */
			$object = $event->getObject();

			switch ($event->Special) {
				case 'user':
					$user_id = $this->Application->GetVar('u_id');

					if ( $user_id !== false ) {
						// show only groups, that user doesn't belong to
						$table_name = $this->Application->GetTempName(TABLE_PREFIX . 'UserGroupRelations', 'prefix:u');

						$sql = 'SELECT GroupId
								FROM ' . $table_name . '
								WHERE PortalUserId = ' . (int)$user_id;
						$group_ids = $this->Conn->GetCol($sql);

						// add system groups
						array_push($group_ids, $this->Application->ConfigValue('User_GuestGroup')); // Guest
						array_push($group_ids, $this->Application->ConfigValue('User_LoggedInGroup')); // Everyone

						$object->addFilter('already_member_filter', '%1$s.GroupId NOT IN (' . implode(',', $group_ids) . ')');
					}
					break;
			}
		}

		/**
		 * Refreshes left tree on save
		 *
		 * @param kEvent $event
		 * @return void
		 * @access protected
		 */
		protected function OnSave(kEvent $event)
		{
			parent::OnSave($event);

			$this->Application->StoreVar('refresh_tree', 1);
		}
	}