<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.7.0
 *	LISENSE: FL4HLD2A8696 - https://www.flynax.com/flynax-software-eula.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN : immofil.com
 *	FILE   : RLFBCONNECT.CLASS.PHP
 *
 *	This script is a commercial software and any kind of using it must be
 *	coordinate with Flynax Owners Team and be agree to Flynax License Agreement
 *
 *	This block may not be removed from this file or any other files with out
 *	permission of Flynax respective owners.
 *
 *	Copyrights Flynax Classifieds Software | 2019
 *	https://www.flynax.com
 *
 ******************************************************************************/

class rlFBConnect
{
    /**
     * Install the plugin
     *
     * @since 2.2.5
     **/
    public function install()
    {
        global $rlDb;

        if (false === $this->columnExists('facebook_ID', 'accounts')) {
            $rlDb->query("ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `facebook_ID` VARCHAR(25) NOT NULL");
        }

        $group_id = intval($rlDb->getOne('ID', "`Key` = 'facebookConnect'", 'config_groups'));
        $rlDb->query("
            INSERT INTO `" . RL_DBPREFIX . "config` (`Key`, `Default`, `Plugin`) VALUES 
            ('facebookConnect_configs_group_id', '{$group_id}', 'facebookConnect')");
    }

    /**
     * Uninstall the plugin
     *
     * @since 2.2.5
     **/
    public function uninstall()
    {
        if (true === $this->columnExists('facebook_ID', 'accounts')) {
            $GLOBALS['rlDb']->query("ALTER TABLE `" . RL_DBPREFIX . "accounts` DROP `facebook_ID`");
        }
    }

    /**
     * @since 2.2.6
     */
    private function columnExists($column, $table)
    {
        global $rlDb;

        if (method_exists($rlDb, 'columnExists')) {
            return $rlDb->columnExists($column, $table);
        }
        $column = $rlDb->getRow("SHOW COLUMNS FROM  `" . RL_DBPREFIX . "{$table}` LIKE  '{$column}'");

        return !empty($column);
    }

    /** Hooks **/

    /**
     * @hook phpBeforeLoginValidation
     *
     * @since 2.2.5
     */
    public function hookPhpBeforeLoginValidation()
    {
        if (false === $this->isConfigured(true)) {
            return;
        }
        $this->facebookConnectHandler();
    }

    /**
     * @hook specialBlock
     *
     * @since 2.2.5
     */
    public function hookSpecialBlock()
    {
        if (false === $this->isConfigured()) {
            return;
        }
        $seo_base = SEO_BASE;

        if ($GLOBALS['geo_filter_data']['geo_url']) {
            $seo_base = str_replace($GLOBALS['geo_filter_data']['geo_url'] . "/", '', $seo_base);
        }

        $urlBase = $seo_base;
        $urlBase = (stristr($_SERVER['HTTPS'], 'on') ? str_replace('http:', 'https:', $urlBase) : $urlBase);

        $_SESSION['facebook_base_url'] = $urlBase;
        $_SESSION['facebook_page_login'] = $GLOBALS['pages']['login'];
        $_SESSION['facebook_page_registration'] = $GLOBALS['pages']['registration'];
    }

    /**
     * @hook tplUserNavbar
     *
     * @since 2.2.5
     */
    public function hookTplUserNavbar()
    {
        if (false === $this->isConfigured()) {
            return;
        }

        printf('<img onclick="fcLogin();" id="fb-nav-bar" style="cursor:pointer;" src="%s" title="%s" alt="" />',
            RL_PLUGINS_URL . 'facebookConnect/static/fb_ico.png',
            $GLOBALS['lang']['fConnect_login_title']);
    }

    /**
     * @hook tplFooter
     *
     * @since 2.2.5
     */
    public function hookTplFooter()
    {
        if (false === $this->isConfigured(true)) {
            return;
        }
        
        $GLOBALS['rlSmarty']->display(RL_PLUGINS . 'facebookConnect/connect.tpl');
    }

    /**
     * @hook tplRegistrationCheckbox
     */
    public function hookTplRegistrationCheckbox()
    {
        if (isset($_SESSION['facebook_process']) && $_SESSION['facebook_process'] == 'registration') {
            $GLOBALS['rlSmarty']->assign('facebook_info', $_SESSION['facebook_info']);
            $GLOBALS['rlSmarty']->display(RL_PLUGINS . 'facebookConnect' . RL_DS . 'registration.tpl');
        }
    }

    /**
     * @hook phpRegistrationBeforeInsert
     */
    public function hookPhpRegistrationBeforeInsert(&$new_account)
    {
        global $account_types;

        if ($this->isRegistrationProcess()) {
            $new_account['facebook_ID'] = intval($_SESSION['facebook_info']['id']);

            // turn of system options only if Facebook account is verified!
            if ($this->isFBAccountVerified()) {
                $new_account['Password_tmp'] = '';
                $new_account['Status'] = 'active';
                unset($new_account['Confirm_code']);

                $type_id = intval($_POST['profile']['type']);
                $account_types[$type_id]['Email_confirmation'] = 0;
                $account_types[$type_id]['Admin_confirmation'] = 0;
            }
        }
    }

    /**
     * @hook registerSuccess
     */
    public function hookRegisterSuccess()
    {
        global $account_types;

        if (false === $this->isRegistrationProcessAndFBAccountVerified()) {
            return;
        }
        $type_id = intval($GLOBALS['profile_data']['type']);

        $account_types[$type_id]['Email_confirmation'] = 0;
        $account_types[$type_id]['Admin_confirmation'] = 0;
        $account_types[$type_id]['Auto_login'] = 1;
    }

    /**
     * @hook registrationDone
     */
    public function hookRegistrationDone()
    {
        global $account_types;

        if (false === $this->isRegistrationProcessAndFBAccountVerified()) {
            return;
        }
        $type_id = intval($_SESSION['registr_account_type']);
        $account_id = intval($_SESSION['registration']['account_id']);

        $account_types[$type_id]['Auto_login'] = 1;
        $account_types[$type_id]['Email_confirmation'] = 0;
        $account_types[$type_id]['Admin_confirmation'] = 0;

        if ($account_id && $_SESSION['account']['Status'] != 'active') {
            $sql = "UPDATE `" . RL_DBPREFIX . "accounts` SET `Status` = 'active' ";
            $sql.= "WHERE `ID` = " . $account_id;
            $GLOBALS['rlDb']->query($sql);
        }
        unset($_SESSION['facebook_process']);
    }

    /**
     * @hook phpSendRegistrationNotification
     * 
     * @since 2.2.5 (Flynax 4.5.1 required)
     * 
     * @param array $type - account type details
     * @param array $data - account details from registation form
     */
    public function hookPhpSendRegistrationNotification(&$type, &$data)
    {
        if (false === $this->isRegistrationProcessAndFBAccountVerified()) {
            return;
        }

        $type['Email_confirmation'] = 0;
        $type['Admin_confirmation'] = 0;
    }

    /**
     * @hook apPhpConfigBottom
     * @since v2.2.3
     */
    public function hookApPhpConfigBottom()
    {
        global $lang, $configs;

        $where = "`Key` = 'facebookConnect' AND `Plugin` = 'facebookConnect'";
        $group_id = intval($GLOBALS['rlDb']->getOne('ID', $where, 'config_groups'));

        if (!empty($configs[$group_id])) {
            foreach ($configs[$group_id] as $key => $entry) {
                if ($entry['Key'] == 'facebookConnect_account_type') {
                    // get accout types
                    $sql = "SELECT `Key` FROM `" . RL_DBPREFIX . "account_types` ";
                    $sql .= "WHERE `Status` = 'active' AND `Key` <> 'visitor' ORDER BY `Position`";
                    $tmpTypes = $GLOBALS['rlDb']->getAll($sql);

                    $configs[$group_id][$key]['Values'] = array();

                    foreach ($tmpTypes as $tKey => $tEntry) {
                        $configs[$group_id][$key]['Values'][] = array(
                            'ID' => $tEntry['Key'],
                            'name' => $lang["account_types+name+" . $tEntry['Key']],
                        );
                    }
                    unset($tmpTypes);
                }
            }
        }
    }

    /**
     * @hook reeflessRedirctVars
     * @since 2.2.6
     */
    public function hookReeflessRedirctVars()
    {
        global $lang;

        if (defined('REALM')
            && $GLOBALS['controller'] == 'settings'
            && $_POST['group_id'] == $GLOBALS['config']['facebookConnect_configs_group_id']
        ) {
            $_config = $_POST['post_config'];

            if ($_config['facebookConnect_module']['value'] == 1
                && ($_config['facebookConnect_appid']['value'] == ''
                    || $_config['facebookConnect_secret']['value'] == ''
                    || $_config['facebookConnect_account_type']['value'] == '')
            ) {
                $GLOBALS['rlConfig']->setConfig('facebookConnect_module', 0);

                $msg = sprintf(
                    $lang['fConnect_save_settings_error_notice'],
                    $lang['config+name+facebookConnect_appid'],
                    $lang['config+name+facebookConnect_secret'],
                    $lang['config+name+facebookConnect_account_type']
                );
                $GLOBALS['rlNotice']->saveNotice($msg, 'errors');
            }
        }
    }

    /**
     * @hook apTplFooter
     * @since 2.2.6
     */
    public function hookApTplFooter()
    {
        if ($GLOBALS['controller'] != 'settings') {
            return;
        }

        $instruction = <<<HTML
<div class="settings_desc" style="line-height:20px;padding:0px 0 15px 3px;">
To give your users the ability to log into your site with their Facebook accounts you have to set up an Application first:<br />
1. Sign into your <a target="_blank" href="http://developers.facebook.com/apps">http://developers.facebook.com/apps</a> account and select "<b>Add a New App</b>" from the "Apps" menu at the top;<br />
2. Fill out the pop-up form, and click "<b>Create App</b>";<br />
3. Сlick the "<b>Get Started</b>" button next to "Facebook Login";<br />
4. Set your site URL to "<b>Valid OAuth redirect URIs</b>" from "Client OAuth Settings";<br />
5. Go to the "Settings" and click "<b>Add Platform</b>", then "<b>Website</b>", and enter your "Site URL";<br />
6. Save a copy or write down the <b>App ID</b> and <b>App Secret</b> (you\'ll need them in the next step) and save changes.<br />
7. Go to "<b>App Review</b>" and make the App public.<br />
8. Enter your App ID and App Secret below, which you got above.
</div>
HTML;

        printf(
            "<script>\$('#facebookConnect_module_0').closest('table.form').before('%s');</script>",
            preg_replace('/(\n|\t|\r)?/', '', $instruction));
    }

    /** Common **/

    /**
     * @since 2.2.6
     */
    private function isConfigured($skipConstant = false)
    {
        global $config;

        if (($skipConstant || !defined('IS_LOGIN'))
            && $config['facebookConnect_module'] == 1
            && $config['facebookConnect_appid'] != ''
            && $config['facebookConnect_secret'] != ''
            && $config['facebookConnect_account_type'] != ''
        ) {
            return true;
        }
        return false;
    }

    /**
     * @since 2.2.6
     */
    private function isRegistrationProcessAndFBAccountVerified()
    {
        if (false === $this->isRegistrationProcess()) {
            return false;
        }
        return $this->isFBAccountVerified();
    }

    /**
     * @since 2.2.6
     */
    private function isRegistrationProcess()
    {
        if (isset($_SESSION['facebook_process']) && $_SESSION['facebook_process'] == 'registration') {
            if (0 !== intval($_SESSION['facebook_info']['id'])) {
                return true;
            }
        }
        return false;
    }

    /**
     * @since 2.2.6
     */
    private function isFBAccountVerified()
    {
        return (bool) $_SESSION['facebook_info']['verified'];
    }

    /**
     * Handler for login,registraion pages
     */
    public function facebookConnectHandler()
    {
        global $config, $reefless;

        // check facebook id
        if (0 !== $facebook_id = intval($_SESSION['facebook_info']['id'])) {
            // login
            if ($_SESSION['facebook_process'] == 'login') {
                $fields = array('Username', 'Mail', 'Password');
                $where = "AND `Status` <> 'trash'";
                $user_info = $GLOBALS['rlDb']->fetch($fields, array('facebook_ID' => $facebook_id), $where, 1, 'accounts', 'row');

                // deep checking
                if (!empty($user_info)) {
                    $reefless->loadClass('Account');

                    // turn off login attempts control
                    $config['security_login_attempt_user_module'] = 0;

                    // detect login method option
                    $login_field = $config['account_login_mode'] == 'email' ? 'Mail' : 'Username';
                    $result = $GLOBALS['rlAccount']->login($user_info[$login_field], $user_info['Password'], true);

                    if ($result) {
                        $reefless->loadClass('Notice');
                        $GLOBALS['rlNotice']->saveNotice($GLOBALS['lang']['notice_logged_in']);

                        $GLOBALS['rlHook']->load('loginSuccess', $user_info);

                        // redirect to back
                        $facebook_referer = $_SESSION['facebook_referer'];
                        unset($_SESSION['facebook_referer'], $_SESSION['facebook_process']);
                        $reefless->redirect(false, $facebook_referer);
                    } else {
                        unset(
                            $_SESSION['facebook_referer'],
                            $_SESSION['facebook_process'],
                            $_SESSION['facebook_info']);

                        $GLOBALS['rlSmarty']->assign('errors', $result);
                    }
                }
            }
            // registration
            else if ($_SESSION['facebook_process'] == 'registration') {
                $config['security_img_registration'] = false;

                // replace fake password to generated
                if (!empty($_POST['profile']) && !array_key_exists('xjxfun', $_POST)) {
                    $_passord = $reefless->generateHash(10, 'password', true);
                    $_POST['profile']['password'] = $_POST['profile']['password_repeat'] = $_passord;
                }
            }
        }
    }

    /**
     * @deprecated since 2.0.0
     */
    public function createFBConnectButton()
    {}
}
