Location: PHPKode > projects > Esvon Personals > esvon-personals/inc/app_init.php
<?php

// --------------------------------------------------------------------------
//
// Esvon Classifieds v.4.0
// Copyright(C), Esvon LTD, 2001-2010, All Rights Reserved.
// E-mail: hide@address.com
//
// All forms of reproduction, including, but not limited to, internet posting, 
// printing, e-mailing, faxing and recording are strictly prohibited.
// One license required per site running Esvon Classifieds. 
// To obtain a license for using Esvon Classifieds, please register at
// http://www.esvon.com/pg/products/p_classifieds/
//
// --------------------------------------------------------------------------

if(!defined('SITE_PATH')) die('Access Denied');

// if(version_compare(PHP_VERSION,'4.2') < 0) die('You should upgrade to PHP 4.2.0 or later');

define('TBL_USER',TBL_PREFIX.'user');
define('TBL_AD',TBL_PREFIX.'ad');
define('TBL_CAT',TBL_PREFIX.'category');
define('TBL_SETTINGS',TBL_PREFIX.'hw_settings');
define('TBL_IP',TBL_PREFIX.'ip');
define('TBL_REG_CONFIRM',TBL_PREFIX.'register');
define('TBL_PAY_LOG',TBL_PREFIX.'payment_log');
define('TBL_PAY_PEND',TBL_PREFIX.'payment_pending');
define('TBL_PAY_EXP',TBL_PREFIX.'expense');
define('TBL_ADM_LOGIN',TBL_PREFIX.'admin_login');
define('TBL_REL_LINK',TBL_PREFIX.'related_links');
define('TBL_REL_CAT',TBL_PREFIX.'related_cat');
define('TBL_MODULES',TBL_PREFIX.'modules');
define('TBL_PAY_PLAN',TBL_PREFIX.'price_plan');
define('TBL_PP_CAT',TBL_PREFIX.'price_plan_category');
define('TBL_PP_USER',TBL_PREFIX.'price_plan_user');
define('TBL_SESSION',TBL_PREFIX.'session');
define('TBL_RESERV_FLD',TBL_PREFIX.'reserved_field');
define('TBL_EXTRA_OPT',TBL_PREFIX.'extra_opt');
define('TBL_TPL',TBL_PREFIX.'template');
define('TBL_FIELD',TBL_PREFIX.'field');
define('TBL_FS',TBL_PREFIX.'fset');
define('TBL_USER_ON',TBL_PREFIX.'user_online');
define('TBL_CAT_EXTRA',TBL_PREFIX.'category_extra');
define('TBL_FILE',TBL_PREFIX.'file');
define('TBL_DEP_MENU',TBL_PREFIX.'dep_menu');
define('TBL_DEP_MENU_TREE',TBL_PREFIX.'dep_menu_tree');
define('TBL_HITS',TBL_PREFIX.'hits');

//ini_set('session.save_handler', 'files');
//session_save_path ('tmp_dir/');
// Session Timeout Value, seconds
//ini_set('session.gc_maxlifetime', '1440');
//ini_set('allow_url_fopen', 1);
//ini_set('auto_detect_line_endings', true);

ini_set('session.auto_start', 0);
@ini_set('session.use_trans_sid', 0);
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);

// assert_options(ASSERT_ACTIVE, 0);

// reduce connection timeout
ini_set('default_socket_timeout', 5);
ini_set('gd.jpeg_ignore_warning', 1); // PHP 5.1.3+

umask(000);

define('HW_TIME', isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time() ); // since php 5.1
define('SQL_NOW', 'FROM_UNIXTIME('.HW_TIME.')');

define('ADM_TPL_PATH', TPL_PATH.'admin/'); //full path with trailing "/"

define('FS_DIR', 'db_fields');
define('MOD_DIR', SITE_PATH.'modules/');
define('CACHE_DIR', SITE_PATH.'files/cache/');

define('FILE_DIR', SITE_PATH.'files/');

define('HW_IS_WINDOWS', DIRECTORY_SEPARATOR == '\\');

// functions area, alter only if you know what you do

function hwMetaTagsSetup($a_v){
global $db,$META_K,$META_D,$HW_LANG;
  if($a_v['cid']){
    $v = array();
    if($HW_LANG!='en' && hwModGetState('Multi_Lang') == 'A'){
      $v = $db->one_assoc('SELECT meta_k,meta_d FROM '.hwModTable('Multi_Lang','category').
      ' WHERE id="'.$a_v['cid'].'" AND lang_id="'.$HW_LANG.'"');
      if($v['meta_k']) $META_K = $v['meta_k'];
      if($v['meta_d']) $META_D = $v['meta_d'];
    }
    if(!$v['meta_k'] || !$v['meta_d']){
      $v = $db->one_assoc('SELECT meta_k,meta_d FROM '.TBL_CAT.' WHERE id="'.$a_v['cid'].'"');
      if($v['meta_k']) $META_K = $v['meta_k'];
      if($v['meta_d']) $META_D = $v['meta_d'];
    }
  }
}

