<?php 
/*#################################################################*\
|# Licence Number 0NKV-1011-132L-0118
|# -------------------------------------------------------------   #|
|# Copyright (c)2018 PHP Link Directory.                           #|
|# http://www.phplinkdirectory.com                                 #|
\*#################################################################*/
	 
/**
  # ################################################################################
  # Project:   PHP Link Directory
  #
  # **********************************************************************
  # Copyright (C) 2004-2013 NetCreated, Inc.
  # This software is licensed per-installation.
  # **********************************************************************
  # @version        5.1.0 Phoenix Release
  # ################################################################################
 */

// Show all but warnings/notices (matches your original intent)
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
// Consider hiding deprecations in production (optional):
// error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
@date_default_timezone_set('UTC');

// ---- register_globals hardening (legacy safeguard) ----
$register_globals = trim(ini_get('register_globals'));
if (!empty($register_globals) && strtolower($register_globals) != 'off') {
    $getRequest = array_keys($_REQUEST);
    foreach ($getRequest as $var) {
        if ($_REQUEST[$var] === $var) {
            $var = null;
            unset($var);
        }
    }
    unset($getRequest);
}

// ---- App-wide constants ----
define('IN_PHPLD', true);
define('PLD_TIMESTART', microtime());
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);
define('SAPI_NAME', php_sapi_name());

// ---- Core includes (order matters) ----
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';

/**
 * IMPORTANT:
 * Load the Smarty 4 compatibility shim (IntSmarty) BEFORE functions.php,
 * because legacy code in functions.php expects class IntSmarty to exist.
 */
require_once __DIR__ . '/libs/IntSmarty.php';                      // <- shim extends Smarty 4
require_once __DIR__ . '/libs/smarty/SmartyPaginate.class.php';    // <- keep existing paginator

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';

spl_autoload_register('phpldAutoload');
session_start();

// ---- Disallow prefetching for logged-in users ----
if (
    isset($_SESSION['phpld']['user']) &&
    $_SESSION['phpld']['user']['id'] > 0 &&
    isset($_SERVER['HTTP_X_MOZ']) &&
    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');
    exit('Prefetching is not allowed.');
}

// ---- Paths ----
define('SERVER_DOC_ROOT', dirname(__FILE__));
define('DOC_ROOT', substr($_SERVER["SCRIPT_NAME"], 0, strrpos($_SERVER["SCRIPT_NAME"], '/')));
define('DIRECTORY_ROOT', substr($_SERVER["SCRIPT_NAME"], 0, strrpos($_SERVER["SCRIPT_NAME"], '/')));

// ---- Installer redirect if DB_DRIVER missing ----
if (!defined('DB_DRIVER')) {
    http_custom_redirect(DOC_ROOT . '/install/index.php');
    exit;
}

// ---- (GLOBAL) Smarty instance via IntSmarty shim ----
// Some parts of phpLD assume $smarty is globally available.
if (!isset($smarty) || !($smarty instanceof IntSmarty)) {
    $smarty = new IntSmarty(); // IntSmarty sets template/compile/cache dirs internally
    // If you prefer to override here instead of in the shim, uncomment:
    // $smarty->setTemplateDir(__DIR__ . '/templates');       
    // $smarty->setCompileDir(__DIR__ . '/temp/templates');   
    // $smarty->setCacheDir(__DIR__ . '/temp/cache');         
}

// ---- Lightweight DB check for DB_CACHING flag ----
$cachecheck = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ($cachecheck) {
    mysqli_select_db($cachecheck, DB_NAME);
    $sql = "SELECT * FROM `PLD_CONFIG` WHERE `ID` = 'DB_CACHING'";
    $dbc = mysqli_query($cachecheck, $sql);
    if (!$dbc) {
        die('Query Error: ' . mysqli_error($cachecheck));
    }
    $dbcc = mysqli_fetch_array($dbc, MYSQLI_ASSOC);
    define('DB_CACHING', $dbcc['VALUE'] ?? null);
    mysqli_close($cachecheck);
} else {
    define('ERROR', 'ERROR_DB_CONNECT');
    exit('ERROR :: Could not connect to database server!');
}

