<?php 
/*#################################################################*\
|# Licence Number 0H6R-0808-0UVQ-0111
|# -------------------------------------------------------------   #|
|# Copyright (c)2012 PHP Link Directory.                           #|
|# http://www.phplinkdirectory.com                                 #|
\*#################################################################*/
	 
	 
/**
 # ################################################################################
 # Project:   PHP Link Directory
 #
 # **********************************************************************
 # Copyright (C) 2004-2012 NetCreated, Inc. (http://www.netcreated.com/)
 #
 # This software is for use only to those who have purchased a license.
 # A license must be purchased for EACH installation of the software.
 #
 # By using the software you agree to the terms:
 #
 #    - You may not redistribute, sell or otherwise share this software
 #      in whole or in part without the consent of the the ownership
 #      of PHP Link Directory. Please contact david@david-duval.com
 #      if you need more information.
 #
 #    - You agree to retain a link back to http://www.phplinkdirectory.com/
 #      on all pages of your directory if you purchased any of our "link back" 
 #      versions of the software.
 #
 #
 # In some cases, license holders may be required to agree to changes
 # in the software license before receiving updates to the software.
 # **********************************************************************
 #
 # For questions, help, comments, discussion, etc., please join the
 # PHP Link Directory Forum http://www.phplinkdirectory.com/forum/
 #
 # @link           http://www.phplinkdirectory.com/
 # @copyright      2004-2012 NetCreated, Inc. (http://www.netcreated.com/)
 # @projectManager David DuVal <david@david-duval.com>
 # @package        PHPLinkDirectory
 # @version        4.2.1
 # ################################################################################
 */
 ////register_globals turned ON is a major security hole
////we'll unset ALL variables requested via URL
//
//if (ini_get ('register_globals'))
//{
//   //Get request variables
//   $getRequest = array_keys ($_REQUEST);
//   //Loop through each variable
//   foreach ($getRequest as $var)
//   {
//      //Test if variable was declared
//      if ($_REQUEST[$var] === $var)
//      {
//         //Set value of the variable to NULL,
//         //just in case unset does not work
//         $var = null;
//
//         //Unset variable
//         unset($var);
//      }
//   }
//   unset ($getRequest);
//}


error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

//register_globals turned ON is a major security hole
//we'll unset ALL variables requested via URL
$register_globals = trim(ini_get('register_globals'));
 if (!empty($register_globals) && strtolower($register_globals) != 'off') {
   //Get request variables
   $getRequest = array_keys ($_REQUEST);
   //Loop through each variable
   foreach ($getRequest as $var)
   {
      //Test if variable was declared
      if ($_REQUEST[$var] === $var)
      {
         //Set value of the variable to NULL,
         //just in case unset does not work
         $var = null;

         //Unset variable
         unset($var);
      }
   }
   unset ($getRequest);
}

/**
 * Define some application wide constants to increase security.
 * By checking them in included files, further execution can be blocked for unauthorized access.
 */
define ('IN_PHPLD', true); //For all files

//Start page generation timer
define ('PLD_TIMESTART', microtime());