function hwSQLFieldsGet($all = false, $db_f = ''){
global $TITLE_FIELD;

if($db_f){
  if($db_f[0]!=',') $db_f = ','.$db_f;
  if(strpos($db_f,',hw_region_id')!==false && hwModGetState('Regions') != 'A') $db_f = str_replace(',hw_region_id','',$db_f);
}

if(!$all) return 'link_id,images,catid,'.$TITLE_FIELD.' AS f_title'.$db_f;

static $sql;
if(!isset($sql)){
  global $db;
  $sql = $db->one_col_array('SELECT DISTINCT(db_f) FROM '.TBL_FIELD.' WHERE fset NOT LIKE "'.FS_CH1.'%"');
  $sql = 'link_id,images,catid,'.implode(',',$sql);
  if(hwModGetState('Multi_Lang')=='A') $sql.=',hw_lang_id';
  $A_EO_ID = array_keys( hwGetExtraOptionIDs( array( // visibility options
    'prefix' => 'hw_',
    'case' => 'lower',
  )));
  if($A_EO_ID) $sql.=','.implode(',',$A_EO_ID);
}
return $sql.$db_f;

}

function hwSQLRowGet($a_Ad, $opts = array()){ // returns ad_url, images, f_title
  if($a_Ad['images']) list($a_Ad['images']) = explode("\n",$a_Ad['images']);
  if(!isset($a_Ad['f_title']) && count($a_Ad)>3){ 
    $a_Ad['v_descr'] = strip_tags($a_Ad['v_descr']);
    if(DESCR_MAX_LEN>0 && strlen($a_Ad['v_descr'])>DESCR_MAX_LEN) $a_Ad['v_descr'] = substr($a_Ad['v_descr'],0,DESCR_MAX_LEN).'..';
    if($a_Ad['catid']){

      $fs = hwGetFsByCat($a_Ad['catid']);
      $O_FS = &Factory::singleton('FieldsSet',$fs);
      $a_Ad = $O_FS->FillCustomFieldsArray($a_Ad);
      $O_FS->AdjustCustomFields($a_Ad);
      
      static $A_FS_NO_DBF = array(); // fields to remove
      if(!isset($A_FS_NO_DBF[$fs])){
        $a_v = array();
        foreach(array_keys($a_Ad) as $fid){
          if(!strncmp($fid, 'v_255_', 6)) $a_v[$fid] = '';
        }
        $A_FS_NO_DBF[$fs] = $a_v;
        unset($a_v);
      }
      if(count($A_FS_NO_DBF[$fs])>0){ 
        if(function_exists('array_diff_key')) $a_Ad = array_diff_key($a_Ad, $A_FS_NO_DBF[$fs]);
        else{
          foreach(array_keys($A_FS_NO_DBF[$fs]) as $db_f) unset($a_Ad[$db_f]);
        }
      }
    }
    //if(ctype_digit($a_Ad['hw_added'])) $a_Ad['hw_added'] = strftime($DATE_FMT,$a_Ad['hw_added']);
    //if(ctype_digit($a_Ad['hw_updated'])) $a_Ad['hw_updated'] = strftime($DATE_FMT,$a_Ad['hw_updated']);
  }
  $a_Ad['ad_url'] = hwGetAdURL($a_Ad['link_id']);
  unset($a_Ad['link_id']);

  /*if($opts['w_region']){
    $a_Ad['REGION_PATH'] = '';
    if($a_Ad['hw_region_id']){
      static $tbl_reg;
      if(!isset($tbl_reg)) $tbl_reg = hwModTable('Regions','category');
      $o_cache = &Factory::singleton('Hw_Cache');
      $a_Ad['REGION_PATH'] = $o_cache->get('f_Reg_Path_'.$GLOBALS['HW_LANG'].'_'.$a_Ad['hw_region_id'],"ShowCategoryPath(".$a_Ad['hw_region_id'].",'index.php?page=search&s_res=AND&hw_region_id=##cid##', $tbl_reg)");
    }
  }*/

  return $a_Ad;
}

function hwSendMail($to, $from, $subj, $msg, $hw_uid = 0, $attach = false){
  $o_m =& Factory::create('Hw_Mail');
  if($hw_uid) $o_m->setUserID($hw_uid);
  $o_m->sendParsed($to, $from, $subj, $msg, $attach);
}

function SE_VerifyValidURL($valid_url){
  if(EN_SE_ADV){ 
    hwProcessTags($valid_url);
    if($p = strpos($valid_url,'<')) $valid_url = substr($valid_url, 0, $p);
  }
  $s = basename($_SERVER['REQUEST_URI']);
  if($p = strpos($s,'.html?')) $s = substr($s,0,$p+5);
  if($s != $valid_url){
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: '.SITE_URL.$valid_url);
    exit;
  }
}