// ---- ADOdb ----
require_once 'libs/adodb/adodb.inc.php';
if (!function_exists('ADONewConnection') && function_exists('NewADOConnection')) {
    function ADONewConnection($driver) {
        return NewADOConnection($driver);
    }
}
require_once 'include/adodb_extender.php';

// ---- Connect application DB ----
$db = ADONewConnection(DB_DRIVER);
Phpld_Db::factory($db, $tables);
if ($db->Connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)) {
    $db->SetFetchMode(ADODB_FETCH_ASSOC);
    // $db->Execute("SET NAMES 'utf8'");
    // $db->Execute("SET CHARACTER SET utf8'");
    $db->fnExecute     = 'CountExecs';
    $db->fnCacheExecute= 'CountCachedExecs';
    $phpldSettings = read_config($db);
} else {
    define('ERROR', 'ERROR_DB_CONNECT');
    exit('ERROR :: Could not connect to database server!');
}

// ---- Optional debug log ----
if (defined('DEBUG') && DEBUG === 1) {
    set_log('frontend_log.txt');
}

// ---- Time ----
if (defined('SERVER_OFFSET_TIME')) {
    define('TIMENOW', time() + (SERVER_OFFSET_TIME * 60 * 60));
} else {
    define('TIMENOW', time());
}
$phpldSettings['TIMENOW'] = TIMENOW;

// ---- ADOdb file cache (if enabled) ----
$db_cache_dir     = SERVER_DOC_ROOT . '/temp/adodb/';
$db_cache_timeout = (defined('DB_CACHE_TIMEOUT') ? DB_CACHE_TIMEOUT : 3600);
if (DB_CACHING == '1' && !ini_get('register_globals')) {
    if (is_dir($db_cache_dir) && is_writable($db_cache_dir)) {
        $ADODB_CACHE_DIR = $db_cache_dir;
        $db->cacheSecs   = (int)$db_cache_timeout;
        phpLDAdoCache::phpld_ExpiredCacheFlush($ADODB_CACHE_DIR);
        $db->CacheFlush();
    }
}

// ---- Session ID ----
define('PLD_SESSION_ID', session_id());

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

// ---- User level (optional) ----
if (isset($_SESSION['phpld']['user']['id'])) {
    $user_level = get_user_level($_SESSION['phpld']['user']['id']);
}

// ---- Input filter for guests ----
if (!isset($_SESSION['phpld']['user']['id']) || (isset($user_level) && ($user_level <= 0))) {
    require_once 'libs/inputfilter/class.inputfilter_php5.php';
    require_once 'include/io_filter.php';
}

// ---- Template selection ----
if (defined('USE_MOBILE_SITE') && USE_MOBILE_SITE == '1') {
    $tpl = get_tpl();
} else {
    $tpl = get_tplnm();
}

define('TEMPLATE_PATH', 'templates/' . TEMPLATE);
define('MOBILE_TEMPLATE_PATH', 'templates/' . MOBILE_TEMPLATE);
define('FULL_TEMPLATE_PATH', DOC_ROOT . '/templates/' . TEMPLATE);
$phpldSettings['TEMPLATE_PATH'] = TEMPLATE_PATH;
$phpldSettings['FULL_TEMPLATE_PATH'] = FULL_TEMPLATE_PATH;
define('USE_TEMPLATE', TEMPLATE);

// ---- Constants, editor route guard, URL vars ----
require_once 'include/constants.php';

if (isset($_SESSION['phpld']['user']) && $_SESSION['phpld']['user']['id']) {
    if (isset($_SESSION['return']) && 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(isset($URLcomponents['query']) ? $URLcomponents['query'] : '', $URLvariables);
}

define('FRONT_DOC_ROOT', (substr(SITE_URL, -1) == '/' ? substr(SITE_URL, 0, strlen(SITE_URL)-1) : SITE_URL));

if (!empty($_REQUEST['formSubmitted'])) { $_REQUEST['submit'] = $_REQUEST['formSubmitted']; }
if (!empty($_POST['formSubmitted']))    { $_POST['submit']    = $_POST['formSubmitted']; }
if (!empty($_GET['formSubmitted']))     { $_GET['submit']     = $_GET['formSubmitted']; }
?>
