<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLSMSACTIVATION.CLASS.PHP
 *
 *	The software is a commercial product delivered under single, non-exclusive,
 *	non-transferable license for one domain or IP address. Therefore distribution,
 *	sale or transfer of the file in whole or in part without permission of Flynax
 *	respective owners is considered to be illegal and breach of Flynax License End
 *	User Agreement.
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2017 |  All copyrights reserved.
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlSmsActivation extends reefless
{
	/**
	* @var bool access - is plugin access allowed
	**/
	public $access = false;
	
	/**
	* class constructor
	**/
	public function __construct()
	{
		global $config, $account_info, $rlSmarty, $page_info, $lang, $errors, $pages;
		
		if (defined('IS_LOGIN') && self::isConfigured()) {
 			if (!$account_info['smsActivation']) {
 				$this->access = true;
 				
 				$allowed = array('my_profile', 'my_messages');
 				
 				/* restrict access in account area */
 				$account_menu = $rlSmarty -> get_template_vars('account_menu');
 				foreach ($account_menu as $key => $account_menu_item) {
 					$account_meny_keys[] = $account_menu_item['Key'];
 					if (!in_array($account_menu_item['Key'], $allowed)) {
 						unset($account_menu[$key]);
 					}
 				}
 				$rlSmarty->assign_by_ref('account_menu', $account_menu);
 				
 				if (!in_array($page_info['Key'], $allowed) && in_array($page_info['Key'], $account_meny_keys)) {
					$page_info['Controller'] = '404';
					$activate_href = SEO_BASE;
					$activate_href .= $config['mod_rewrite'] ? "{$pages['my_profile']}.html" : "?page={$pages['my_profile']}";
					$errors[] = preg_replace('/\[(.*)\]/', '<a href="'. $activate_href .'">$1</a>', $lang['smsActivation_access_deny']);
				}
 			}
 		}
	}
	
	/**
	* modify profile tabs
	*
	* @access hook - profileController
	*
	**/
	function profileTab()
	{
		global $tabs, $lang, $rlSmarty, $account_info, $config, $rlXajax;
		
		if ($this->access) {
			unset($tabs['password']);
			
			$tabs['account']['active'] = false;
			$tabs['profile']['active'] = false;
			
			$tabs_back = $tabs;
			$tabs = array();
			$tabs['smsActivation'] = array(
				'key' => 'smsActivation',
				'name' => $lang['smsActivation_tab_caption'],
				'active' => true
			);
			$tabs = array_merge($tabs, $tabs_back);
			
			$phone_fields = explode(',', $config['sms_activation_phone_field']);
			
			/* checking, was phone field filled in or not */
			foreach ($phone_fields as $phone_field) {
				if (!empty($account_info[$phone_field])) {
					$sms_phone_number = $account_info[$phone_field];
					$sms_phone_field = $phone_field;
					break;
				}
			}
			
			$rlSmarty->assign('success_code', str_replace(array('{number}', '{phone}'), array($config['sms_activation_code_length'], $sms_phone_number), $lang['smsActivation_profile_text']));
			
			$rlXajax->registerFunction(array('smsActivationCheckp', $GLOBALS['rlSmsActivation'], 'ajax_checkp'));
			$rlXajax->registerFunction(array('smsActivationSendCode', $GLOBALS['rlSmsActivation'], 'ajax_sendCode'));
		}
	}
	
	/**
	* check code
	*
	* @package XAJAX
	*
	* @param int $code - sms code
	*
	**/
	public function ajax_check( $code = false )
	{
		global $_response, $config, $pages, $lang, $account_info;

		$sms_username = $GLOBALS['rlValid'] -> xSql($_SESSION['smsActication_username']);

		if (empty($sms_username)) {
			$mess = $lang['smsActivation_sesseion_expired'];
			$_response -> script("printMessage('error', '{$mess}')");

			$tpl = RL_PLUGINS .'smsActivation' . RL_DS . 'sesExpired.tpl';
			$_response -> script( "$('#smsActivation_container').next().remove()" );
			$_response -> assign( 'smsActivation_container', 'innerHTML', $GLOBALS['rlSmarty'] -> fetch( $tpl, null, null, false ) );
		} else {
			$code = (int)$code;
			$res = $this -> getOne('ID', "`Username` = '{$sms_username}' AND `smsActivation_code` = {$code}", 'accounts');

			if ($res) {
				$this -> query("UPDATE `". RL_DBPREFIX ."accounts` SET `smsActivation` = '1', `smsActivation_code` = 'done' WHERE `ID` = '{$res}' LIMIT 1");
				$account_info['smsActivation'] = 1;
				$_SESSION['account']['smsActivation'] = 1;

				$_response -> script("printMessage('notice', '{$lang['smsActivation_activated']}')");

				$tpl = RL_PLUGINS .'smsActivation' . RL_DS . 'completed.tpl';
				$_response -> script("$('#smsActivation_container').next().remove()");
				$_response -> assign('smsActivation_container', 'innerHTML', $GLOBALS['rlSmarty'] -> fetch( $tpl, null, null, false ));

				unset($_SESSION['smsActication_username']);
			} else {
				$mess = $lang['smsActivation_code_is_wrong'];
				$_response -> script("
					printMessage('error', '{$mess}');
					$('input[name=sms_submit]').val('{$lang['smsActivation_confirm']}');
				");
			}
		}

		return $_response;
	}

	/**
	* check code on profile page
	*
	* @package XAJAX
	*
	* @param int $code - sms code
	*
	**/
	function ajax_checkp( $code = false )
	{
		global $_response, $config, $pages, $lang, $account_info;

		$code = (int)$code;
		$res = $this -> getOne('ID', "`ID` = '{$account_info['ID']}' AND `smsActivation_code` = {$code}", 'accounts');

		if ($res) {
			$this->query("UPDATE `". RL_DBPREFIX ."accounts` SET `smsActivation` = '1', `smsActivation_code` = 'done' WHERE `ID` = '{$res}' LIMIT 1");
			$account_info['smsActivation'] = 1;
			$_SESSION['account']['smsActivation'] = 1;

			$this->loadClass('Notice');
			$GLOBALS['rlNotice']->saveNotice($lang['smsActivation_activated_aa']);

			$link = SEO_BASE;
			$link .= $config['mod_rewrite'] ? "{$pages['my_profile']}.html" : "?page={$pages['my_profile']}";

			$_response->redirect($link);
		} else {
			$_response->script("
				printMessage('error', '{$lang['smsActivation_code_is_wrong']}');
				$('input[name=sms_submit]').val('{$lang['smsActivation_confirm']}');
			");
		}

		$_response->script("$('#sms_loading').fadeOut()");

		return $_response;
	}

	/**
	* send new code
	*
	* @package XAJAX
	*
	* @param int $code - sms code
	*
	**/
	public function ajax_sendCode( $code = false )
	{
		global $_response, $config, $pages, $lang, $rlAccount, $account_info;

		/* plugin phone fields */
		$phone_fields = explode(',', $config['sms_activation_phone_field']);
		if (empty($phone_fields[0])) {
			$_response -> script("printMessage('error', '{$lang['smsActivation_phone_fields_doesnot_exist']}')");
			$error = true;
		}

		/* checking, was phone field filled in or not */
		foreach ($phone_fields as $phone_field) {
			if (!empty($account_info[$phone_field])) {
				$sms_phone_number = $account_info[$phone_field];
				$sms_phone_field = $phone_field;
				break;
			}
		}

		if (!$sms_phone_number) {
			$_response -> script("printMessage('error', '{$lang['smsActivation_no_phone_error']}')");
			$error = true;
		}

		/* validate phone number*/
		if (false !== strpos($sms_phone_number, 'c:')) {
			$field = $this -> fetch(array('Opt1'), array('Key' => $sms_phone_field), null, 1, 'account_fields', 'row');
			$sms_phone_number = $this -> parsePhone($sms_phone_number, $field);
		}

		if (!$error) {
			$sms_code = rand(str_repeat(1, $config['sms_activation_code_length']), str_repeat(9, $config['sms_activation_code_length']));
            $response = $this->send($sms_code, $sms_phone_number, $lang['smsActivation_message_text']);

			if (false === strpos($response, 'ID:')) {
				$mess = str_replace('{error}', $response, $lang['smsActivation_sending_fail']);
				$_response -> script("
					printMessage('error', '{$mess}');
					$('input[name=new_code]').val('{$lang['smsActivation_get_code']}');
				");
			} else {
				$this->query("UPDATE `". RL_DBPREFIX ."accounts` SET `smsActivation` = '0', `smsActivation_code` = '{$sms_code}' WHERE `ID` = '{$account_info['ID']}' LIMIT 1");
				$mess = str_replace('{number}', $sms_phone_number, $lang['smsActivation_regenerated']);
				$_response->script("printMessage('notice', '{$mess}')");
			}
		}
		
		return $_response;
	}
    

    /**
    * @hook registerSuccess
    * 
    * @since 2.1.0
    */
    public function hookRegisterSuccess()
    {
        if (version_compare($GLOBALS['config']['rl_version'], '4.5.0') >= 0) {
            return;
        }
        global $reefless, $config, $pages, $profile_data;

        if ($config['sms_activation_module'] && $config['sms_activation_username'] && $config['sms_activation_api_id'] && $config['sms_activation_password']) {
            $_SESSION['smsActication_username'] = $profile_data['username'];
            $redirect = SEO_BASE;
            $redirect .= $config['mod_rewrite'] ? "{$pages['sms_activation']}.html" : "?page={$pages['sms_activation']}";
            $reefless->redirect(null, $redirect);
            exit;
        }    
    }
    

    /**
    * @hook beforeRegister
    * 
    * @since 2.1.0
    */
    public function hookBeforeRegister()
    {
        if (version_compare($GLOBALS['config']['rl_version'], '4.5.0') >= 0) {
            return;
        }
        global $account_types, $config;
        
        if ($config['sms_activation_module']) {
            foreach ($account_types as &$account_type) {
                $account_type['Email_confirmation'] = 0;
                $account_type['Admin_confirmation'] = 0;
            }
         
            /* hack for <= 4.0.1 version */
            $config['account_email_confirmation'] = 0;
            $config['account_admin_confirmation'] = 0;
        }   
    }

    /**
    * @hook specialBlock
    * 
    * @since 2.1.0
    */
    public function hookSpecialBlock()
    {
        if (version_compare($GLOBALS['config']['rl_version'], '4.5.0') >= 0) {
            return;
        }
        $GLOBALS['reefless']->loadClass('SmsActivation', null, 'smsActivation');
    }

    /**
    * @hook profileController
    * 
    * @since 2.1.0
    */
    public function hookProfileController()
    {
        $this->profileTab();
    }

    /**
    * @hook profileBlock
    * 
    * @since 2.1.0
    */
    public function hookProfileBlock()
    {
        if ($this->access) {
            $GLOBALS['rlSmarty']->display(RL_ROOT . 'plugins' . RL_DS . 'smsActivation' . RL_DS . 'tab.tpl');
        }
    }

    /**
    * @hook pageinfoArea
    * 
    * @since 2.1.0
    */
    public function hookPageinfoArea()
    {
        global $reg_steps, $lang, $page_info, $config;
        
        if ($page_info['Key'] == 'registration' && self::isConfigured()) {
            if ($config['membership_module']) {
                foreach ($reg_steps as $key => $step) {
                    $steps[$key] = $step;
                    if ($key == 'plan') {
                        $steps['smsActivation'] = array(
                            'name' => $lang['smsActivation_tab_caption'],
                            'caption' => true,
                            'path' => 'sms-activation'
                        );
                    }
                }
            } else {
                foreach ($reg_steps as $key => $step) {
                    if ($key == 'done') {
                        $steps['smsActivation'] = array(
                            'name' => $lang['smsActivation_step'],
                            'caption' => true,
                            'path' => 'sms-activation'
                        );
                    }
                    $steps[$key] = $step;
                }    
            }
            $reg_steps = $steps;
        }
    }
    
    /**
    * check settings of the plugin
    * 
    * @return bool
    */
    public static function isConfigured()
    {
        if ($GLOBALS['config']['sms_activation_module'] && 
            $GLOBALS['config']['sms_activation_phone_field'] && 
            $GLOBALS['config']['sms_activation_username'] && 
            $GLOBALS['config']['sms_activation_password'] &&
            $GLOBALS['config']['sms_activation_api_id']) {
                return true;
            }   

        return false;
    }
    
    /**
    * @hook phpRegistrationBottom
    * 
    * @since 2.1.0
    */
    public function hookPhpRegistrationBottom()
    {
        if (version_compare($GLOBALS['config']['rl_version'], '4.5.0') < 0) {
            return;
        }
        global $errors, $cur_step, $next_step, $page_info, $config, $lang;
        
        if ($cur_step == 'smsActivation') {
            $account_id = (int)$_SESSION['registration']['account_id'];
            $sms_account_info = $GLOBALS['rlAccount']->getProfile($account_id);
            $_SESSION['smsActication_username'] = $sms_account_info['Username'];
            
            if ($sms_account_info['smsActivation_code'] == 'done') {
                // do redirect to login page
                $url = SEO_BASE;
                $url .= $config['mod_rewrite'] ? $page_info['Path'] . '/' . $next_step['path'] . '.html' : '?page=' . $page_info['Path'] . '&step=' . $next_step['path'];
                $this->redirect(null, $url);
            }
            
            $code_exist = $sms_account_info['smsActivation_code'];
            $sms_code = $code_exist ? $code_exist : rand(str_repeat(1, $config['sms_activation_code_length']), str_repeat(9, $config['sms_activation_code_length']));

            $phone_fields = explode(',', $config['sms_activation_phone_field']);
            
            // set '0' as smsActivation for current user
            $this->query("UPDATE `". RL_DBPREFIX ."accounts` SET `smsActivation` = '0', `smsActivation_code` = '{$sms_code}' WHERE `ID` = '{$account_id}' LIMIT 1");
            
            // check system phone fields
            if (empty($phone_fields[0])) {
                $errors[] = $lang['smsActivation_phone_fields_doesnot_exist'];
                $notice = preg_replace('/\[(.*)\]/', '<a href="'. $this->getPageUrl('contact_us') . '">$1</a>', $lang['smsActivation_account_approved']);

                $GLOBALS['rlDebug']->logger("smsActivation plugin | Phone fields does not exist.");
            }
            
            // checking, was phone field filled in or not
            foreach ($phone_fields as $phone_field) {
                if (!empty($sms_account_info[$phone_field])) {
                    $sms_phone_number = $sms_account_info[$phone_field];
                    $sms_phone_field = $phone_field;
                    break;
                }
            }

            if (!$sms_phone_number) {
                $errors[] = $lang['smsActivation_no_phone_error'];
                $notice = preg_replace('/(\[(.*)\])/', '<b>$1</b>', $lang['smsActivation_phone_value_doesnot_exist']);
            }
            
            // validate phone number
            if (false !== strpos($sms_phone_number, 'c:')) {
                $sms_phone_number = $this->parsePhone($sms_phone_number, $this->fetch(array('Opt1'), array('Key' => $sms_phone_field), null, 1, 'account_fields', 'row'));
            }

            $GLOBALS['rlSmarty']->assign('success_code', str_replace(array('{number}', '{phone}'), array($config['sms_activation_code_length'], $sms_phone_number), $lang['smsActication_meesage_sent_text']));
            $GLOBALS['rlSmarty']->assign_by_ref('notice', $notice);
            
            if (!$errors) {
                if (empty($sms_account_info['smsActivation_code'])) {
                    $response = $this->send($sms_code, $sms_phone_number, $lang['smsActivation_message_text']);
                    if (!is_numeric(strpos($response, 'ID:'))) {                        
                        $errors[] = str_replace('{error}', $response, $lang['smsActivation_sending_fail']);
                        $notice = preg_replace('/\[(.*)\]/', '<a href="'. $this->getPageUrl('contact_us') .'">$1</a>', $lang['smsActivation_sending_fail_notice']);
                    } else {
                        $this->loadClass('Notice');
                        $GLOBALS['rlNotice']->saveNotice($lang['smsActication_meesage_sent']);
                    }
                }
            }
        }
    }
    
    /**
    * @hook ajaxRequest
    * 
    * @since 2.1.0
    */
    public function hookAjaxRequest(&$out, &$request_mode, &$request_item, &$request_lang)
    {
        if ($request_mode == 'smsActivationCheck') {
            $code =  $GLOBALS['rlValid']->xSql($request_item);
            $sms_username = $GLOBALS['rlValid']->xSql($_SESSION['smsActication_username']);

            if (!$sms_username) {
                $out = array(
                    'status' => 'failure',
                    'message_text' => $lang['smsActivation_sesseion_expired']
                );    
            } else {
                $account_info = $this->fetch('*', array('ID' => (int)$_SESSION['registration']['account_id'], 'smsActivation_code' => $code), null, 1, 'accounts', 'row');

                if ($account_info) {
                    $account_id = (int)$_SESSION['registration']['account_id'];
                    $this->loadClass('Actions');
                    $update = array(
                        'fields' => array(
                            'smsActivation' => '1',
                            'smsActivation_code' => 'done' 
                        ),
                        'where' => array('ID' => $account_id)
                    );
                    if (!$GLOBALS['config']['membership']) {
                        $this->loadClass('AccountTypes');
                        $account_type = $GLOBALS['rlAccountTypes']->types[$account_info['Type']];
                        $update['fields']['Status'] = ($account_type['Admin_confirmation'] || $account_type['Email_confirmation']) && !defined('REALM') ? 'pending' : 'active';
                    }
                    $GLOBALS['rlActions']->updateOne($update, 'accounts');
                    if (defined('IS_LOGIN')) {
                        $account_info['smsActivation'] = 1;
                        $_SESSION['account']['smsActivation'] = 1;   
                    } else {
                        $_SESSION['registration']['smsActivation'] = 1;
                    }
                    
                    $out = array(
                        'status' => 'ok',
                        'message_text' => $lang['smsActivation_activated']
                    );
                } else {
                    $out = array(
                        'status' => 'failure',
                        'message_text' => $lang['smsActivation_code_is_wrong']
                    );
                }
            }
        }
    }
    
    /**
    * @hook ajaxRequest
    * 
    * @since 2.1.0
    */
    public function hookRegistrationStepActionsTpl()
    {
        global $cur_step;

        if ($cur_step == 'smsActivation') {
            $GLOBALS['rlSmarty']->display(RL_ROOT . 'plugins' . RL_DS . 'smsActivation' . RL_DS . 'step.tpl');
        }
    }
    
    public function hookRegistrationBegin()
    {
        global $cur_step, $reg_steps;
        
        $is_add = false;
        $steps = array();
        foreach ($reg_steps as $key => $step) {
            if ($key == 'smsActivation') {
                $is_add = true;
                continue;
            }
            if ($is_add) {
                $steps[] = $key;
            }
        }

        if (in_array($cur_step, $steps)) {
            $sms_account_info = $GLOBALS['rlAccount']->getProfile((int)$_SESSION['registration']['account_id']);
            
            if ($sms_account_info['smsActivation_code'] != 'done') {
                $this->redirect(false, $this->getPageUrl('registration', 'sms-activation'));
                exit;
            }    
        }
        
    }
    
    /**
    * send request to sms server
    * 
    * @param string $sms_code
    * @param mixed $phone
    * @param string $message
    * 
    * @return mixed
    */
    public function send($sms_code = '', $phone = '', $message = '')
    {
        if (!$phone || !$message) {
            return false;
        }
        $phone = str_replace(array('+', '-', '(', ')', ' '), '', $phone);
        
        $sms_text = urlencode(str_replace('{code}', $sms_code, $message));
        $clickatell_url = 'http://api.clickatell.com/http/sendmsg';
        $request = 'user='. $GLOBALS['config']['sms_activation_username'] .'&password='. $GLOBALS['config']['sms_activation_password'] .'&api_id='. $GLOBALS['config']['sms_activation_api_id'];
        $request .= '&to='. $phone .'&text='. $sms_text;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $clickatell_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);    

        return $response;
    }
}