function hwAppInit(){

if(get_magic_quotes_gpc()) {

	$in = array(&$_GET, &$_POST, &$_COOKIE);
	while(list($k,$v) = each($in)) {
		foreach($v as $k1 => $v1) {
			if(!is_array($v1)) {
				$in[$k][$k1] = stripslashes($v1);
				continue;
			}
			$in[] =& $in[$k][$k1];
		}
	}
	unset($in);

	if(!empty($_FILES)) {
    foreach(array_keys($_FILES) as $k){ 
      if(is_array($_FILES[$k]['name'])) $_FILES[$k]['name'] = array_map('stripslashes', $_FILES[$k]['name']);
      else $_FILES[$k]['name'] = stripslashes($_FILES[$k]['name']);
    }
	}
} 

if(ini_get('register_globals')){
  $in = array('_GET'=>1,'_POST'=>1,'_REQUEST'=>1,'_COOKIE'=>1,'_SERVER'=>1,'_ENV'=>1,'_FILES'=>1,'GLOBALS'=>1,'TITLE_FIELD'=>1);
  if($_REQUEST) foreach (array_keys($_REQUEST) AS $k){
    if(!$in[$k]) unset($GLOBALS[$k]);
  }
}

  $_REQUEST = ($_SERVER['REQUEST_METHOD']=='POST') ? array_merge($_GET, $_POST) : $_GET;

  $a_funcs = array(
    'file_get_contents', // since 4.3
//    'array_chunk', // since 4.2
  );
  
  foreach($a_funcs as $k=>$f){
    if(function_exists($f)) unset($a_funcs[$k]);
  }
  if(count($a_funcs) > 0) hwLoadFunction($a_funcs);

  global $O_HW;

  if(EN_CRON && $_SERVER['HTTPS']!='on' && (CRON_TIME + 86400 < HW_TIME)){

    $O_HW->Update( array('CRON_TIME' => HW_TIME) );
    
    hwCURL( array(
      'url' => SITE_URL.'cron/cl_cron.php',
      'nobody' => 1,
      'method' => 'socket',
    ));
  }
 
  if(hwModGetState('Auction')=='A'){
    // Auction Closing handler
    $sec = 300; // checking time intervals, seconds
    $MOD_CFG = $O_HW->GetModOptions('Auction');
    $ok = $sec ? 0 : 1;
    if(!$ok && ($MOD_CFG['CLOSE_TIME'] + $sec < HW_TIME)){
      $MOD_CFG['CLOSE_TIME'] = HW_TIME;
      $O_HW->SetModOptions('Auction', $MOD_CFG);
      $ok = 1;
    }
    if($ok && $GLOBALS['db']->one_data('SELECT count(*) FROM '.TBL_AD.' WHERE exp_date<'.SQL_NOW.' AND hw_auct_closed="N"')){
      include MOD_DIR.'Auction/hw_auct_close.php';
    }
  }

}

/***************************************************/

class esPage {

  var $tpl_header = 'header.htm';
  var $tpl_footer = 'footer.htm';
  var $func_inner_page = '';
  var $_buf_inner = '';
  var $_buf_header = '';
  var $_buf_footer = '';

  function setInnerPage($s){ $this->_buf_inner = $s; }
  function setHeader($s){ $this->_buf_header = $s; }
  function setFooter($s){ $this->_buf_footer = $s; }
  function getHeader(){ 
    
    if($this->_buf_header!='') return $this->_buf_header;
    $tpl_v = array();
  // $tpl_v['head_date'] = strftime('%A %B %d, %Y'); //Wednesday December 1, 2010
    $tpl_v['cid'] = (int)$_REQUEST['cid'];
    $tpl_v['SES_UID'] = (int)hwSessionGetVar('userid');
    //$tpl_v['HTTPS'] = $_SERVER['HTTPS']=='on' ? 1 : 0;
    $tpl_v['q'] = '';
    if($_GET['q']!='') $tpl_v['q'] = html_esc($_GET['q']);

    $buf = EvalAdvTpl(TPL_PATH.$this->tpl_header, $tpl_v);
    if($GLOBALS['JQUERY']) $buf = preg_replace('/<\/head>/i',
      '<script src="img/jquery.js"></script>'.
      '<script src="img/jquery.blockUI.js"></script>'.
      '</head>', $buf);
    return $buf;
  }
  
