<?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   : RLSSLPROTECTION.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 rlSslProtection extends reefless {

    /**
     * Install the plugin
     * 
     * @since 1.2.0
     **/
    public function install() {
        $sql = "ALTER TABLE `".RL_DBPREFIX."pages` ADD `Https` ENUM('1', '0') DEFAULT '0' NOT NULL";
        $this->query($sql);
    }    

    /**
     * UnInstall the plugin
     * 
     * @since 1.2.0
     **/
    public function unInstall() {
        $sql = "ALTER TABLE `".RL_DBPREFIX."pages` DROP `Https`";
        $this->query($sql);
    }

    /**
     * defines is https enabled 
     * 
     * @since 1.3.0
     **/
    private function isServerHttps(){
        return $_SERVER['HTTPS'] 
            || $_SERVER['HTTP_CF_VISITOR'] == '{"scheme":"https"}'
            || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
    }

    /**
     * is https enabled
     * 
     * @since 1.3.0
     **/
    private function serverHttpsOn() {
        return $this->isServerHttps();
    }
    
    /**
     * is https disabled
     * 
     * @since 1.3.0
     **/
    private function serverHttpsOff() {
        return !$this->isServerHttps();
    }

    /**
     * hook seo base
     * 
     * @since 1.3.3
     **/
    public function hookSeoBase() {
        if ($GLOBALS['config']['secure_front']) {
            $GLOBALS['bPath'] = str_replace('http://', 'https://', $GLOBALS['bPath']);
            $GLOBALS['seo_base'] = str_replace('http://', 'https://', $GLOBALS['seo_base']);
        }
    }

    /**
     * @hook pageinfoArea
     * 
     * @since 1.2.0
     **/
    public function hookPageinfoArea() {
        global $secure_pages, $config;

        /* enable https only for selected pages */
        if (!$config['secure_front']) {
            $where = array("Status" => 'active');

            if (!$config['secure_front']) {
                $where = array("Https" => '1');

                if ($config['secure_account_area']) {
                    $add_where = "OR FIND_IN_SET('2', `Menus`) ";
                }
            }

            $tmp_secure_pages = $this->fetch("*", $where, $add_where, null, 'pages');

            foreach ($tmp_secure_pages as $pKey => $spage) {
                $secure_pages[ $spage['Key'] ] = $spage;
            }
        }
        /* enable https only for selected pages end */

        if (($config['secure_front'] || in_array($GLOBALS['page_info']['Key'], array_keys($secure_pages))) && $this->serverHttpsOff()) {
            //redirect to secured version of a page if the page should be secured but accessed with http
            $redirect = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            header("Location: $redirect", true, 301);

        } elseif (
            !$config['secure_front'] 
            && !in_array($GLOBALS['page_info']['Key'], array_keys($secure_pages)) 
            && $this->serverHttpsOn()
            && false === strpos(RL_URL_HOME, 'https://')
        ) {
            //redirect to non-secured version if a page configured to be http but accessed via https
            $redirect = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            header("Location: $redirect", true, 301);
            
        }
    }


    /**
     * replace content
     * 
     * @param content - html source
     **/

    public function replaceContent(&$content) {
        global $config;

        if ($config['secure_front'] && !defined('REALM')) {
            $base = RL_URL_HOME;
            $sfind[] = $base;
            $sreplace[] = str_replace('http://', 'https://', $base);
        } elseif (defined('REALM') && REALM =='admin' && $config['secure_admin_panel']) {
            $sfind[] = RL_URL_HOME . ADMIN;
            $sreplace[] = str_replace('http://', 'https://', RL_URL_HOME . ADMIN);
        } else {
            if (defined('SEO_BASE') && false == strpos(SEO_BASE, 'https://')) {
                $url_base = str_replace('https://', 'http://', SEO_BASE);
            } else {
                $url_base = RL_URL_HOME;
            }

            foreach ($GLOBALS['secure_pages'] as $spk => $spage) {
                if ($spk == 'listings_by_field') {
                    $fbbs = $this->fetch(array("Path"), "`Status` = 'active'", null, null, "field_bound_boxes");
                    foreach ($fbbs as $fbk => $fbv) {
                        $sfind[] = $url_base.$fbv['Path']."/";
                        $sreplace[] = str_replace('http://', 'https://', $url_base).$fbv['Path']."/";
                    }
                } elseif (substr($spk,0,3) == 'at_') {
                    $dealers_page_secured = true;
                }

                if ($spage['Path']) {
                    $sfind[] = $url_base.$spage['Path'].".html";
                    $sreplace[] = str_replace('http://', 'https://', $url_base).$spage['Path'].".html";

                    $sfind[] = $url_base.$spage['Path']."/";
                    $sreplace[] = str_replace('http://', 'https://', $url_base).$spage['Path']."/";
                } else {
                    $sfind[] = $url_base.'"';
                    $sreplace[] = str_replace('http://', 'https://', $url_base).'"';

                    $sfind[] = $url_base."'";
                    $sreplace[] = str_replace('http://', 'https://', $url_base)."'";
                }
            
                if ($spage['Controller'] == 'listing_type' && $GLOBALS['ltypes_to_transform_links']) {
                    foreach ($GLOBALS['ltypes_to_transform_links'] as $ltk => $ltv) {
                        if ($ltv['Links_type'] == 'subdomain') {
                            
                            $ltsub = preg_replace('#http://(www.)?#', 'http://'.$ltv['Path'].'.', $url_base);

                            $sfind[] = $ltsub;
                            $sreplace[] = str_replace('http://', 'https://', $ltsub);

                        } elseif ($ltv['Links_type'] == 'short') {
                            $top_cats = $this -> fetch(array("Path"), array("Parent_ID" => 0, "Type" => $ltv['Key']), null, null, "categories");

                            foreach ($top_cats as $topcat) {
                                $sfind[] = $url_base.$topcat['Path']."/";
                                $sreplace[] = str_replace('http://', 'https://', $url_base.$topcat['Path']."/"); 
                            }

                            $search_res_url = $url_base.$spage['Path']."&#47;".$GLOBALS['search_results_url'];
                            $sfind[] = $search_res_url;
                            $sreplace[] = str_replace('http://', 'https://', $search_res_url);

                            $search_res_url = $url_base.$spage['Path']."&#47;".$GLOBALS['advanced_search_url'];                        
                            $sfind[] = $search_res_url;
                            $sreplace[] = str_replace('http://', 'https://', $search_res_url);
                        }
                    }
                }

                if ($GLOBALS['geo_filter_data']['bPath']) {
                    $sfind[] = $GLOBALS['geo_filter_data']['bPath'].$spage['Path'].".html";
                    $sreplace[] = str_replace('http://', 'https://', $GLOBALS['geo_filter_data']['bPath']).$spage['Path'].".html";

                    $sfind[] = $GLOBALS['geo_filter_data']['bPath'].$spage['Path']."/";
                    $sreplace[] = str_replace('http://', 'https://', $GLOBALS['geo_filter_data']['bPath']).$spage['Path']."/";
                }
            }
        }

        if (($config['secure_front'] && !defined('REALM')) || in_array($GLOBALS['page_info']['Key'], array_keys($GLOBALS['secure_pages'])) 
            || (REALM =='admin' && $config['secure_admin_panel'])) {

            foreach ($GLOBALS['languages'] as $lk => $lang_item) {
                if ($config['lang'] != $lang_item['Code']) {
                    $sfind[] = RL_URL_HOME.$lang_item['Code']."/";
                    $sreplace[] = str_replace('http://', 'https://', RL_URL_HOME.$lang_item['Code']."/");
                }
            }
            
            $sfind[] = RL_LIBS_URL;
            $sreplace[] = str_replace('http://', 'https://', RL_LIBS_URL);

            $sfind[] = RL_PLUGINS_URL;
            $sreplace[] = str_replace('http://', 'https://', RL_PLUGINS_URL);

            $tpl_base = defined('RL_TPL_BASE') ? RL_TPL_BASE : RL_URL_HOME . "templates/" . $config['template'] . "/";

            $sfind[] = $tpl_base;
            $sreplace[] = str_replace('http://', 'https://', $tpl_base);
            
            $sfind[] = RL_FILES_URL;
            $sreplace[] = str_replace('http://', 'https://', RL_FILES_URL);

            $sfind[] = 'http://img.youtube.com/';
            $sreplace[] = 'https://img.youtube.com/';

            $sfind[] = 'http://maps.googleapis.com/';
            $sreplace[] = 'https://maps.googleapis.com/';

            $sfind[] = RL_URL_HOME.'request.ajax.php';
            $sreplace[] = str_replace('http://', 'https://', RL_URL_HOME."request.ajax.php");
        }

        $content = str_replace($sfind, $sreplace, $content);

        if (($config['secure_front'] && !defined('REALM')) || $dealers_page_secured) {
            if ($GLOBALS['page_info']['Controller'] == 'account_type') {
                $users = '';
                if( $GLOBALS['alphabet_dealers'] ) {
                    foreach( $GLOBALS['alphabet_dealers'] as $k => $dealer ) {
                        $users .=$dealer['Own_address']."|";
                    }
                }
                $users = substr($users, 0, -1);

                if ($users) {
                    $reg_find = '#http://('.$users.')'.$GLOBALS['domain_info']['domain'].'/#';
                    $reg_replace = 'https://$1'.$GLOBALS['domain_info']['domain'].'/';
                    $content = preg_replace( $reg_find, $reg_replace, $content);
                }
            } elseif ($GLOBALS['page_info']['Key'] == 'view_details') {
                $str_find = $GLOBALS['seller_info']['Personal_address'];
                $str_replace = str_replace('http://', 'https://', $str_find);

                $content = str_replace($str_find, $str_replace, $content);
            } elseif ($GLOBALS['page_info']['Key'] == 'my_profile') {

                $str_find = $GLOBALS['profile_info']['Personal_address'];
                $str_replace = str_replace('http://', 'https://', $str_find);

                $content = str_replace($str_find, $str_replace, $content);
            }
        }
    }

    /**
     * @hook phpSmartyClassFetch
     * 
     * @since 1.2.0
     **/
    public function hookPhpSmartyClassFetch(&$param1) {
        $this->replaceContent($param1);
    }

    /**
     * @hook SmartyFetchHook
     * 
     * @since 1.2.0
     **/
    public function hookSmartyFetchHook(&$param1) {
        $this->replaceContent($param1);
    }

    /**
     * @hook apPhpPagesPost
     * 
     * @since 1.2.0
     **/
    public function hookApPhpPagesPost() {
        $_POST['https'] = $GLOBALS['info']['Https'];
    }

    /**
     * @hook apPhpPagesBeforeAdd
     * 
     * @since 1.2.0
     **/
    public function hookApPhpPagesBeforeAdd() {
        $GLOBALS['data']['Https'] = $_POST['https'];
    }

    /**
     * @hook apPhpPagesBeforeEdit
     * 
     * @since 1.2.0
     **/
    public function hookApPhpPagesBeforeEdit() {
        $GLOBALS['update_data']['fields']['Https'] = $_POST['https'];
    }

    /**
     * @hook apTplPagesForm
     * 
     * @since 1.2.0
     **/
    public function hookApTplPagesForm() {
        echo '<tr><td class="name">'. $GLOBALS['lang']['sp_page'] .'</td><td class="field">';

        if ($_POST['https'] == '1') {
            $https_yes = 'checked="checked"';
        } elseif ($_POST['https'] == '1') {
            $https_no = 'checked="checked"';
        } else {
            $https_no = 'checked="checked"';
        }

        echo '<label><input '. $https_yes .' class="lang_add" type="radio" name="https" value="1" /> '. $GLOBALS['lang']['yes'] .' </label>';
        echo '<label><input '. $https_no .' class="lang_add" type="radio" name="https" value="0" /> '. $GLOBALS['lang']['no'] .' </label></td></tr>';
    }

    /**
     * @hook apBoot
     * 
     * @since 1.2.0
     **/
    public function hookApBoot() {
        global $config;

        if (!$_POST['xjxfun']) {
            if (isset($config['secure_admin_panel'])) {
                $secure_admin_config = $config['secure_admin_panel'];
            } else {
                $secure_admin_config = $this->getOne("Default", "`Key`='secure_admin_panel'", "config");
            }

            if ($secure_admin_config && $this->serverHttpsOff()) {
                $redirect = str_replace('http://', 'https://', RL_URL_HOME);
                $sbstr = RL_DIR ? strlen(RL_DIR) + 1 : 1;
                $redirect .= substr($_SERVER['REQUEST_URI'], $sbstr);
                $this->redirect(null, $redirect);
            } elseif (!$secure_admin_config && $this->serverHttpsOn() && false === strpos(RL_URL_HOME, 'https://')) {
                $redirect = str_replace('https://', 'http://', RL_URL_HOME);
                $sbstr = RL_DIR ? strlen(RL_DIR) + 1 : 1;
                $redirect .= substr($_SERVER['REQUEST_URI'], $sbstr);
                $this->redirect(null, $redirect);
            }
        }
    }

    /**
     * @hook phpMailSend
     * 
     * @since 1.2.0
     **/
    public function hookPhpMailSend(&$param1, &$param2) {
        $this->replaceContent($param1);
        $this->replaceContent($param2);
    }

    /**
     * @hook reeflessRedirctTarget
     * 
     * @since 1.2.0
     **/
    public function hookReeflessRedirctTarget(&$param1) {
        $this->replaceContent($param1);
    }

    /**
     * @hook ajaxRequest
     *  
     * @since 1.3.0
     **/
    public function hookAjaxRequest(&$param1) {
        $this->replaceContent($param1);
    }

    /**
     * @hook reeflessRedirctTarget - for 4.5.2 
     *  
     * @since 1.3.0
     **/
    public function hookReeflessWwwRedirect(&$param1) {
        $this->replaceContent($param1);
    }

    /**
     * @hook staticDataPostGet
     *  
     * @since 1.3.3
     **/
    public function hookStaticDataPostGet(&$files) {
        foreach ($files as &$file) {
            $this->replaceContent($file);
        }
    }

    /**
     * @hook apNotifications
     *  
     * @since 1.3.3
     **/
    public function hookApNotifications(&$notifications) {
        if (false !== strpos(RL_URL_HOME, 'https://')) {
            $notifications[] = $GLOBALS['lang']['sp_ap_deprecated_notice'];
        }
    }
}
