<?php

/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -----------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2006 BoonEx Group
*     website              : http://www.boonex.com/
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software. This work is licensed under a Creative Commons Attribution 3.0 License. 
* http://creativecommons.org/licenses/by/3.0/
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Creative Commons Attribution 3.0 License for more details. 
* You should have received a copy of the Creative Commons Attribution 3.0 License along with Dolphin, 
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

require_once( 'inc/header.inc.php' );
require_once( BX_DIRECTORY_PATH_INC . 'design.inc.php' );
require_once( BX_DIRECTORY_PATH_INC . 'profiles.inc.php' );
require_once( BX_DIRECTORY_PATH_CLASSES . 'BxDolEmailTemplates.php' );

$_page['name_index'] = 44;

$logged['member'] = member_auth(0);

$sourceID = getLoggedId();
$targetID = ( isset($_GET['ID']) ) ? (int)$_GET['ID'] : 0;
$action   = ( isset($_GET['action']) ) ? strip_tags($_GET['action']) : exit ;

$sMenuPosition = ( isset($_POST['menu_settings']) ) ? $_POST['menu_settings'] : null;

$_ni = $_page['name_index'];

$sMode = bx_get('mode');
$bAjxMod = ($sMode == 'ajax') ? true : false;
$sJQueryJS = genAjaxyPopupJS($targetID);

	switch ($action)
	{
		case 'extra_menu':
            $sPageCaption = _t( '_Member menu position' );
			$_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption, getMemberMenuSettings($sMenuPosition, $sourceID), $oTemplConfig -> PageListPop_db_num);
		break;

        case 'block':

			if ($bAjxMod) {
				echo PageListBlock($sourceID, $targetID) . $sJQueryJS; exit;
			}

            $sPageCaption = _t( '_Block list' );
			$_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption, PageListBlock($sourceID, $targetID), $oTemplConfig -> PageListPop_db_num );
		break;

		case 'unblock':

			if ($bAjxMod) {
				echo PageListUnBlock($sourceID, $targetID) . $sJQueryJS; exit;
			}

            $sPageCaption = _t( '_Block list' );
			$_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption, PageListUnBlock($sourceID, $targetID), $oTemplConfig -> PageListPop_db_num );
		break;

		case 'hot':

			if ($bAjxMod) {
				echo PageListHot($sourceID, $targetID) . $sJQueryJS; exit;
			}

			$sPageCaption = _t( '_Hot list' );
            $_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption,  PageListHot($sourceID, $targetID), $oTemplConfig -> PageListPop_db_num );
		break;

		case 'remove_friend':
			if ($bAjxMod) {
				echo PageListFriendRemove($sourceID, $targetID) . $sJQueryJS; exit;
			}

			$sPageCaption = _t( '_Friend list' );
            $_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption, PageListFriendRemove($sourceID, $targetID), $oTemplConfig -> PageListPop_db_num );
			break;
			
		case 'friend':
			if ($bAjxMod) {
				echo PageListFriend($sourceID, $targetID) . $sJQueryJS; exit;
			}

			$sPageCaption = _t( '_Friend list' );
            $_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption, PageListFriend($sourceID, $targetID), $oTemplConfig -> PageListPop_db_num );
		break;

		case 'spam':
			if ($bAjxMod) {
				echo PageListSpam($sourceID, $targetID) . $sJQueryJS; exit;
			}

			$sPageCaption = _t( '_Spam report' );
            $_page['header'] = $sPageCaption;
			$_page_cont[$_ni]['page_main_code'] = DesignBoxContent( $sPageCaption, PageListSpam($sourceID, $targetID), $oTemplConfig -> PageListPop_db_num);
		break;

		case 'change_status':
			if ($bAjxMod) {
                $sStatus = ( isset($_GET['status']) ) ? $_GET['status'] : null;
                if ($sStatus) {
                    echo ActionChangeStatus($sourceID, $sStatus); exit;
                }
			}
        break;

        case 'change_status_message':
			if ($bAjxMod && isset($_COOKIE['memberID']) ) {
				echo ActionChangeStatusMessage(); 
                exit;
			}
        break;

        default:
            $_page_cont[$_ni]['page_main_code'] = '';
        break;

    }