  function getFooter(){ 
    if($this->_buf_footer!='') return $this->_buf_footer;
    $tpl_v = array();
    $tpl_v['cid'] = (int)$_REQUEST['cid'];
    $tpl_v['SES_UID'] = (int)hwSessionGetVar('userid');
    //$tpl_v['HTTPS'] = $_SERVER['HTTPS']=='on' ? 1 : 0;
    return EvalAdvTpl(TPL_PATH.$this->tpl_footer, $tpl_v);
  }
  function getInnerPage(){ return $this->_buf_inner; }
  function getContents($wrap = true){ 

    ob_start();
    if($this->func_inner_page){ $f = $this->func_inner_page; $buf = $f(); }
    else $buf = $this->getInnerPage();
    $ob_buf = ob_get_contents();
    ob_end_clean();
    if(!$buf) $buf = $ob_buf;
    unset($ob_buf);

    if($wrap) $buf = $this->getHeader().$buf.$this->getFooter();
    hwProcessTags($buf);
    return $buf; 
  }
}

class Factory {

  function &singleton($class_id, $arg = ''){ // $sign
    static $a_obj = array();
    
    $class_id = strtoupper($class_id);
    if($class_id=='FIELDSSET' && $arg=='') $arg = $GLOBALS['FSET_DIR'];
    
    $obj_id = $class_id.($arg!='' ? '_'.$arg : '');
    if(!isset($a_obj[$obj_id])){ 

      $a_obj[$obj_id] =& Factory::create($class_id, $arg);
      
      switch($class_id){
      
        case 'TAG_FILTER':
          $a_tags = hwReadCfgFile(TPL_PATH.'allowed_html.txt');
          if($a_tags){ 
            $a_tags = '<'.implode('><',$a_tags).'>';
            $a_obj[$obj_id]->setAllowedTags($a_tags);
          }
          break;
          
      }
    }

    return $a_obj[$obj_id];
  }

  function &create($id, $args = ''){
    static $A_OK = array();
    
    if(!isset($A_OK[$id])){
      $class_id = hwLoadClass($id);
      $A_OK[$id] = $class_id;
    }
    else $class_id = $A_OK[$id];

    switch($class_id){

      case 'HW_CACHE':
        return new $class_id( CACHE_DIR, CACHING_TIME_M*60, HW_TIME, 'CacheKeyAdjust' );

      case 'IMAGE_RESIZER':
        $obj = new $class_id(GD_VER);
        if(defined('THUMB_FILL') && defined('THUMB_BG') && THUMB_FILL) $obj->setFillColor(THUMB_BG);
        if(defined('EN_IMAGEMAGICK') && defined('IM_DIR') && EN_IMAGEMAGICK) $obj->setImageMagickPath(IM_DIR);
        return $obj;

      case 'MEDIA_IMAGE':
        return new $class_id(TBL_AD,'images','link_id',0,FILE_DIR);
/*
      case 'MEDIA_VIDEO':
        return new $class_id(TBL_AD,'videos','link_id',0,FILE_DIR);

      case 'MEDIA_AUDIO':
        return new $class_id(TBL_AD,'audios','link_id',0,FILE_DIR);
*/

      default:

        /*if($class_id=='FIELDSSET' && substr($args[0],-11)=='ufields.txt'){ 
          $arg1 = $args[0];
          $args[0] = TPL_PATH.'ufields_buyer.txt';
          array_unshift($args, $arg1);
        }*/

        $new_id = 'ES_CLASS_'.$class_id; // custom classes support
        if(defined($new_id)) $class_id = constant($new_id);
        return new $class_id($args);
    }
  }

  function &getFieldInstance($a_f){
    static $a_obj = array();
    $type = $a_f['TYPE'];
    if(!isset($a_obj[$type])) $a_obj[$type] =& Factory::createField($a_f);
    else $a_obj[$type]->Init($a_f);
    return $a_obj[$type];
  }

  function &createField($a_f, $type = ''){
    if(!class_exists('FieldsSet')) hwLoadClass('FieldsSet');
    if(!$type) $type = $a_f['TYPE'];
    $class_name = strtoupper($type.'Field');
    return Factory::create($class_name, $a_f);
    //return new $class_name($a_f);
  }

  function &getMediaObj($id = 'ALL', $hw_pay_plan = '', $fs = false){
    
    $a_class = array( // db_field => class_name
      'images' => 'Media_Image',
//      'audios' => 'Media_Audio',
//      'videos' => 'Media_Video',
    );
    
    $CFG = hwGetFSConfig($fs);

    // 26.08.2010 - && $fs
    if(!$CFG['EN_IMAGES'] && $fs) unset($a_class['images']); // universal naming convention ??

    $a_obj = array();
    
    if($id == 'ALL') $id = '';
    if($id){
      if(!isset($a_class[$id])) return false;
      $a_obj[$id] = &Factory::singleton($a_class[$id]);
    }
    else {
      foreach($a_class as $media_id=>$class_id) $a_obj[$media_id] = &Factory::singleton($class_id);
    }

    $a_opts = $hw_pay_plan ? hwGetOptsArrFromPlans($hw_pay_plan) : false;
    if($a_opts) foreach(array_keys($a_obj) as $media_id){
      $a_obj[$media_id]->adjustOptions($a_opts); 
    }

    return $id ? $a_obj[$id] : $a_obj;
  }

}

