<?php
/**
* @version	$Id: user_profile_eh.php 14241 2011-03-16 20:24:35Z 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 UserProfileEventHandler extends kDBEventHandler {

		/**
		 * Allows to override standart permission mapping
		 *
		 */
		function mapPermissions()
		{
			parent::mapPermissions();
			$permissions = Array (
				'OnItemBuild'	=>	Array('subitem' => true),
				'OnUpdate'	=>	Array('subitem' => true),
			);

			$this->permMapping = array_merge($this->permMapping, $permissions);
		}

		/**
		 * Saves user profile to database
		 *
		 * @param kEvent $event
		 */
		function OnUpdate(&$event)
		{
			$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
			list ($user_id, $field_values) = each($items_info);

			if ($user_id != $this->Application->RecallVar('user_id')) {
				// we are not updating own profile
				return ;
			}

			$public_profile_add = Array ();
			$public_profile_remove = Array ();
			$profile_mapping = $this->Application->getUnitOption('u', 'UserProfileMapping');

			foreach ($field_values as $variable_name => $variable_value) {
				if (array_key_exists($variable_name, $profile_mapping)) {
					// old style variable for displaying fields in public profile (named "pp_*")
					if ($variable_value) {
						$public_profile_add[] = $profile_mapping[$variable_name];
					}
					else {
						$public_profile_remove[] = $profile_mapping[$variable_name];
					}
				}
				else {
					$this->Application->StorePersistentVar($variable_name, unhtmlentities($variable_value));
				}
			}

			if ($public_profile_add || $public_profile_remove) {
				$user =& $this->Application->recallObject('u.current');
				/* @var $user kDBItem */

				// get current value
				$display_to_public_old = $user->GetDBField('DisplayToPublic');
				$display_to_public_new = $display_to_public_old ? explode('|', substr($display_to_public_old, 1, -1)) : Array ();

				// update value
				$display_to_public_new = array_diff(array_merge($display_to_public_new, $public_profile_add), $public_profile_remove);
				$display_to_public_new = array_unique($display_to_public_new);
				$display_to_public_new = $display_to_public_new ? '|' . implode('|', $display_to_public_new) . '|' : '';

				if ($display_to_public_new != $display_to_public_old) {
					$user->SetDBField('DisplayToPublic', $display_to_public_new);
					$user->Update();
				}
			}
		}
	}