<?php

/******************************************************************************
 *  
 *  PROJECT: Flynax Classifieds Software
 *  VERSION: 4.5.2
 *  LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *  PRODUCT: Real Estate Classifieds
 *  DOMAIN: savingrack.com
 *  FILE: RLSMARTY.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 rlSmarty extends Smarty 
{
	/**
	* class constructor
	**/
	function __construct()
	{
		global $config;
		
		//$this -> force_compile = true;
		
		if (defined('REALM'))
		{
			$this->template_dir = RL_ROOT . ADMIN_DIR . 'tpl' . RL_DS;
			$this->compile_dir = RL_TMP . 'aCompile';
		}
		else 
		{
			$this->template_dir = RL_ROOT . 'templates' . RL_DS . $config['template'] . RL_DS . 'tpl' . RL_DS;
			$this->compile_dir = RL_TMP . 'compile';
		}
		
		$this->cache_dir = RL_TMP . 'cache';
	}

    /**
     * rewrite method to fix resource_name path taking into account the template core requests
     *
     * @since 4.5.2
     */
    function fetch($resource_name, $cache_id = null, $compile_id = null, $display = false)
    {
        $this->fixURI($resource_name);

        return parent::fetch($resource_name, $cache_id, $compile_id, $display);
    }

    /**
     * rewrite method to fix $params['smarty_include_tpl_file'] path taking into account the template core requests
     *
     * @since 4.5.2
     */
    function _smarty_include($params)
    {
        $this->fixURI($params['smarty_include_tpl_file']);

        parent::_smarty_include($params);
    }

    /**
     * fix the file path and replace default template with template core of the requested file doesn't exists
     *
     * @since 4.5.2
     *
     * @param string - requested file 
     */
    private function fixURI(&$file)
    {
        if (!defined('REALM') && TPL_CORE) {
            if (strpos($file, RL_ROOT) !== 0) {
                $file = $this->template_dir . $file;
            }

            if (!file_exists($file)) {
                $file = str_replace($GLOBALS['config']['template'], 'template_core', $file);
            }
        }
    }
	
	/**
	* create fckEditor
	*
	* @param array $aParams - editor options
	*
	**/
	function fckEditor($aParams)
	{
        /* load JS of CKEditor lib */
        $this->fckEditorJsLoad = !$this->fckEditorJsLoad ? true : false;
        $aParams['fckEditorJsLoad'] = $this->fckEditorJsLoad;

        $this->assign_by_ref('fckEditorParams', $aParams);
        $this->display('blocks' . RL_DS . 'fckEditor.tpl');
	}
	
	/**
	* convert string to url path
	*
	* @param array $aParams - string
	*
	**/
	function str2path( $aParams )
	{
		$string = is_array($aParams) ? $aParams['string'] : $aParams ;
		$string = $GLOBALS['rlValid'] -> str2path($string);
		
		return $string;
	}

	/**
	* convert int format to money format
	*
	* @param array $aParams - string
	*
	**/
	function str2money($aParams) {
		$string = is_array($aParams) ? $aParams['string'] : $aParams;

		if (!$GLOBALS['rlValid']) {
			$this->loadClass('Valid');
		}
		return $GLOBALS['rlValid']->str2money($string);
	}
	
	/**
	* build paging block
	*
	* @param int $calc - calculated items
	* @param int $total - total items
	* @param int $per_page - per page items number
	* @param string $add_url - additional url
	* @param string $var - non mod_revrite mod variable
	* @param string $controller - controller name
	* @param string $method - variables transfer method
	* @param string $custom - custom url
	* @param bool $full - use full initial page url
	*
	**/
	function paging($aParams)
	{
		global $page_info, $lang, $config;
	
        $calc = $aParams['calc'];
        $total = is_array($aParams['total']) ? count($aParams['total']) : $aParams['total'];
        $pagination_tpl = $this->template_dir . RL_DS . 'blocks' . RL_DS . 'pagination.tpl';
        
        $this->fixURI($pagination_tpl);

        // return if the tpl file doesn't exist
        if (!is_file($pagination_tpl) && $calc > $total) {
            echo "No pagination.tpl file found";
            return;
        }
        
        $per_page = $aParams['per_page'];
        $aParams['pages'] = ceil($calc / $per_page);
        $aParams['current'] = $aParams['current'] == 0 ? 1 : $aParams['current'];
        $add_url = $aParams['url'];
        $custom = $aParams['custom'];
        $full = $aParams['full'];
        $base = rtrim(SEO_BASE, 'index.php');

        // return if there is just one page
        if ($aParams['pages'] <= 1) {
            return;
        }

        // build url
        if ($config['mod_rewrite']) {
            if (empty($add_url)) {
                if ($custom) {
                    $first_url = $base . $custom;
                    $tpl_url = $base . $custom . '/index[pg].html';
                    $first_url = $full ? str_replace('[pg]', '1', $tpl_url) : $first_url;
                } else {
                    $first_url = $base . $page_info['Path'] . '.html';
                    $tpl_url = $base . $page_info['Path'] . '/index[pg].html';
                }
            } else {
                $first_url = $base . $page_info['Path'] . '/' . $add_url;

                // categoryFilter trailing html bug fix
                if (is_numeric(strpos($add_url, ':'))) {
                    $first_url .= '/';
                } else {
                    $first_url .= '.html';
                }

                $tpl_url = $base . $page_info['Path'] . '/' . $add_url . '/index[pg].html';
                $first_url = $full ? str_replace('[pg]', '1', $tpl_url) : $first_url;
            }
            
            if ($method == 'get') {
                preg_match('/^([^\?]*)\?/', $_SERVER['REQUEST_URI'], $matches);
                if ($matches[0]) {
                    $request_string = preg_replace('/^([^\?]*)\?/', '', $_SERVER['REQUEST_URI']);
                    $first_url .= '?'. $request_string;
                    $tpl_url .= '?'. $request_string;
                }
            }
        }
        else {
            $query_string = preg_replace('/(page\=[^\?\&]+)/', '', $_SERVER['QUERY_STRING']);
            $query_string = preg_replace('/(\&?\??pg\=[^\?\&]+)/', '', $query_string);
            
            $first_url = $tpl_url = $base . 'index.php?page=' . $page_info['Path'] . '&amp;pg=1';
            $tpl_url = $tpl_url = $base . 'index.php?page=' . $page_info['Path'] . '&amp;pg=[pg]';
            
            if ($add_url) {
                $first_url .= $var ? '&amp;' . $var . '=' . $add_url : '&amp;'. $add_url;
                $tpl_url .= $var ? '&amp;' . $var . '=' . $add_url : '&amp;'. $add_url;
            }
        }

        $aParams['first_url'] = $first_url;
        $aParams['tpl_url'] = $tpl_url;

        // display tpl pagination file
        $this->assign('pagination', $aParams);
        $this->display($pagination_tpl);
	}
	
	/**
	* search form build
	*
	* @param string $key - form key
	* @param bool $photos - "with photos only" check box using
	* @param mixed - hidden fields, unlimited
	*
	**/
	function search($aParams)
	{
		global $df, $reefless;

		$key = $_SESSION['post_form_key'] = $aParams['key'];
		$photos = isset($aParams['photos']) && (bool) $aParams['photos'] === false ? false : true;
	
		if (empty($df)) {
			$reefless->loadClass('Categories');
			$df = $GLOBALS['rlCategories']->getDF();
			$this->assign_by_ref('df', $df);
		}
		
		unset($aParams['key'], $aParams['photos']);
		
		if (!empty($aParams)) {
			$GLOBALS['rlDb']->setTable('listing_fields');
			$available_fields = $GLOBALS['rlDb']->fetch( array('Key'), array('Status' => 'active') );
			$GLOBALS['rlDb']->resetTable();
			
			foreach ($available_fields as $afVal) {
				$a_fields[] = $afVal['Key'];
			}
			
			unset($available_fields);
			
			foreach ($aParams as $afKey => $akVal) {
				if (!in_array($afKey, $a_fields)) {
					unset($aParams[$afKey]);
				}
			}
			
			$this->assign('hidden_fields', $aParams);
		}

		/* get search forms */
		$GLOBALS['reefless']->loadClass('Search');
		$form = $GLOBALS['rlSearch']->buildSearch($key);

		$form['listing_type'] = $GLOBALS['rlDb']->getOne("Type", "`Key` ='{$key}'", "search_forms");

		$this->assign_by_ref('form', $form);
		$this->assign_by_ref('form_key', $key);
		$this->assign_by_ref('use_photos', $photos);
		
		$this->display('blocks' . RL_DS . 'search_block.tpl');
	}
	
	/**
	* encode e-mail address to javascript code
	*
	* @param array $email - email to encode
	*
	**/
	function encodeEmail( $params = false )
	{
		global $rlValid, $reefless, $lang;
		
		$email = $params['email'];
		
		if ( !$email || !$rlValid -> isEmail($email) )
			return false;
			
		$out = '<a href="mailto:'. $email .'">'. $email .'</a>';
		$len = strlen($out);
		$step = rand(3, 7);
		$max = $len * $step;
		$range = range(0, $max-1);

		for ( $i = 0; $i < $len; $i++)
		{
			$index = $this -> encodeEmailSet($range);
			$array[$index] = $out[$i];
			$indexes[$i*$step] = $index;
		}
		
		for ( $i = 0; $i < $max; $i++)
		{
			if ( !isset($indexes[$i]) )
			{
				$index = $this -> encodeEmailSet($range);
				$array[$index] = $reefless -> generateHash(1, 'password');
				$indexes[$i] = $index;
			}
		}
		
		ksort($array);
		ksort($indexes);

		$js_l = "['". implode("','", $array) ."']";
		$js_i = "['". implode("','", $indexes) ."']";
		
		$var1 = $reefless -> generateHash(7, 'lower', false).'c';
		$var2 = $reefless -> generateHash(7, 'lower', false).'x';
		$var3 = $reefless -> generateHash(7, 'lower', false).'a';
		$GLOBALS['encoded_email_index'] = $GLOBALS['encoded_email_index'] ? $GLOBALS['encoded_email_index'] + 1 : 1;
		$code = <<<VS
<span id="encoded_email_{$GLOBALS['encoded_email_index']}"></span><script type="text/javascript">//<![CDATA[
var $var1 = $js_l;var $var2 = $js_i;var $var3 = new Array(); var js_e = '';for(var i = 0; i<$var1.length;i+=$step){ $var3.push({$var1}[{$var2}[i]]); } for(var i = 0; i<$var3.length;i++){js_e += {$var3}[i]}; $('#encoded_email_{$GLOBALS['encoded_email_index']}').html(js_e).next().remove();
//]]></script><noscript>{$lang['noscript_show_email']}</noscript>
VS;
		echo $code;
	}
	
	/**
	* populate array | secondary methods for encodeEmail()
	*
	* @param array $array - array in use
	*
	**/
	function encodeEmailSet( &$range )
	{
		$i = rand(0, count($range) - 1);
		$t = $range[$i];
		unset($range[$i]);
		$range = array_values($range);
		
		return $t;
	}

	/**
	* generates rss url
	*
	* @return string - rss page URL
	**/
    function getRssUrl($params = false) {
    	global $config, $pages;

    	$rss = $this -> get_template_vars('rss');
    	$url = SEO_BASE;

    	if ($config['mod_rewrite']) {
    		$url .= $pages['rss_feed'].'/';
    		$url .= $rss['item'] ? $rss['item'] .'/' : '';

    		if ($params['mode'] == 'footer' && !$rss['id'] && !$rss['listing_type']) {
    			$url .= 'news/';
    		} else {
	    		$url .= $rss['id'] ? $rss['id'] .'/' : '';
	    		$url .= $rss['listing_type'] ? $rss['listing_type'] .'/' : '';
	    	}
    	} else {
    		$url .= '?page='.$pages['rss_feed'];

    		if ($params['mode'] == 'footer' && !$rss['id'] && !$rss['listing_type']) {
    			$url .= '&item=news';
    		} else {
	    		$url .= $rss['item'] ? '&item='. $rss['item'] : '';
	    		$url .= $rss['id'] ? '&id='. $rss['id'] : '';
	    		$url .= $rss['listing_type'] ? '&id='. $rss['listing_type'] : '';
	    	}
    	}

    	return $url;
    }

    /**
	* generates category url
	*
	* @return string - category url
	**/
    function categoryUrl($params = false) {

    	$data = is_array($params['category'])
    			? $params['category']['ID']
    			: (int) $params['id'];
		$custom_lang = $params['custom_lang'];

    	$out = $GLOBALS['reefless']->getCategoryUrl($data, $custom_lang);

    	if ($params['assign']) {
    		$this -> assign($params['assign'], $out);
    	} else {
	    	return $out;
	    }
    }

    /**
	* generates listing url
	*
	* @return string - listing url
	**/
    function listingUrl($params = false) {

		$data = is_array($params['listing'])
    			? $params['listing']
    			: (int) $params['id'];
		$custom_lang = $params['custom_lang'];

		$out = $GLOBALS['reefless']->url('listing', $data, $custom_lang);

    	if ($params['assign']) {
    		$this -> assign($params['assign'], $out);
    	} else {
	    	return $out;
	    }
    }

    /**
	* generates page url
	*
	* @return string - page url
	**/
    function pageUrl($params = false) {

    	$key = $params['page'] ?: $params['key'];
    	$add_url = $params['add_url'];
		$custom_lang = $params['custom_lang'];

		$out = $GLOBALS['reefless'] -> getPageUrl($key, $add_url, $custom_lang);

    	if ($params['assign']) {
    		$this -> assign($params['assign'], $out);
    	} else {
    		return $out;
    	}
    }

	/**
	* transforms compiled smarty output
	*
	* @param string compiled content
	* @return string - transformed content
	**/
	function transformSmartyOutput($compiled_content, $resource_name) {
		if ($GLOBALS['rlListingTypes']) {
			$compiled_content = $GLOBALS['rlListingTypes'] -> prepareListingTypeLinks($compiled_content);
		}

		$GLOBALS['rlHook'] -> load('smartyFetchHook', $compiled_content, $resource_name);

		// static data class parser
		if (!defined('REALM') && REALM != 'admin') {
			$compiled_content = $GLOBALS['rlStatic']->collectJSDynamicCode($compiled_content, $resource_name);
		}

		return $compiled_content;
	}
}