/***************************************************/

function CacheKeyAdjust($base_key){
  // selective key adjustment is possible
  return $base_key.'_'.$GLOBALS['HW_LANG'];
}

function hwLoadFunction($funcs) {
  if (!is_array($funcs)) $funcs = array($funcs);
  foreach($funcs as $func){
    if(!function_exists($func)) {
      $func = strtolower($func);
      if((include SITE_PATH."inc/funcs/$func.php") === false) trigger_error('Failed to load '.$func, E_USER_ERROR);
    }
  }
}

function hwLoadClass($_class_id) {
static $pear_inc;

    $class_id = strtoupper($_class_id);
    // Array for alternative class names
    $A_ALIAS = array(
//      'SMARTY' => 'HW_SMARTY',
    );
    
    $is_pear = false;
    if(!strncmp($class_id,'PEAR::',6)){
      $class_id = substr($_class_id,6);
      $is_pear = true;
      if(!$pear_inc){
        $pear_inc = true;
        ini_set('include_path', SITE_PATH.'inc/pear'.PATH_SEPARATOR.ini_get('include_path'));
      }
    }
    else $class_id = isset($A_ALIAS[$class_id]) ? $A_ALIAS[$class_id] : $class_id;

    if(!class_exists($class_id)){

      // Array for classes not using automatic naming convention, e.g.:
      // FTP -> ftp.inc.php (instead of class.ftp.php).
      $A_FILE = array(
          'FIELDSSET' => 'class.fields.php', // ,class.fields_extra.php
//        'FTP' => 'ftp.inc.php',
      );

      if($is_pear){ // XML_HTMLSax is in XML dir
        $subdir = ($p=strpos($class_id, '_')) ? substr($class_id,0,$p).'/' : '';
        $fn = 'pear/'.$subdir.$class_id.'.php';
      }
      elseif(isset($A_FILE[$class_id])) $fn = $A_FILE[$class_id];
      else {
        $fn = $class_id;
        if(!strncmp($fn,'HW_',3)) $fn = substr($fn, 3);
        $fn = 'class.'.strtolower($fn).'.php';
      }
      
      $a_fn = explode(',', $fn);
      foreach($a_fn as $fn){
        if((include SITE_PATH.'inc/'.$fn) === false) trigger_error('Failed to load '.$fn, E_USER_ERROR);
      }
    }
    return $class_id;
}


/*
esFilter - input filtering function
Usage example:

$whitelist = array(
  'name' => array(
    'type' => 'string',
    'maxlength' => 50,
  ),
);
if($_POST) $clean = esFilter($_POST, $whitelist);

$whitelist options :
type - string, int, decimal, alpha, email, url, phone, zip, option, print, regexp
maxlength (all types except "option")
For "option" type - options (Array or 'int'), multiselect (Boolean)
For "regexp" type - pattern (String)
*/