PageCode();

function ActionChangeStatus($iMemberID, $sStatus) 
{
    $sStatus = process_db_input ($sStatus, BX_TAGS_STRIP);
    $oUserStatus = new BxDolUserStatusView();
    if ( $oUserStatus -> getRegisteredStatus($sStatus) ) {
        $sUpdateSQL = "UPDATE `Profiles` SET `UserStatus`='{$sStatus}' WHERE `ID` = '{$iMemberID}'";
        db_res($sUpdateSQL);

        // update the date of last navigate;
        $sQuery = "UPDATE `Profiles` SET `DateLastNav` = NOW() WHERE `ID` = '{$iMemberID}'";
        db_res($sQuery);

        require_once(BX_DIRECTORY_PATH_CLASSES . 'BxDolAlerts.php');
        $oZ = new BxDolAlerts('profile', 'edit_status', $iMemberID, $iMemberID);
        $oZ->alert();

        bx_import('BxTemplMemberMenu');
        $oMemberMenu = new BxTemplMemberMenu();
        $oMemberMenu -> deleteMemberMenuKeyFile($iMemberID);

        createUserDataFile($iMemberID);

        $sStatusImg  = getTemplateIcon( $oUserStatus -> getStatusIcon($iMemberID) );
    }

	return $sStatusImg;
}

function ActionChangeStatusMessage($iMemberIdForce = 0) 
{
    if ($iMemberIdForce)
        $iMemberID = $iMemberIdForce;
    else
        $iMemberID = (isset($_COOKIE['memberID']) && isMember() ) ? (int) $_COOKIE['memberID'] : 0;
    if($iMemberID) {
    	$sNewStatusMessage = process_db_input($_REQUEST['status_message'], BX_TAGS_STRIP);

    	$sUpdateSQL = "UPDATE `Profiles` SET `UserStatusMessage`='{$sNewStatusMessage}', `UserStatusMessageWhen`=UNIX_TIMESTAMP() WHERE `ID` = '{$iMemberID}'";
        db_res($sUpdateSQL, 0);

    	require_once(BX_DIRECTORY_PATH_CLASSES . 'BxDolAlerts.php');
    	$oZ = new BxDolAlerts('profile', 'edit_status_message', $iMemberID, $iMemberID, array ($sNewStatusMessage));
    	$oZ->alert();

        createUserDataFile($iMemberID);
    }
}

/**
 * Function will set member's menu position ;
 *
 * @param  : $sValue (string) - selected position name;
 * @param $sourceID integer - profile's id
 * @return : (text) - Html presentation data ;
 */