//Detect web-server software
define ('IS_APACHE', ( strstr ($_SERVER['SERVER_SOFTWARE'], 'Apache') || strstr ($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') ) ? 1 : 0);
define ('IS_IIS'   , strstr ($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') ? 1 : 0);

//Get type of interface between web server and PHP
define('SAPI_NAME', php_sapi_name());

require_once 'include/version.php';
require_once 'include/config.php';
require_once 'include/client_info.php';
require_once 'include/settings.php';
require_once 'include/tables.php';
require_once 'include/functions.php';
require_once 'include/validation_functions.php';
require_once 'Validator.class.php';
require_once 'include/functions_validate.php';
require_once 'include/dirdb.php';
session_start();

if (get_magic_quotes_gpc()){ 
 $_GET = custom_stripslashes($_GET); 
 $_POST = custom_stripslashes($_POST); 
 $_COOKIE = custom_stripslashes($_COOKIE); 
 $_REQUEST = custom_stripslashes($_REQUEST); 
}

//Do not allow prefetching for logged in users (only for guests)
//Google Web Accelerator can display sensitive data
if ($_SESSION['phpld']['user']['id'] > 0 && strpos ($_SERVER['HTTP_X_MOZ'], 'prefetch') !== false)
{
   if (SAPI_NAME == 'cgi' || SAPI_NAME == 'cgi-fcgi')
   @ header ('Status: 403 Forbidden');
   else
   @ header ('HTTP/1.1 403 Forbidden');

   //Terminate the current script
   exit ('Prefetching is not allowed.');
}

define ('SERVER_DOC_ROOT', dirname (__file__));//example:/var/www/html/admin
define ('DOC_ROOT',       substr ($_SERVER["SCRIPT_NAME"], 0, strrpos ($_SERVER["SCRIPT_NAME"], '/')));
define ('DIRECTORY_ROOT', substr ($_SERVER["SCRIPT_NAME"], 0, strrpos ($_SERVER["SCRIPT_NAME"], '/')));


if (!defined ('DB_DRIVER'))
{
   http_custom_redirect(DOC_ROOT.'/install/index.php');
}

require_once 'libs/intsmarty/intsmarty.class.php';
require_once 'libs/smarty/SmartyPaginate.class.php';
$cachecheck = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ($cachecheck)
{
$sql = "SELECT * FROM `PLD_CONFIG` WHERE `ID` = 'DB_CACHING' ";
mysql_select_db(DB_NAME);
$dbc = mysql_query($sql);
$dbcc=mysql_fetch_array($dbc);
define ('DB_CACHING',$dbcc['VALUE']);
}
else
{
   define('ERROR', 'ERROR_DB_CONNECT');
   exit('ERROR :: Could not connect to database server!');
}
mysql_close($cachecheck);
if (DB_CACHING == '1')
{
require_once 'libs/adodb/adodb.inc.php';
}else{
require_once 'libs/adodb/ncadodb.inc.php';
}

//Add custom database library extender
require_once 'include/adodb_extender.php';

//Connect to database
$db = ADONewConnection(DB_DRIVER);
if ($db->Connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME))
{
   $db->SetFetchMode(ADODB_FETCH_ASSOC);

  // $setCharset = $db->Execute ("SET NAMES 'utf8'");
  // $setCharset = $db->Execute ("SET CHARACTER SET utf8");
   
   //Load extenders to count executions
   $db->fnExecute = 'CountExecs';
   $db->fnCacheExecute = 'CountCachedExecs';

   $phpldSettings = read_config($db);
}
else
{
   define('ERROR', 'ERROR_DB_CONNECT');
   exit('ERROR :: Could not connect to database server!');
}

if (DEBUG === 1)
{
   set_log('frontend_log.txt');
}

//Define current time
if (defined ('SERVER_OFFSET_TIME'))
{
   //Calculate with offset time
   define ('TIMENOW', time() + (SERVER_OFFSET_TIME * 60 * 60));
}
else
{
   //Offset time was not defined, use current time
   define ('TIMENOW', time());
}
$phpldSettings['TIMENOW'] = TIMENOW;


//Path to cache directory
//You might want to set this outside your document root
$db_cache_dir     = SERVER_DOC_ROOT . '/temp/adodb/';
$db_cache_timeout = (defined ('DB_CACHE_TIMEOUT') ? DB_CACHE_TIMEOUT : 3600);
if (DB_CACHING == '0')
{
	// Clear cache data if DB Caching not used
	//$db->cacheSecs = 1;
   //Flush database cache
  // phpLDAdoCache::phpld_ExpiredCacheFlush($db_cache_dir);
	//$db->CacheFlush();
}
//do NOT use DB caching if "register_globals" is ON
if (DB_CACHING == '1' && !ini_get('register_globals'))
{
   //Clear all expired cache files
   if (is_dir ($db_cache_dir) && is_writeable ($db_cache_dir))
   {
      //Define database cache directory
      $ADODB_CACHE_DIR = $db_cache_dir;

      //Define cache timeout
      $db->cacheSecs = (int)$db_cache_timeout;

      //Flush database cache
      phpLDAdoCache::phpld_ExpiredCacheFlush($ADODB_CACHE_DIR);
      
      $db->CacheFlush();
   }
}


//Define session ID
define ('PLD_SESSION_ID', session_id());



//Send character set header
@ header ('Content-type: text/html; charset='.(defined ('CHARSET') ? CHARSET : 'utf-8'));

if (isset($_SESSION['phpld']['user']['id'])) {
   $user_level = get_user_level($_SESSION['phpld']['user']['id']);
}

if (!isset($_SESSION['phpld']['user']['id']) || (isset($user_level) && ($user_level<=0))) {
	//Load input filter
	require_once 'libs/inputfilter/class.inputfilter_php4.php';
	//Run input filter, request variables should be safe now
	require_once 'include/io_filter.php';
}

//Initialize template
if (USE_MOBILE_SITE == '1')
{
$tpl = &get_tpl();
}else{
$tpl = &get_tplnm();
}


$tpl->cache_lifetime = 0;
define ('TEMPLATE_PATH'     , 'templates/'.USE_TEMPLATE);
define ('FULL_TEMPLATE_PATH', DOC_ROOT.'/templates/'.USE_TEMPLATE);
$phpldSettings['TEMPLATE_PATH']      = TEMPLATE_PATH;
$phpldSettings['FULL_TEMPLATE_PATH'] = FULL_TEMPLATE_PATH;
$tpl->assign('core_templates', CORE_TEMPLATES);

$tpl->assign("user_level", $user_level);

////need next one so that when a user logges in, he's redirected to the previous page he was visiting
//if (!strpos($_SERVER['REQUEST_URI'], 'login.php') && !strpos($_SERVER['REQUEST_URI'], 'captcha.php') && !strpos($_SERVER['REQUEST_URI'], 'content.css') && !strpos($_SERVER['REQUEST_URI'], 'inplace')) {
//    $_SESSION['prev_page'] = $_SERVER['REQUEST_URI'];
//}


require_once 'include/constants.php';
$tpl->assign('VERSION', CURRENT_VERSION);

//META Tags
$MetaKeywords    = DEFAULT_META_KEYWORDS;
$MetaDescription = DEFAULT_META_DESCRIPTION;
$MetaAuthor      = DEFAULT_META_AUTHOR;
$MetaCopyright   = DEFAULT_META_COPYRIGHT;
$MetaRobots      = DEFAULT_META_ROBOTS;

$tpl->assign('MetaRobots'     , trim ($MetaRobots)      );
$tpl->assign('MetaKeywords'   , trim ($MetaKeywords)    );
$tpl->assign('MetaDescription', trim ($MetaDescription) );
$tpl->assign('MetaAuthor'     , trim ($MetaAuthor)      );
$tpl->assign('MetaCopyright'  , trim ($MetaCopyright)   );

//By default, Javascript libraries are disabled
//If needed enable them on submit page or whatever else page
//$load_Javascript = 1;
//$tpl->assign('load_Javascript', $load_Javascript);

$regular_user_details = $db->GetRow("SELECT `ID`, `LOGIN`, `NAME`, `EMAIL` FROM `{$tables['user']['name']}` WHERE `ID` = ".$db->qstr($_SESSION['phpld']['user']['id'])." AND `ACTIVE` = '1'");
$tpl->assign('regular_user_details', $regular_user_details);

// Disallow access to the page if it's not allowed for editors
if ($_SESSION['phpld']['user']['id'])
{
   if (preg_match ('!^admin/?([a-bA-B](\.php))?$!', $_SESSION['return']))
      $_SESSION['return'] = SITE_URL;
}

$URLcomponents = @ parse_url ($_SERVER['REQUEST_URI']);
if (is_array ($URLcomponents) && !empty ($URLcomponents))
{
   @ parse_str ($URLcomponents['query'], $URLvariables);
}
// ---misc  ---------

	
	//if required email confirmation add this to sql queries
	if (EMAIL_CONFIRMATION == 1) {
	    $email_conf = " AND `OWNER_EMAIL_CONFIRMED` = '1' ";
	}
	
	
	//random featured
	$random_link = $db->GetAll("SELECT * FROM {$tables['link']['name']} WHERE FEATURED = 1 AND STATUS=2 ORDER BY RAND() LIMIT 3");
	foreach($random_link as $k => $v) {
        $random_link[$k]['SEO_URL'] = seo_url($v['ID'], $v['TITLE'], REWRITE_TYPE, REWRITE_EXT, 2);
    }
	$tpl->assign('random_link', $random_link);
// ----------------------------------
//Credit goes to Tojo from the phpLD Forums for the scriptname code
$tpl->assign('scriptname'        , basename($_SERVER[PHP_SELF], ".php"));
$maincontent = MAINCONTENT;
$tpl->assign('maincontent', $maincontent);





if (isset($_SESSION['phpld']['user']['id'])) {
    //...from session we take its level
    $uLevel = $_SESSION['phpld']['user']['level'];
    $tpl->assign('uLevel', $uLevel);
}

if (isset($_SESSION['phpld']['user']['id'])) {
    //need this one for add category/page rights
    
    $rights =  user_needs_approval($_SESSION['phpld']['user']['id'], 0);

    $tpl->assign('rights', $rights);
}

if (!empty($_SESSION['inplace_caterror'])) {
    $tpl->assign('inplace_caterror', $_SESSION['inplace_caterror']);
    //unset($_SESSION['inplace_caterror']);
}
if (!empty($_SESSION['inplace_linkerror'])) {
    $tpl->assign('inplace_linkerror', $_SESSION['inplace_linkerror']);
    //unset($_SESSION['inplace_linkerror']);
}
if (!empty($_SESSION['inplace_arterror'])) {
    $tpl->assign('inplace_arterror', $_SESSION['inplace_arterror']);
    //unset($_SESSION['inplace_arterror']);
}
if (!empty($_SESSION['inplace_pageerror'])) {
    $tpl->assign('inplace_pageerror', $_SESSION['inplace_pageerror']);
    //unset($_SESSION['inplace_arterror']);

}

//widget related//
//get link id for details pages for widgets
if (basename($_SERVER[PHP_SELF], ".php") == 'detail')
{
if(!empty($action))
{
   $lid = $action[1];
}
elseif (ENABLE_REWRITE == 1)
{
      // Know extensions
   $ext = array('.htm', '.html', '.php', '/');
   $lid = explode('-', $_REQUEST['id']);
   $el = count($lid) - 1;
   $lid = intval(str_replace($ext, '', $lid[$el]));
}
else
{
   $lid = (!empty ($_REQUEST['id']) ? $_REQUEST['id'] : 0);
}
define ('LID', $lid);
}

require_once INSTALL_PATH.'/widgets/Widget.php';

$wd = new Widget();

$widgets = get_active_widgets();

$tpl->assign('widgets', $widgets);

//end of widget related//


$catid = get_category();
$tpl->assign('catid', $catid);

//Main categories
$mainCategs = $db->CacheGetAll("SELECT * FROM `{$tables['category']['name']}` WHERE (`STATUS` = '2') AND `PARENT_ID` = 0 ORDER BY `".CATEG_FIELD_SORT."` ".CATEG_FIELD_SORT_ORDER);
	
if (!empty($mainCategs)) {
	for ($i =0; $i< count($mainCategs); $i++) {
    	$mainCategs[$i]['SUBCATS'] = $db->CacheGetAll("SELECT * FROM `{$tables['category']['name']}` WHERE (`STATUS` = '2') AND `SYMBOLIC` <> '1' AND `PARENT_ID` = ".$db->qstr($mainCategs[$i]['ID'])." ORDER BY `".CATEG_FIELD_SORT."` ".CATEG_FIELD_SORT_ORDER);
	}
}

$tpl->assign('mainCategs', $mainCategs);


$tpl->assign('ratings_on', LINK_RATING);
$tpl->assign('comments_on', LINK_COMMENT);
$tpl->assign('tell_friend_on', LINK_TELL_FRIEND);

//Disable any caching by the browser
disable_browser_cache();

$tpl->assign('validation_messages', $validation_messages);

//RALUCA: JQuery validation related FOR TOP LOGIN FORM
$validators = array(
	'rules' => array(
		'user' => array(
						'required' => true
				),
	    'pass' => array(
						'required' => true
				)
	)
);

$vld = json_custom_encode($validators);
$tpl->assign('login_validators', $vld);

$validators = array(
	'rules' => array(
		'search' => array(
						'required' => true
				)
	)
);
$vld = json_custom_encode($validators);
$tpl->assign('search_validators', $vld);
//RALUCA: end of JQuery validation related

//The problem: we need to use js form.submit() function.
//But, all the forms have an <input name="submit"> which is used to test if the form was submitted: if (!empty($_REQUEST['submit'])) { ... }
//These inputs conflicts with the .submit() method. The browsers will raise a js error instead of submitting the form.
//The workaround: all the <input name="submit"> are renamed to <input name="whatever">.
//<input type="hidden" name="formSubmitted" value="1" /> - added to all forms
if (!empty($_REQUEST['formSubmitted'])) {
	$_REQUEST['submit'] = $_REQUEST['formSubmitted'];
} 
if (!empty($_POST['formSubmitted'])) {
	$_POST['submit'] = $_POST['formSubmitted'];
} 
if (!empty($_GET['formSubmitted'])) {
	$_GET['submit'] = $_GET['formSubmitted'];
}

?>