function esFilter($input, $whitelist) {

  $clean = array();
  if(!$input || !is_array($input)) return $clean;

  foreach(array_keys($whitelist) as $k) {
 
      if($input[$k]=='') continue; // not set or empty
      $val = $input[$k];
      if(is_array($val)){
        if($whitelist[$k]['type']!='option') continue;
      }
      else{
        $val = trim($val);
        if(isset($whitelist[$k]['maxlength']) && (strlen($val) > $whitelist[$k]['maxlength'])) continue;
      }

      $filtered = NULL;
      
      switch ($whitelist[$k]['type']) {
        case 'string':
          $filtered = preg_match('/^[-\w\.\'"\(\):;, ]*$/', $val) ? $val : NULL;
          //$filtered = (!is_array($val) && !preg_match("/[\r\n]+/",$val)) ? $val : NULL;
          break;
        case 'int':
          $filtered = ctype_digit($val) ? $val : NULL;
          break;
        case 'decimal':
          $filtered = preg_match('/^[0-9]{1,20}\.?[0-9]{0,20}$/', $val) ? $val : NULL;
          break;
        case 'alpha':
          $filtered = ctype_alnum( str_replace('_','',$val) ) ? $val : NULL;
//          $filtered = preg_match('/^\w+$/', $val) ? $val : NULL;
          break;
        case 'print':
          $filtered = ctype_print($val) ? $val : NULL;
          break;
        case 'print_ws': // printable + white spaces allowed
          $filtered = ctype_print( preg_replace('/[\r\n\t]/','',$val) ) ? $val : NULL;
          break;
        case 'email':
          $filtered = preg_match('/^[A-Z0-9._%+-]+@(?:[-A-Z0-9]+\.)+[A-Z]{2,}$/i', $val) ? $val : NULL;
          // if(!class_exists('Validate')) hwLoadClass('PEAR::Validate');
          // $filtered = Validate::email($val) ? $val : NULL;
          break;
        case 'url':
          $filtered = preg_match('/^https?:\/\/[^\s"\']+$/i', $val) ? $val : NULL;
          // if(!class_exists('Validate')) hwLoadClass('PEAR::Validate');
          // $filtered = Validate::uri($val) ? $val : NULL;
          break;
        case 'phone':
          $filtered = preg_match('/^[\(]?(\d{3})[\)]?[\s]?[\-]?(\d{3})[\s]?[\-]?(\d{4})[\s]?[x]?(\d*)$/', $val) ? $val : NULL;
          break;
        case 'zip':
          $filtered = preg_match('/^(\d{5})[\-]?(\d{4})?$/', $val) ? $val : NULL;
          break;
        case 'regexp':
          $filtered = preg_match($whitelist[$k]['pattern'], $val) ? $val : NULL;
          break;
        
        case 'option':
          
          if($whitelist[$k]['options']=='int'){
            $filtered = array();
            if(is_array($val)) foreach($val as $opt) {
              if(ctype_digit($opt)) $filtered[] = $opt;
            }
            break;
          }
          
          if(!is_array($whitelist[$k]['options'])) break;
          
          if(is_array($val)) {
            if($whitelist[$k]['multiselect']) {
              $filtered = array();
              foreach ($val as $opt) {
                if(in_array($opt, $whitelist[$k]['options'])) $filtered[] = $opt;
              }
            }
          } else {
            $filtered = in_array($val, $whitelist[$k]['options']) ? $val : NULL;
          }
          break;
      }
      if (!is_null($filtered)) $clean[$k] = $filtered;
  }
  return $clean;
}


function hwTplVarModify($v,$p){

  $A_FUNCS = array(
    'addslashes' => 1,
    'htmlentities' => 1,
    'nl2br' => 1,
    'strip_tags' => 1,
    'trim' => 1,
    'ucfirst' => 1,
    'ucwords' => 1,
    'urlencode' => 1,
    'floor' => 1,
    'ceil' => 1,
  );
  
  // TODO: sprintf, preg_replace, etc

  $A_ALIAS = array(
    'count_words' => 'str_word_count',
    'lower' => 'strtolower',
    'upper' => 'strtoupper',
    'lc' => 'strtolower',
    'uc' => 'strtoupper',
    'len' => 'strlen',
    'html_esc' => 'htmlspecialchars',
  );

  $func = $p[0];
  unset($p[0]);
  
  $is_aliased = false;
  if($A_ALIAS[$func]){ 
    $func = $A_ALIAS[$func]; 
    $is_aliased = true; 
  }

  if($A_FUNCS[$func] || $is_aliased){
    if($func=='htmlspecialchars' || $func=='htmlentities') return $func($v, ENT_QUOTES);
    // if($func=='trim') $v = str_replace('&nbsp;', '', $v);
    if(!function_exists($func)) hwLoadFunction($func);
    return $func($v);
  }

  switch($func){
    case 'replace':
      if($p[1]=='~nl~') $p[1] = array("\r\n","\r","\n");
      return str_replace($p[1],$p[2],$v);
    case 'escape':
      switch($p[1]){
        case 'htmlall':
          return htmlentities($v, ENT_QUOTES);
        case 'url':
          return rawurlencode($v);
        case 'hex':
        case 'hexentity': 
          $ch = $p[1] == 'hex' ? '%' : '&#x';
          $len = strlen($v); $ret = '';
          for($i=0; $i < $len; $i++) $ret .= $ch.bin2hex($v[$i]);
          return $ret;
        case 'mail':
          return str_replace(array('@', '.'), array(' [AT] ', ' [DOT] '), $v);
        default: // html
          return htmlspecialchars($v, ENT_QUOTES);
      }
    case 'truncate':
      $max_len = (int)$p[1];
      $trail_chars = $p[2];
      if(strlen($v)>$max_len){ 
        $v = substr($v,0,$max_len).$trail_chars;
      }
      return $v;
    case 'round':
      return round($v, (int)$p[1]);
    case 'date_format':
      if(!ctype_digit((string)$v)) $v = strtotime($v);
      $date_fmt = $p[1];
      return strftime($date_fmt,$v);
    case 'reverse':
      if($v=='' || strpos($v, $p[1])===false) return $v;
      $a_v = explode($p[1], $v);
      $a_v = array_reverse($a_v);
      return implode($p[2]!='' ? $p[2] : $p[1], $a_v);
    case 'explode':
      $a_v = explode($p[1], $v);
      $idx = $p[2];
      if($idx<0) $idx = count($a_v)+$idx;
      if(!isset($a_v[$idx])) return '';
      return $a_v[$idx];
    case 'remove':
      if($p[1]=='~nl~') $p[1] = array("\r","\n");
      return str_replace($p[1],'',$v);
    case 'mod':
      if($p[1] && is_numeric($p[1])) return $v % $p[1];
      return;
    case 'wordwrap':
      if(!$p[1]) $p[1] = 75;
      if(!$p[2]) $p[2] = "\n";
      return wordwrap($v,$p[1],$p[2],$p[3]);
    case 'number_format':
      if(strpos($v,',')!==false) $v = str_replace(',','',$v); // strip commas
      return number_format($v,$p[1],$p[2],$p[3]); // int decimals, dec_point, thousands_sep 
    case 'pos':
      return strpos($v,$p[1]);
    case 'op':
      if($p[1]=='*') return $v*$p[2];
      //if($p[1]=='/' && $p[2]!=0) return $v/$p[2];
      //if($p[1]=='+') return $v+$p[2];
      //if($p[1]=='-') return $v-$p[2];
  }

  return;
}