function getMemberMenuSettings( $sRadioValue = null, $sourceID = 0)
{
    $sParameters   = null;
    $sOutputHtml   = null;
    $sDefaultValue = null;

    $aLangugeKeys = array (
        'top'       => _t( '_Top' ),
        'bottom'    => _t( '_Bottom' ),
        'static'    => _t( '_Static' ),
        'save'      => _t( '_Save Changes' ),
        'saved'     => _t( '_Saved' ),
    );
 
    // define from glParam ;
    if ( !$sRadioValue )
    {
        if  ( isset($_COOKIE['menu_position']) ) {
            $sDefaultValue = $_COOKIE['menu_position'];
        }
        else {
             $sDefaultValue = getParam( 'ext_nav_menu_top_position' );
        }
    }

    // set menu position 
    if ( $sRadioValue ) {
        $sOutputHtml = _t_action( $aLangugeKeys['saved'] );
        $sOutputHtml .= 
        '
            <script type="text/javascript">
                opener.location.reload();
                window.close();
            </script>
        ';

        setcookie("menu_position", $sRadioValue, time() + 60 * 60 * 24 * 180);

        //clear cache
        bx_import('BxDolMemberMenu');
        $oMemberMenu = new BxDolMemberMenu();
        $oMemberMenu -> deleteMemberMenuKeyFile($sourceID);
    }

    // collect all received get parameters ;
    foreach( $_GET as $sKey => $sValue )
    {
        $sParameters .= '&' . $sKey . '=' .  $sValue;
    }

    $aForm = array (
        'form_attrs' => array (
            'action' => BX_DOL_URL_ROOT . 'list_pop.php?' . $sParameters,
            'method' => 'post',
            'name' => 'menu_position_form'
        ),
        'inputs' => array(
            array(
                'type' => 'radio_set',
                'name' => 'menu_settings',
                'caption' => 'Position',
                'dv' => '<br />',
                'values' => array(
                    'top'    => $aLangugeKeys['top'],
                    'bottom' => $aLangugeKeys['bottom'],
                    'static' => $aLangugeKeys['static'],
                ),
                'value' => ( $sRadioValue ) ? $sRadioValue : $sDefaultValue
            ),
            array(
                'type' => 'submit',
                'name' => 'do_submit',
                'value' => $aLangugeKeys['save'],
                'colspan' => true,
            )
        ),
    );

    $oForm = new BxTemplFormView($aForm);
    $sOutputHtml .= $oForm->getCode();

    return $sOutputHtml;
}


function PageListUnBlock( $sourceID, $targetID )
{
    $targetID = (int) $targetID;
    $sourceID = (int) $sourceID;
	$ret = '';

	bx_import('BxDolCommunicator');
	$oCommunicator = new BxDolCommunicator('', array('member_id' => $targetID));
	if( $oCommunicator -> _deleteRequest('sys_block_list', $sourceID) ){
		$ret = MsgBox( _t('_User was removed from block list') );
	}
	else {
		$ret = _t_err('_Failed to apply changes');
	}

	return $ret;
}

function PageListBlock( $sourceID, $targetID )
{
    $targetID = (int) $targetID;
    $sourceID = (int) $sourceID;

	$ret = '';
	$query = "REPLACE INTO `sys_block_list` SET `ID` = '$sourceID', `Profile` = '$targetID';";
	if( db_res($query, 0) )
	{
        $ret = MsgBox(_t('_User was added to block list'));

        bx_import('BxDolAlerts');
        $oZ = new BxDolAlerts('block', 'add', $targetID, $sourceID);
        $oZ->alert();
		
		$sqlQuery = "DELETE FROM `sys_friend_list` WHERE (`ID`='$sourceID' AND `Profile`='$targetID') OR (`ID`='$targetID' AND `Profile`='$sourceID')";
    	db_res($sqlQuery);
	}
	else
	{
		$ret = _t_err('_Failed to apply changes');
	}

	return $ret;
}

function PageListHot($sourceID, $targetID)
{
	$targetID = (int) $targetID;
    $ret = '';

	$query = "REPLACE INTO `sys_fave_list` SET `ID` = '$sourceID', `Profile` = '$targetID';";
	if( db_res($query, 0) )
	{
        $ret = MsgBox(_t('_User was added to hot list'));

        bx_import('BxDolAlerts');
        $oZ = new BxDolAlerts('fave', 'add', $targetID, $sourceID);
        $oZ->alert();        
	}
	else
	{
		$ret = _t_err('_Failed to apply changes');
	}

	return $ret;
}

function PageListFriendRemove($sourceID, $targetID) {
    $sourceID = (int)$sourceID;
    $targetID = (int)$targetID;

     // create BxTemplCommunicator object ;
    $aCommunicatorSettings = array(
    	'member_id' => $sourceID,
    );

    bx_import('BxTemplCommunicator');
    $oCommunicator = new BxTemplCommunicator('communicator_page', $aCommunicatorSettings);
    $aParams = array($targetID);
    $oCommunicator -> execFunction( '_deleteRequest', 'sys_friend_list', $aParams, array(1, 1) );
   	$ret = MsgBox(_t('_Friend was removed') );

    return $ret;
}