/* Specifies some restricted mod_events which are called only if at least 1 module 
handling such event (below) is active - for better performance */
function hwIsModEventAllowed($event){
  $A_MOD = array(
    'onLFSObjSetup' => 'Auction,Availability',
    'onExtraOptionsGet' => 'Availability',
  );
  if(isset($A_MOD[$event])){
    $a_mod = explode(',', $A_MOD[$event]);
    if($a_mod) foreach($a_mod as $mod){
      if(hwModGetState($mod) == 'A') return 1;
    }
  }
  return 0;
}

function hwIsAuction($lid, $opts = NULL){
  if(hwModGetState('Auction') != 'A') return 0;
  if(!function_exists('hwIsRealAuction')){
    if((include MOD_DIR.'Auction/hw_auct_info.php') === false) trigger_error('Failed to load Auction/hw_auct_info.php', E_USER_ERROR);
  }
  static $A_OK;
  $cache_it = false;
  if($lid && is_null($opts)){
    if(isset($A_OK[$lid])) return $A_OK[$lid];
    $cache_it = true;
  }
  $ret = hwIsRealAuction($lid, $opts);
  if($cache_it) $A_OK[$lid] = $ret;
  return $ret;
}

function hwGetFSConfig($fs = false){
  if($fs===false) $fs = $GLOBALS['FSET_DIR'];
  return $GLOBALS['O_HW']->GetFSetOptions($fs);
}

function hwErrMsgRequired($s){
  return sprintf(hwLng('req'),ucfirst($s));
}

function IsEmail($s) {
  if(!is_string($s)) return false;
  if(!class_exists('Validate')) hwLoadClass('PEAR::Validate');
  return Validate::email($s);
}

function html_esc($s) {
  if($s=='') return $s;
  return htmlspecialchars($s, ENT_QUOTES);
}

function ob_gz_cookie($s) { 
static $i;
  if(!isset($i)) $i = 1;
  else $i++;
  setcookie("ob_gz_$i", strlen($s));
  return $s;
}

define('ES_SH_FILE_DIR', FILE_DIR);
//define('FILE_URL', 'http://192.168.1.10:8080/files/');
//define('ES_SH_FILE_DIR', 'C:/webdev/files/');

class esSharedFile {
  function exists($f){
    return file_exists(ES_SH_FILE_DIR.$f); // thumbnails ???
  }
  function remove($f){
    @unlink(ES_SH_FILE_DIR.$f);
  }
  function write($f, $buf, $ap = false){
    FileWrite(ES_SH_FILE_DIR.$f, $buf, $ap);
    chmod(ES_SH_FILE_DIR.$f, 0666);
  }
  function getURL($f){
    return FILE_URL.$f;
  }
  // getPath() is used for faster files handling on local file system
  // and should be commented out on remote files environment where getStream() will be used
  function getPath($f){
    return ES_SH_FILE_DIR.$f;
  }
  function getStream($f){
    return fopen(ES_SH_FILE_DIR.$f);
  }
  function copy($src, $short_fname){
    $f_out = ES_SH_FILE_DIR.$short_fname;
    // for "duplicating"
    if(strpos($src,DIRECTORY_SEPARATOR)===false && basename($src) == $src) $src = ES_SH_FILE_DIR.$src;
    return copy($src, $f_out);
  }

  //function open($f, $mode){} 
  //function touch($f){}
  //function chmod($f, $mode){}
  //function lastModified($f){}
}

// timer class

class HwTimer {
	var $ts;
    function startTimer() {
      $this->ts = array_sum(explode(' ', microtime()));
    }
    function endTimer() {
      return round ((array_sum(explode(' ', microtime())) - $this->ts), 5);
    }
}

if(DEBUG_LEVEL>0){ 
  $HwTimer = &Factory::singleton('HwTimer');
  $HwTimer->startTimer();
  unset($HwTimer);
}

require SITE_PATH.'inc/lib.inc.php';

// Initialize environment

if(isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) { exit; }
if($_SERVER['REQUEST_METHOD']=='POST' && $_SERVER['HTTP_REFERER']!='' && !strpos($_SERVER['HTTP_REFERER'], '/'.$_SERVER['HTTP_HOST'].'/')) {
  die('This form may not be used outside of its parent site');
}

// workaround for shell CLI
if(!isset($_SERVER['REMOTE_ADDR'])) $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
define('REMOTE_ADDR', $_SERVER['REMOTE_ADDR']);

$_SERVER['PHP_SELF'] = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES);
if(isset($_SERVER['HTTP_HOST'])) $_SERVER['HTTP_HOST'] = htmlspecialchars($_SERVER['HTTP_HOST'], ENT_QUOTES);

// IIS workaround
if(HW_IS_WINDOWS && !$_SERVER['REQUEST_URI']){
  if(!isset($_SERVER['PATH_INFO']) && isset($_SERVER['ORIG_PATH_INFO'])) $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
  $_SERVER['REQUEST_URI'] = $_SERVER['URL'] ? $_SERVER['URL'] : $_SERVER['PATH_INFO'];
  if(isset($_SERVER['QUERY_STRING'])) $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
}

if(!defined('ADMIN_AREA') && $_SERVER['HTTP_HOST']){
  $_dir = dirname($_SERVER['REQUEST_URI']);
  if(strlen($_dir)==1) $_dir = '';
  else $_dir = htmlspecialchars($_dir, ENT_QUOTES);
  define('SITE_URL','http'.($_SERVER['HTTPS']=='on' ? 's' : '').'://'.$_SERVER['HTTP_HOST'].$_dir.'/');
  unset($_dir);
}

define('PHP_SELF_BASE', basename($_SERVER['PHP_SELF'])); // /dir/file.php

if(!defined('PATH_SEPARATOR')) define('PATH_SEPARATOR', DIRECTORY_SEPARATOR == '\\' ? ';' : ':' ); // 4.3

require SITE_PATH.'inc/class.tpl_hawk.php';
require SITE_PATH.'inc/class.settings.php';
require SITE_PATH.'inc/class.mysql.php';

/***************************************************/

$db = new Database;
if(!$db->connect(DB_SERVER,DB_USER,DB_PW,DB_NAME)){ 
  $db->error('MySQL connection attempt failed');
  exit;
}

$O_HW = new HawkSettings('hw');
$O_HW->Init();

// DB Upgrade script ?
if(defined('DB_UPGRADE')) return;

if(!defined('FILE_URL')) define('FILE_URL', SITE_URL.'files/');

if(!defined('ADMIN_AREA')){
  if(EN_WARN_INSTALL_EX && file_exists(SITE_PATH.'install.php')) die('Warning: Installation file exists: install.php. Please remove this file for security reasons');
}

if(EN_GZIPPED_PHP && !ini_get('zlib.output_compression')){
  if(DEBUG_LEVEL>0) ob_start('ob_gz_cookie');
  ob_start('ob_gzhandler');
  if(DEBUG_LEVEL>0) ob_start('ob_gz_cookie');
}

ini_set('display_errors', EN_PHP_ERR ? 'On' : 'Off');

if($_POST['go_x']) $_POST['go'] = 1;

if(!extension_loaded('ctype')){
  function ctype_digit($s){
    return (is_string($s) && preg_match('/^\d+$/',$s));
  }
  function ctype_print($s){ // specific implementation for our purposes
    return (is_string($s) && !preg_match('/[\r\n]/',$s));
  }
  function ctype_alnum($s){
    return (is_string($s) && preg_match('/^[a-z0-9]+$/iD',$s));
  }
}

hwAppInit();

if(!defined('IS_CRON')){

  if($_REQUEST['hw_cache']=='on') session_cache_limiter('public'); // IE on SSL fails to download file with "nocache"
  elseif($_REQUEST['hw_cache']=='form') session_cache_limiter('private, must-revalidate'); // Form-values are cached, but pages are not
  // elseif(in_array((string)$_GET['page'], array('browse','search','out'))) session_cache_limiter('private_no_expire');
  else session_cache_limiter('nocache');

  hwSessionInit();
  if(function_exists('output_reset_rewrite_vars')) output_reset_rewrite_vars();
}
else hwLangInit(LANG_DEF);

// Die if IP is banned (after session start)
if(hwIsBannedIP(TPL_PATH.'banned_ips.txt','ban_ip')){
  include TPL_PATH.'banned.htm';
  exit;
}

if(!defined('ADMIN_AREA') && !IsUser(0)) hwMemberAutoLogin();

$FSET_DIR = GetCurFieldsSet();

/* ***************************** */ 
Return current item: Esvon Personals