function PageListFriend($sourceID, $targetID) {
    $sourceID = (int)$sourceID;
    $targetID = (int)$targetID;

    // block members
	if (isBlocked($targetID, $sourceID) ) {
        return MsgBox( _t('_You have blocked by this profile') );
	}

	$temp = db_assoc_arr("SELECT * FROM `sys_friend_list` WHERE (`ID`='$sourceID' AND `Profile`='$targetID') OR (`ID`='$targetID' AND `Profile` = '$sourceID')");

	$ret = '';
	if($temp['Check'] == 1)
        $ret = MsgBox(_t('_already_in_friend_list'));
	else if ($sourceID == $temp['ID'] && $temp['Check'] == 0)
        $ret = MsgBox(_t('_pending_friend_request'));
	else if ($targetID == $temp['ID'] && $temp['Check'] == 0) {
		$query = "UPDATE `sys_friend_list` SET `Check` = '1' WHERE `ID` = '$targetID' AND `Profile` = '$sourceID';";
		if (db_res($query)) {
			$ret = MsgBox(_t('_User was added to friend list'));

			require_once(BX_DIRECTORY_PATH_CLASSES . 'BxDolAlerts.php');
    		$oZ = new BxDolAlerts('friend', 'accept', $targetID, $sourceID);
    		$oZ->alert();
		}
		else
			$ret = _t_err('_Failed to apply changes');
	}
	else {
		$query = "INSERT INTO `sys_friend_list` SET `ID` = '$sourceID', `Profile` = '$targetID', `Check` = '0';";
		if (db_res($query)) {
			$ret = MsgBox(_t('_User was invited to friend list'));

			require_once(BX_DIRECTORY_PATH_CLASSES . 'BxDolAlerts.php');
    		$oZ = new BxDolAlerts('friend', 'request', $targetID, $sourceID);
    		$oZ->alert();
			
			// send email notification
			$oEmailTemplate = new BxDolEmailTemplates();
			$aTemplate = $oEmailTemplate -> getTemplate('t_FriendRequest') ;

			$aRecipient = getProfileInfo($targetID);

			$aPlus = array(
			    'Recipient'     => $aRecipient['NickName'],
			    'SenderLink'	=> getProfileLink($sourceID),
			    'Sender'		=> getNickName($sourceID),
			    'RequestLink'	=> BX_DOL_URL_ROOT . 'communicator.php?communicator_mode=friends_requests',
			);

            sendMail( $aRecipient['Email'], $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus );
 		}
		else
			$ret = _t_err('_Failed to apply changes');
	}
	return $ret;
}

function PageListSpam($reporterID, $aSpamers)
{
	global $site;

	// init some nedded variables ;

	$ret = _t_err('_Report about spam failed to sent');

	$oEmailTemplate = new BxDolEmailTemplates();
    $aTemplate = $oEmailTemplate -> getTemplate( 't_SpamReport' ) ;

	// reporter information ;
	$aReporter = getProfileInfo( $reporterID );
   
	$aPlus = array();
    $aPlus['reporterID'] = $reporterID;
    $aPlus['reporterNick'] = $aReporter['NickName'];
    
	// try to define as Array ;
	$aSpamers = explode(',', $aSpamers);
	if ( is_array($aSpamers) and !empty($aSpamers) )
	{
        $aSpamers = array_unique($aSpamers);
	    foreach($aSpamers AS $spamerID)
        {   $aSpamerInfo = getProfileInfo( $spamerID );

            $aPlus['spamerID'] = $spamerID;
            $aPlus['spamerNick'] = $aSpamerInfo['NickName'];

            $mail_result = sendMail( $site['email'], $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus );

        	if ( $mail_result )
        	    $ret = MsgBox(_t('_Report about spam was sent'));
        }
	}

	return $ret;
}

?>
