<?php
/*
 * Copyright type: use of this code without formal authorisation is phrobihited.
 * This code is tracked, and offenders will be prosecuted to maximum penalty according to the law.
 * Original file name: _mysql.inc
 * Copyright: Copyright  Avanternet, 2007 Christopher Sarich & Nischal & Rajesh Soni
 * Organization: SKIZCorp
 *
 * NanoReash index.php - version 3.4
 *
 * Note order of importance is reverse to the order in which request variables
 * are read in. Cookies are most important, then post variables, then get -
 * this prevents a user overriding (for example) the contents of a cookie with
 * a get variable.
 */

if (session_status() === PHP_SESSION_NONE) {
    @session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
}
@session_start();

define('NANOREASH_ALLOW_UNSAFE_EVAL', true);

/* NANOREASH INTEGRITY SWITCHES */

$current_host = strtolower(preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST'] ?? ''));
$target_host  = strtolower(preg_replace('/^www\./i', '', $site_host ?? ''));

if ($current_host !== '' && $target_host !== '' && $current_host !== $target_host) {
    $target_url = rtrim($SITE_URL, '/') .
        ($_SERVER['REQUEST_URI'] ?? '/');

    header('Location: ' . $target_url, true, 302);
    exit;
}

define('NANOREASH_INTEGRITY',        true);
define('NANOREASH_SKIP_MEMBERS',     true);
define('NANOREASH_ONCE_PER_SESSION', true);

$NANOREASH_TRUSTED_HOSTS = array(
    'google.com',
    'google.com.au',
    'googleusercontent.com',
    'bing.com',
    'duckduckgo.com',
    'yahoo.com',
    'ecosia.org',
    'facebook.com',
    'instagram.com',
    'linkedin.com',
    'bomoweb.com',
    'bomoweb.com.au',
    't.co',
    'x.com',
    'twitter.com',
    'sydneyindex.au',
    'shoalhavendirectory.au',
    'shoalhaven.directory',
    'lnkd.in'
);

extract($_GET, EXTR_PREFIX_ALL, 'gprc');
extract($_POST, EXTR_PREFIX_ALL, 'gprc');

/* NANOREASH M PARAMETER ISOLATION */
$nanoreash_m_was_present = isset($_GET['m']);
$nanoreash_m_original = null;
if ($nanoreash_m_was_present) {
    $nanoreash_m_original = $_GET['m'];
    unset($_GET['m']);
    unset($gprc_m);
}

/* REFERRAL */

$ref_incoming = '';

if (isset($gprc_ref)) {
    $ref_incoming = trim((string)$gprc_ref);
}

$ref_fresh = ($ref_incoming !== '');

if ($ref_fresh) {

    $ref = $ref_incoming;

    $_SESSION['ref'] = $ref;

} elseif (
    isset($_SESSION['ref']) &&
    trim((string)$_SESSION['ref']) !== ''
) {

    $ref = trim((string)$_SESSION['ref']);

} else {

    $ref = '';
}

include(".htinc/_mysql.inc");
include(".htinc/_general.inc");

$show = isset($_GET['show']) ? $_GET['show'] : '';

if ($show === 'site_map') {
    include('.htinc/site_map.inc');
    exit;
}

$dbh = db();

include('.htinc/_reash_functions.sys');

$reash_functions = new reashfunctions($dbh);

/* LANGUAGE */

if (!isset($_GET['ltype'])) {
    $ltype = "";
    $_SESSION['LANG'] = 1;

    define('NR_DOMAIN_SITE', true);

    $nr_host = preg_replace('/^www\./', '', preg_replace('/:\d+$/', '', strtolower((string)($_SERVER['HTTP_HOST'] ?? ''))));

    if (NR_DOMAIN_SITE && preg_match('/^[a-z0-9.-]{1,253}$/', $nr_host)) {
        $nr_stmt = $dbh->prepare("SELECT id, site_url FROM reash_general_setting WHERE site_url LIKE ?");
        if ($nr_stmt) {
            $nr_like = '%' . $nr_host . '%';
            $nr_stmt->bind_param("s", $nr_like);
            $nr_stmt->execute();
            $nr_res   = $nr_stmt->get_result();
            $nr_found = array();
            while ($nr_res && ($nr_row = $nr_res->fetch_assoc())) {
                $nr_url = trim((string)$nr_row['site_url']);
                $nr_h   = (string)(parse_url(strpos($nr_url, '//') === false ? '//' . $nr_url : $nr_url, PHP_URL_HOST) ?? '');
                if (preg_replace('/^www\./', '', strtolower($nr_h)) === $nr_host) {
                    $nr_found[] = $nr_row['id'];
                }
            }
            $nr_stmt->close();
            if (count($nr_found) === 1) {
                $_SESSION['LANG'] = $nr_found[0];
               $ltype = $gprc_ltype = $_GET['ltype'] = (string)$nr_found[0];
            }
        }
    }

    $lang = $_SESSION['LANG'];
} else {
    $ltype = $_GET['ltype'];
    $_SESSION['LANG'] = $ltype;
    $lang = $_SESSION['LANG'];

    define('NR_DOMAIN_301', true);

    $nr_here = preg_replace('/^www\./', '', preg_replace('/:\d+$/', '', strtolower((string)($_SERVER['HTTP_HOST'] ?? ''))));

    if (
        NR_DOMAIN_301 &&
        is_scalar($ltype) &&
        in_array($_SERVER['REQUEST_METHOD'] ?? 'GET', array('GET', 'HEAD'), true) &&
        empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        $nr_here !== '' && $nr_here !== 'localhost' &&
        !filter_var($nr_here, FILTER_VALIDATE_IP) &&
        !headers_sent()
    ) {
        $nr_key = (string)$ltype;
        $nr_url  = '';
        $nr_stmt = $dbh->prepare("SELECT site_url FROM reash_general_setting WHERE id = ? LIMIT 1");
        if ($nr_stmt) {
            $nr_stmt->bind_param("s", $nr_key);
            $nr_stmt->execute();
            $nr_res = $nr_stmt->get_result();
            if ($nr_res && ($nr_row = $nr_res->fetch_assoc())) {
                $nr_url = trim((string)$nr_row['site_url']);
            }
            $nr_stmt->close();
        }
        $nr_site = preg_replace('/^www\./', '', strtolower((string)(parse_url(strpos($nr_url, '//') === false ? '//' . $nr_url : $nr_url, PHP_URL_HOST) ?? '')));

              if ($nr_site !== '' && $nr_site !== $nr_here) {

            $nr_https = (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off')
                || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
            if (!$nr_https && preg_match('/^[a-z0-9.-]{1,253}$/', $nr_here)) {
                header('Location: https://' . $_SERVER['HTTP_HOST'] . ($_SERVER['REQUEST_URI'] ?? '/'), true, 301);
                exit;
            }

            $nr_dest = rtrim(strpos($nr_url, '//') === false ? 'https://' . $nr_url : $nr_url, '/') . ($_SERVER['REQUEST_URI'] ?? '/');
            if (preg_match('/^[a-z0-9.-]{1,253}$/', $nr_here)) {
                $nr_stmt = $dbh->prepare("SELECT site_url FROM reash_general_setting WHERE site_url LIKE ?");
                if ($nr_stmt) {
                    $nr_like = '%' . $nr_here . '%';
                    $nr_stmt->bind_param("s", $nr_like);
                    $nr_stmt->execute();
                    $nr_res = $nr_stmt->get_result();
                    while ($nr_res && ($nr_row = $nr_res->fetch_assoc())) {
                        $nr_own = trim((string)$nr_row['site_url']);
                        $nr_own = strpos($nr_own, '//') === false ? 'https://' . $nr_own : $nr_own;

                           if (preg_replace('/^www\./', '', strtolower((string)(parse_url($nr_own, PHP_URL_HOST) ?? ''))) === $nr_here) {

                            $nr_ref_host = nanoHost((string)($_SERVER['HTTP_REFERER'] ?? ''));
                            $nr_bot = (bool)preg_match('/bot|crawl|spider|slurp|bing|google/i', (string)($_SERVER['HTTP_USER_AGENT'] ?? ''));
                            $nr_flag = '';
                            if (NANOREASH_INTEGRITY && !$nr_bot && !nanoHostTrusted($nr_ref_host, $NANOREASH_TRUSTED_HOSTS)
                                && !(NANOREASH_SKIP_MEMBERS && !empty($_SESSION['USERID']))) {
                                $nr_flag = 'index.php?nr_rh=' . rawurlencode($nr_key)
                                         . '&nr_p=' . rawurlencode((string)parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH));
                            }
                            $nr_dest = rtrim($nr_own, '/') . '/' . $nr_flag;
                            break;
                        }
                    }
                    $nr_stmt->close();
                }
            }
            header('Location: ' . $nr_dest, true, (isset($nr_flag) && $nr_flag !== '') ? 302 : 301);
            exit;
        }
    }
}

$page_meta_tag = isset($data->page_meta_tag) ? $data->page_meta_tag : '';

include('.css/stylesheet.php');

$msg = isset($data->msg) ? $data->msg : '';

function getValidCompanies()
{
    return array(
        'new-appointment',
        'general-enquiry',
        'media-enquiry',
        'expression-of-interest',
        'registrations-membership',
        'absences',
        'reciprocal-link-exchange',
        'general-feedback',
        'feedback-tech',
        'feedback-complaint',
        'rfq-pickup',
        'rfq-delivery',
        'supported-brand-enquiry',
        'service-repair',
        'rego',
        'log-book-service',
        'tyre-puncture',
        'replace-tyres',
        'alignment-wheels',
        'require-second-opinion',
        'blue-slip',
        'pink-slip',
        'service-warranty',
        'service-outside-warranty',
        'brake-repairs',
        'suspension-related',
        'fuel-injection-related',
        'windscreen-related',
        'request-call-back',
        'request-quote',
        'proceed',
        's-admin-procedural',
        'agree-continue',
        'confirm-quote-proceed',
        'request-sales-order',
        'request-agent',
        'transfer-license',
        'partner-enquiry',
        'partner-onboarding',
        'partner-pricing',
        'admin-procedural',
        'partner-support'
    );
}

$stmtEarly = $dbh->prepare(
    "SELECT * FROM reash_general_setting WHERE id = ? LIMIT 1"
);
$rowEarly = null;
if ($stmtEarly) {
    $early_lang = (string)$_SESSION['LANG'];
    $stmtEarly->bind_param("s", $early_lang);
    $stmtEarly->execute();
    $earlyRes = $stmtEarly->get_result();
    if ($earlyRes) {
        $rowEarly = $earlyRes->fetch_object();
    }
    $stmtEarly->close();
}
if (!$rowEarly) {
    $rowEarly = new stdClass();
}

$max_faq         = isset($rowEarly->rows_per_page) ? $rowEarly->rows_per_page : 0;
$max_glossary    = 25;
$max_glossary_page = isset($rowEarly->rows_per_page) ? $rowEarly->rows_per_page : 0;
$max_downloads   = 30;

$SITE_EMAIL    = isset($rowEarly->site_email) ? stripslashes($rowEarly->site_email) : '';
$site_entrydate = (isset($site) && isset($site->site_entrydate)) ? $site->site_entrydate : '';
$ipadd         = $_SERVER['REMOTE_ADDR'];
$visit_date    = gmdate("d-m-Y");
$visit_day     = gmdate("l");
$visit_time    = gmdate("h:i A");

$stmtCheck = $dbh->prepare(
    "SELECT 1 FROM reash_visitors WHERE visit_date = ? AND ipadd = ? LIMIT 1"
);
$visitorExists = false;
if ($stmtCheck) {
    $stmtCheck->bind_param("ss", $visit_date, $ipadd);
    $stmtCheck->execute();
    $checkRes = $stmtCheck->get_result();
    if ($checkRes && $checkRes->num_rows > 0) {
        $visitorExists = true;
    }
    $stmtCheck->close();
}

if (!$visitorExists) {

    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? (string)$_SERVER['HTTP_USER_AGENT'] : '';
    if (strlen($ua) > 1024) {
        $ua = substr($ua, 0, 1024);
    }
    $stmtVisit = $dbh->prepare(
        "INSERT INTO reash_visitors
         (lang, ipadd, explorer, visit_date, visit_day, visit_time)
         VALUES (?, ?, ?, ?, ?, ?)"
    );
    if ($stmtVisit) {
        $langStr = (string)$lang;
        $stmtVisit->bind_param(
            "ssssss",
            $langStr, $ipadd, $ua, $visit_date, $visit_day, $visit_time
        );
        $stmtVisit->execute();
        $stmtVisit->close();
    }
}

/* HOST NORMALISATION */

function nanoHost($value)
{
    if (!is_string($value) || trim($value) === '') {
        return '';
    }

    $host = trim($value);

    if (strpos($host, '//') !== false) {
        $host = (string)parse_url($host, PHP_URL_HOST);
    }

    $host = strtolower(trim($host));
    $host = preg_replace('/:\d+$/', '', $host);
    $host = rtrim($host, '.');
    $host = trim($host, '[]');

    if (strpos($host, 'www.') === 0) {
        $host = substr($host, 4);
    }

    return $host;
}

function nanoHostTrusted($host, $trusted_list)
{
    if ($host === '') {
        return false;
    }

    foreach ($trusted_list as $trusted) {

        $trusted = nanoHost($trusted);

        if ($trusted === '') {
            continue;
        }

        if ($host === $trusted) {
            return true;
        }

        if (substr($host, -(strlen($trusted) + 1)) === '.' . $trusted) {
            return true;
        }
    }

    return false;
}

/* ABSOLUTE URL NORMALISER */

function nanoAbsoluteUrl($value, $fallback_scheme, $fallback_origin)
{
    $value = trim((string)$value);

    if ($value === '') {
        return $fallback_origin;
    }

    if (preg_match('#^https?://#i', $value)) {

        $parts = parse_url($value);

        if (
            is_array($parts) &&
            isset($parts['host']) &&
            $parts['host'] !== ''
        ) {
            return $value;
        }

        return $fallback_origin;
    }

    if (strpos($value, '//') === 0) {

        $parts = parse_url($value);

        if (
            is_array($parts) &&
            isset($parts['host']) &&
            $parts['host'] !== ''
        ) {
            return $fallback_scheme . ':' . $value;
        }

        return $fallback_origin;
    }

    if ($value !== '' && $value[0] === '/') {
        return rtrim($fallback_origin, '/') . $value;
    }

    if (preg_match(
        '#^(?:www\.)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:/.*)?$#i',
        $value
    )) {
        return $fallback_scheme . '://' . $value;
    }

    return $fallback_origin;
}

/* ROBOHELP NOTICE */

function nanoReashNotice($heading, $rows, $paras, $buttons, $footnote)
{
    $out = '
    <div id="footnoteModal"
         style="position:fixed;top:0;right:0;bottom:0;left:0;width:100%;height:100%;
                background:rgba(0,0,0,0.82);z-index:21474836472147483647;
                display:flex;align-items:center;justify-content:center;
                padding:20px;box-sizing:border-box;">

        <div style="width:100%;max-width:680px;background:#fff;color:#222;
                    padding:40px;box-sizing:border-box;border-radius:8px;
                    box-shadow:0 10px 50px rgba(0,0,0,0.55);
                    font-family:Arial,Helvetica,sans-serif;text-align:left;">

            <h2 style="margin:0 0 24px 0;font-size:26px;line-height:1.25;">
                ' . htmlspecialchars(
                    $heading,
                    ENT_QUOTES,
                    'UTF-8'
                ) . '
            </h2>';

  foreach ($rows as $label => $value) {

    $link = $value;
    $ref  = $value;

    $separator = (strpos($link, '?') !== false) ? '&' : '?';
    $href = $link . $separator . 'ref=' . urlencode($ref);

    $out .= '
        <p style="margin:0 0 16px 0;font-size:16px;
                  line-height:1.5;overflow-wrap:anywhere;">

            ' . htmlspecialchars(
                $label,
                ENT_QUOTES,
                'UTF-8'
            ) . ':<br>

            <strong>' . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . '</strong>

            <a href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '"
               class="icon-link"></a>

        </p>';
}

foreach ($paras as $para) {

    $out .= '
        <p style="margin:20px 0 0 0;font-size:16px;line-height:1.6;">
            ' . htmlspecialchars((string)$para, ENT_QUOTES, 'UTF-8') . '
        </p>';
}

if ($footnote !== '') {

    $out .= '
        <p style="margin:16px 0 0 0;font-size:14px;
                  line-height:1.5;color:#555;">

            ' . htmlspecialchars(
                $footnote,
                ENT_QUOTES,
                'UTF-8'
            ) . '

        </p>';
}

    $out .= '
            <div style="margin-top:30px;display:flex;
                        justify-content:flex-end;gap:10px;flex-wrap:wrap;">';

    foreach ($buttons as $button) {

        $button_id =
            isset($button['id'])
            ? $button['id']
            : '';

        $button_label =
            isset($button['label'])
            ? $button['label']
            : '';

        $button_url =
            isset($button['url'])
            ? $button['url']
            : '';

        if ($button_id === '' || $button_label === '') {
            continue;
        }

        if ($button_url !== '') {

            $out .= '
                <a
                    id="' . htmlspecialchars(
                        $button_id,
                        ENT_QUOTES,
                        'UTF-8'
                    ) . '"
                    class="button"
                    href="' . htmlspecialchars(
                        $button_url,
                        ENT_QUOTES,
                        'UTF-8'
                    ) . '"
                    style="display:inline-block;
                           padding:13px 24px;
                           border:0;
                           border-radius:5px;
                           cursor:pointer;
                           font-size:16px;
                           text-decoration:none;
                           box-sizing:border-box;">

                    ' . htmlspecialchars(
                        $button_label,
                        ENT_QUOTES,
                        'UTF-8'
                    ) . '

                </a>';

        } else {

            $back_url =
                isset($_SERVER['HTTP_REFERER']) &&
                trim($_SERVER['HTTP_REFERER']) !== ''
                ? trim($_SERVER['HTTP_REFERER'])
                : '/';

            $scheme = parse_url($back_url, PHP_URL_SCHEME);
            if ($scheme !== null && $scheme !== false && $scheme !== '') {
                $scheme = strtolower((string)$scheme);
                if ($scheme !== 'http' && $scheme !== 'https') {
                    $back_url = '/';
                }
            }

            $out .= '
                <a
                    id="' . htmlspecialchars(
                        $button_id,
                        ENT_QUOTES,
                        'UTF-8'
                    ) . '"
                    class="button"
                    href="' . htmlspecialchars(
                        $back_url,
                        ENT_QUOTES,
                        'UTF-8'
                    ) . '"
                    style="display:inline-block;
                           padding:13px 24px;
                           border:0;
                           border-radius:5px;
                           cursor:pointer;
                           font-size:16px;
                           text-decoration:none;
                           box-sizing:border-box;">

                    ' . htmlspecialchars(
                        $button_label,
                        ENT_QUOTES,
                        'UTF-8'
                    ) . '

                </a>';
        }
    }

    $out .= '
            </div>
        </div>
    </div>';

    return $out;
}

/* GENERAL SITE SETTINGS */

$stmtGeneral = $dbh->prepare(
    "SELECT * FROM reash_general_setting WHERE id = ? LIMIT 1"
);

$row = null;

if ($stmtGeneral) {

    $lang_string = (string)$_SESSION['LANG'];

    $stmtGeneral->bind_param(
        "s",
        $lang_string
    );

    $stmtGeneral->execute();

    $generalResult = $stmtGeneral->get_result();

    if ($generalResult) {
        $row = $generalResult->fetch_object();
    }

    $stmtGeneral->close();
}

if (!$row) {
    $row = new stdClass();
}

global
    $SITE_TITLE,
    $SITE_URL,
    $Meta_tag,
    $site_meta_tag,
    $site_meta_description;

$max_faq =
    isset($row->rows_per_page)
    ? $row->rows_per_page
    : 0;

$max_glossary = 25;

$max_glossary_page =
    isset($row->rows_per_page)
    ? $row->rows_per_page
    : 0;

$max_downloads = 30;

$SITE_EMAIL =
    isset($row->site_email)
    ? stripslashes($row->site_email)
    : '';

$site_entrydate =
    (isset($site) && isset($site->site_entrydate))
    ? $site->site_entrydate
    : '';

$_SESSION['SEARCH_WINDOW'] = 'ON';

if ($_SESSION['SEARCH_WINDOW'] === '') {
    $_SESSION['SEARCH_WINDOW'] = 'ON';
}

/* SITE VARIABLES */

$site_email =
    isset($row->site_email)
    ? stripslashes($row->site_email)
    : '';

$phone =
    isset($row->phone)
    ? stripslashes($row->phone)
    : '';

$fax =
    isset($row->fax)
    ? stripslashes($row->fax)
    : '';

$phone2 =
    isset($row->phone2)
    ? stripslashes($row->phone2)
    : '';

$site_location =
    isset($row->site_location)
    ? stripslashes($row->site_location)
    : '';

$site_title =
    isset($row->site_title)
    ? stripslashes($row->site_title)
    : '';

$site_url =
    isset($row->site_url)
    ? stripslashes($row->site_url)
    : '';

$rows_per_page =
    isset($row->rows_per_page)
    ? stripslashes($row->rows_per_page)
    : '';

$site_meta_description =
    isset($row->site_meta_description)
    ? stripslashes($row->site_meta_description)
    : '';

$site_meta_keyword =
    isset($row->site_meta_keyword)
    ? stripslashes($row->site_meta_keyword)
    : '';

$location =
    isset($row->location)
    ? stripslashes($row->location)
    : '';

$ext_site_email =
    isset($row->ext_site_email)
    ? stripslashes($row->ext_site_email)
    : '';

$SITE_URL =
    isset($row->site_url)
    ? stripslashes($row->site_url)
    : '';

/* POST VARIABLES */

$totalPages =
    isset($_POST['totalPages'])
    ? $_POST['totalPages']
    : '';

$pageNumber =
    isset($_POST['pageNumber'])
    ? $_POST['pageNumber']
    : 'Menu Position needs to be set';

$page_site_title =
    isset($_POST['page_site_title'])
    ? htmlspecialchars(
        $_POST['page_site_title'],
        ENT_QUOTES,
        'UTF-8'
    )
    : htmlspecialchars(
        $site_title,
        ENT_QUOTES,
        'UTF-8'
    );

$menuscript =
    isset($_POST['menuscript'])
    ? $_POST['menuscript']
    : '';

$title =
    isset($_POST['title'])
    ? $_POST['title']
    : '';

$heading =
    isset($_POST['heading'])
    ? $_POST['heading']
    : '';

$pagination =
    isset($_POST['pagination'])
    ? $_POST['pagination']
    : '';

$entrydate =
    isset($_POST['entrydate'])
    ? $_POST['entrydate']
    : '';

$MENUPOS =
    isset($_POST['MENUPOS'])
    ? $_POST['MENUPOS']
    : 'Menu Position needs to be set';

$Testimonial =
    isset($_POST['Testimonial'])
    ? $_POST['Testimonial']
    : '';

$meta_descripton =
    isset($_POST['meta_descripton'])
    ? $_POST['meta_descripton']
    : '';

$shop_name =
    isset($_POST['shop_name'])
    ? $_POST['shop_name']
    : '';

$chkout_url =
    isset($_POST['chkout_url'])
    ? $_POST['chkout_url']
    : '';

$meta_keyword =
    isset($_POST['site_meta_keyword']) && $_POST['site_meta_keyword'] !== ''
    ? $_POST['site_meta_keyword']
    : $site_meta_keyword;

$site_entrydate =
    isset($_POST['site_entrydate'])
    ? $_POST['site_entrydate']
    : '';

$meta_description =
    isset($_POST['meta_description']) && $_POST['meta_description'] !== ''
    ? $_POST['meta_description']
    : $site_meta_description;

$front_search_result =
    isset($_POST['front_search_result'])
    ? $_POST['front_search_result']
    : '';

$page_script =
    isset($_POST['page_script'])
    ? $_POST['page_script']
    : '';

$testimonial =
    isset($_POST['testimonial'])
    ? $_POST['testimonial']
    : '';

$url_page =
    isset($_POST['url_page'])
    ? $_POST['url_page']
    : '';

$keyword =
    isset($_POST['keyword'])
    ? $_POST['keyword']
    : '';

$meta_site_keyword =
    isset($_POST['site_meta_keyword'])
    ? $_POST['site_meta_keyword']
    : '';

$Quick_Search =
    isset($_POST['Quick_Search'])
    ? $_POST['Quick_Search']
    : '';

$page_title =
    isset($_POST['page_title'])
    ? $_POST['page_title']
    : '';

if (isset($_POST['page_site_title'])) {

    $page_title = $_POST['page_site_title'];

} else {

    $page_title =
        !empty($site_title)
        ? $site_title
        : 'Welcome to visit';
}

$page_title = htmlspecialchars((string)$page_title, ENT_QUOTES, 'UTF-8');

$page_no =
    isset($_POST['page_no'])
    ? $_POST['page_no']
    : '';

$desc =
    isset($_POST['desc'])
    ? $_POST['desc']
    : '';

$name =
    isset($_POST['name'])
    ? $_POST['name']
    : '';

$search_type =
    isset($_POST['search_type'])
    ? $_POST['search_type']
    : '';

$next_page =
    isset($_POST['next_page'])
    ? $_POST['next_page']
    : '';

/* CONFIG */

$id =
    isset($config['id'])
    ? $config['id']
    : '';

$back_image_path =
    isset($config['back_image_path'])
    ? $config['back_image_path']
    : '';

$page_promail =
    isset($config['page_promail'])
    ? $config['page_promail']
    : '';

$page_callnumber =
    isset($config['page_callnumber'])
    ? $config['page_callnumber']
    : '';

/* STYLESHEET */

$stmtStyle = $dbh->prepare(
    "SELECT * FROM reash_stylesheet WHERE lang = ? LIMIT 1"
);

$Style_data = null;

if ($stmtStyle) {

    $style_lang =
        (string)$_SESSION['LANG'];

    $stmtStyle->bind_param(
        "s",
        $style_lang
    );

    $stmtStyle->execute();

    $Style_res = $stmtStyle->get_result();

    if ($Style_res) {
        $Style_data = $Style_res->fetch_object();
    }

    $stmtStyle->close();
}

if ($Style_data) {

    $kintrodes = stripslashes($Style_data->kintrodes);
    $svgdes    = stripslashes($Style_data->svgdes);
    $svgkey    = stripslashes($Style_data->svgkey);
    $svgmnu    = stripslashes($Style_data->svgmnu);
    $svgli     = stripslashes($Style_data->svgli);
    $svgbul    = stripslashes($Style_data->svgbul);
    $svgload   = stripslashes($Style_data->svgload);
    $svgctc    = stripslashes($Style_data->svgctc);
    $svgmail   = stripslashes($Style_data->svgmail);
    $menunab   = stripslashes($Style_data->menunab);
    $menuopt   = stripslashes($Style_data->menuopt);

} else {

    $kintrodes =
    $svgdes =
    $svgkey =
    $svgmnu =
    $svgli =
    $svgbul =
    '';

    $svgload =
    $svgctc =
    $svgmail =
    $menunab =
    $menuopt =
    '';
}

/* LOGOUT */

$logout =
    isset($_GET['logout'])
    ? $_GET['logout']
    : null;

if ($logout !== null && isset($_SESSION['USERID'])) {

    session_unset();
    session_destroy();

    if (empty($show)) {

        echo '<script>
        window.location.href="../../#LogoutOK";
        </script>';

        exit();
    }
}

/* DETERMINE PAGE */

$show =
    isset($_GET['show'])
    ? $_GET['show']
    : 'index';

if (!is_string($show) || !preg_match('/^[A-Za-z0-9_-]+$/', $show)) {
    $show = 'index';
}

$page = $show . '.html';

$my_include_file = './.htinc/' . $show . '.inc';

$base_dir  = realpath('./.htinc');
$real_file = realpath($my_include_file);

if (
    $base_dir !== false &&
    $real_file !== false &&
    strpos($real_file, $base_dir . DIRECTORY_SEPARATOR) === 0
) {
    include($my_include_file);
}

$page_name =
    isset($data->name)
    ? $data->name
    : '...';

$id =
    filter_input(
        INPUT_GET,
        'id',
        FILTER_SANITIZE_NUMBER_INT
    );

if ($id === false || $id === null) {
    $id = '';
}

/* CALL FUNCTIONS */

$main_menu =
    $reash_functions->main_menu(
        $lang,
        $id,
        $SITE_URL
    );

$search_box =
    $reash_functions->search_box(
        $lang,
        $id,
        $SITE_URL
    );

$LOGO =
    $reash_functions->Get_Logo(
        $SITE_URL
    );

/* LOGIN FEEDBACK */

$ack =
    isset($_GET['ack'])
    ? intval($_GET['ack'])
    : 0;

$message = '';

if ($ack == 1) {

    $message =
        '[ LOGIN DISALLOWED ]<br>Your details are incorrect; either try again or contact us.';

} elseif ($ack == 2) {

    $message =
        '[ SESSION TIMEOUT ]<br>Please login to continue your session.';
}

if (!empty($message)) {
    echo $message;
}

/* Operator21 */
$_SESSION['o21_site'] = array('lang' => isset($lang) ? $lang : '', 'title' => isset($site_title) ? $site_title : '', 'url' => isset($site_url) ? $site_url : '', 'email' => isset($site_email) ? $site_email : (isset($email) ? $email : ''), 'symbol' => isset($svgkey) ? $svgkey : '');
error_log('o21 email: ' . $_SESSION['o21_site']['email']);

/* PAGE GENERATION */

$returned_page = '';

/* PAGE GENERATION */

$returned_page = '';

unset($gprc_m);

$returned_page =
    GSL_ParseHTML(
        $returned_page,
        $page
    );

$page_name =
    isset($page_name)
    ? $page_name
    : $show;

$GLOBALS['page_name'] = $page_name;

if (!isset($fu2)) {
    $fu2 = '';
}

$nanoreash_template_unsafe = false;

if (preg_match('/`|\$\{|[{]\$/', $returned_page)) {
    $nanoreash_template_unsafe = true;
}

$nanoreash_allow_unsafe = defined('NANOREASH_ALLOW_UNSAFE_EVAL')
    && NANOREASH_ALLOW_UNSAFE_EVAL;

if ($nanoreash_template_unsafe && !$nanoreash_allow_unsafe) {
    error_log(
        'NanoReash: refused to eval template containing unsafe interpolation '
        . 'for page "' . $show . '"'
    );

} else {
    $returned_page = preg_replace('/(?<!\\\\)"/', '\\"', $returned_page);
    eval("\$returned_page = \"$returned_page\";");
}

if ($nanoreash_m_was_present) {
    $_GET['m'] = $nanoreash_m_original;
}

/* NANOREASH INTERNAL LINK INTEGRITY */

$request_uri =
    isset($_SERVER['REQUEST_URI'])
    ? $_SERVER['REQUEST_URI']
    : '';

$is_https =
    (!empty($_SERVER['HTTPS']) &&
     strtolower($_SERVER['HTTPS']) !== 'off')
    ||
    (
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
        strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https'
    );

$here_scheme =
    $is_https
    ? 'https'
    : 'http';

$here_raw =
    isset($_SERVER['HTTP_HOST'])
    ? $_SERVER['HTTP_HOST']
    : '';

$here_host =
    nanoHost($here_raw);

$referer_raw =
    isset($_SERVER['HTTP_REFERER'])
    ? trim($_SERVER['HTTP_REFERER'])
    : '';

$referer_host =
    nanoHost($referer_raw);

$referer_scheme = '';

if ($referer_raw !== '') {

    $referer_scheme =
        strtolower(
            (string)parse_url(
                $referer_raw,
                PHP_URL_SCHEME
            )
        );

    if (
        $referer_scheme !== 'http' &&
        $referer_scheme !== 'https'
    ) {
        $referer_scheme = '';
    }
}

$origin_mismatch = false;

if (
    NANOREASH_INTEGRITY &&
    $here_host !== '' &&
    $referer_host !== '' &&
    $referer_scheme !== '' &&
    $referer_host !== $here_host &&
    !nanoHostTrusted(
        $referer_host,
        $NANOREASH_TRUSTED_HOSTS
    )
) {
    $origin_mismatch = true;
}

if (
    $origin_mismatch &&
    NANOREASH_SKIP_MEMBERS &&
    !empty($_SESSION['USERID'])
) {
    $origin_mismatch = false;
}

if (
    $origin_mismatch &&
    NANOREASH_ONCE_PER_SESSION
) {

    if (
        !isset($_SESSION['nr_seen']) ||
        !is_array($_SESSION['nr_seen'])
    ) {
        $_SESSION['nr_seen'] = array();
    }

    if (
        isset(
            $_SESSION['nr_seen'][$referer_host]
        )
    ) {

        $origin_mismatch = false;

    } else {

        $_SESSION['nr_seen'][$referer_host] = 1;
    }
}

/* OUTPUT PAGE */

echo $returned_page;

/* REFERRAL RECORDING */

$actual_http_referer =
    isset($_SERVER['HTTP_REFERER']) &&
    is_string($_SERVER['HTTP_REFERER'])
    ? trim((string)$_SERVER['HTTP_REFERER'])
    : '';

$referral_value =
    isset($gprc_ref) &&
    is_scalar($gprc_ref)
    ? trim((string)$gprc_ref)
    : '';

if (strlen($actual_http_referer) > 8192) {
    $actual_http_referer = '';
}

if (strlen($referral_value) > 8192) {
    $referral_value = '';
}

if ($referral_value !== '' || $actual_http_referer !== '') {

    $Today = date('Y-m-d');
    $Time  = date('H:i:s');

    $user_agent =
        isset($_SERVER['HTTP_USER_AGENT']) &&
        is_string($_SERVER['HTTP_USER_AGENT'])
        ? $_SERVER['HTTP_USER_AGENT']
        : '';

    $ip_address =
        isset($_SERVER['REMOTE_ADDR']) &&
        is_string($_SERVER['REMOTE_ADDR'])
        ? $_SERVER['REMOTE_ADDR']
        : '';

    $stored_referral_url =
        $actual_http_referer !== ''
        ? $actual_http_referer
        : $request_uri;

    $stored_refid = $referral_value;

    $stmtReferral = $dbh->prepare(
        "INSERT INTO reash_refers
        (`lang`, `refid`, `date`, `time`, `browser`,
         `ipaddress`, `refferalurl`, `buy`)
        VALUES (?, ?, ?, ?, ?, ?, ?, '0')"
    );

    if ($stmtReferral) {

        $ref_lang =
            (string)$_SESSION['LANG'];

        $stmtReferral->bind_param(
            "sssssss",
            $ref_lang,
            $stored_refid,
            $Today,
            $Time,
            $user_agent,
            $ip_address,
            $stored_referral_url
        );

        $stmtReferral->execute();
        $stmtReferral->close();
    }
}

/* ROBOHELP */

if ($origin_mismatch) {

    $nanolink_path =
        parse_url(
            $request_uri,
            PHP_URL_PATH
        );

    if (!is_string($nanolink_path)) {
        $nanolink_path = '';
    }

    $nanolink_url =
        $here_scheme .
        '://' .
        $here_raw .
        $nanolink_path;

    $referer_origin =
        $referer_scheme .
        '://' .
        $referer_host;

    $here_origin =
        $here_scheme .
        '://' .
        $here_raw;

    $registered_url =
        nanoAbsoluteUrl(
            $SITE_URL,
            $here_scheme,
            $here_origin
        );

echo nanoReashNotice(

    '⚠ RoboHelp Warning',

    array(

        'Registered NanoLink (Intended)' =>
            $nanolink_url,

        'NanoLink displayed on' =>
            $referer_origin,

        'Nanolink is registered to' =>
            $here_origin
    ),

    array(

        'This link does not appear to belong on this website and may
         have been incorrectly placed or manipulated.'
    ),

    array(),

    'NanoReash has recorded this event for security analysis.'
);

}

if (!$origin_mismatch && isset($_GET['nr_rh'], $_GET['nr_p']) && is_string($_GET['nr_rh']) && is_string($_GET['nr_p'])
    && preg_match('/^[0-9]{1,10}$/', $_GET['nr_rh']) && preg_match('#^/[A-Za-z0-9/_().-]{0,200}$#', $_GET['nr_p'])
    && !(NANOREASH_SKIP_MEMBERS && !empty($_SESSION['USERID']))) {

    $nr_owner = '';
    $nr_stmt  = $dbh->prepare("SELECT site_url FROM reash_general_setting WHERE id = ? LIMIT 1");
    if ($nr_stmt) {
        $nr_id = $_GET['nr_rh'];
        $nr_stmt->bind_param("s", $nr_id);
        $nr_stmt->execute();
        $nr_res = $nr_stmt->get_result();
        if ($nr_res && ($nr_row = $nr_res->fetch_assoc())) {
            $nr_owner = trim((string)$nr_row['site_url']);
            $nr_owner = $nr_owner === '' ? '' : rtrim(strpos($nr_owner, '//') === false ? 'https://' . $nr_owner : $nr_owner, '/');
        }
        $nr_stmt->close();
    }

    if ($nr_owner !== '' && nanoHost($nr_owner) !== nanoHost($here_raw)) {
        echo str_replace('id="footnoteModal"', 'id="nrRoboHelp"', nanoReashNotice(
            '⚠ RoboHelp Warning',
            array(
                'Registered NanoLink (Intended)' => $nr_owner . $_GET['nr_p'],
                'NanoLink displayed on'          => $here_scheme . '://' . $here_raw,
                'Nanolink is registered to'      => $nr_owner
            ),
            array(
                'This link does not appear to belong on this website and may
         have been incorrectly placed or manipulated.'
            ),
            array(),
            'NanoReash has recorded this event for security analysis.'
        ));

        echo '<script>try{history.replaceState(null,"","/");}catch(e){}window.addEventListener("load",function(){var m=document.getElementById("nrRoboHelp");if(m){m.style.zIndex="2147483647";document.body.appendChild(m);}});</script>';
    }
}

?>
<script>

var nav4 = window.Event ? true : false;

var isIE = document.all;
var isNN = !document.all && document.getElementById;
var isN4 = document.layers;

var isHot = false;
var ddEnabled = false;

var topDog = null;
var whichDog = null;
var hotDog = null;

var offsetx = 0;
var offsety = 0;

var nowX = 0;
var nowY = 0;

function ddInit(e) {

    e = e || window.event;

    topDog = isIE ? 'BODY' : 'HTML';

    whichDog =
        isIE
        ? document.all.theLayer
        : document.getElementById('theLayer');

    hotDog =
        isIE
        ? e.srcElement
        : e.target;

    while (
        hotDog &&
        hotDog.id != 'titleBar' &&
        hotDog.tagName != topDog
    ) {

        hotDog =
            isIE
            ? hotDog.parentElement
            : hotDog.parentNode;
    }

    if (
        hotDog &&
        hotDog.id == 'titleBar'
    ) {

        offsetx = e.clientX;
        offsety = e.clientY;

        if (whichDog) {

            nowX =
                parseInt(
                    whichDog.style.left
                ) || 0;

            nowY =
                parseInt(
                    whichDog.style.top
                ) || 0;

            ddEnabled = true;

            document.onmousemove = dd;
        }
    }
}

function dd(e) {

    e = e || window.event;

    if (!ddEnabled) {
        return;
    }

    if (!whichDog) {
        return;
    }

    whichDog.style.left =
        nowX + e.clientX - offsetx;

    whichDog.style.top =
        nowY + e.clientY - offsety;

    return false;
}

function ddN4(whatDog) {

    if (!isN4) {
        return;
    }

    N4 = eval(whatDog);

    N4.captureEvents(
        Event.MOUSEDOWN | Event.MOUSEUP
    );

    N4.onmousedown = function (e) {

        N4.captureEvents(
            Event.MOUSEMOVE
        );

        N4x = e.x;
        N4y = e.y;
    };

    N4.onmousemove = function (e) {

        if (isHot) {

            N4.moveBy(
                e.x - N4x,
                e.y - N4y
            );

            return false;
        }
    };

    N4.onmouseup = function () {

        N4.releaseEvents(
            Event.MOUSEMOVE
        );
    };
}

function hideMe() {

    var site_url =
        '<?php echo htmlspecialchars(
            $SITE_URL,
            ENT_QUOTES,
            'UTF-8'
        ); ?>';

    window.open(
        site_url + '/close_search.php',
        'mywindow',
        'width=1,height=1,left=1200,top=800'
    );

    if (
        (isIE || isNN) &&
        whichDog
    ) {

        whichDog.style.display = 'none';

    } else if (isN4) {

        document.theLayer.display = 'none';
    }
}

function showMe() {

    if (
        (isIE || isNN) &&
        whichDog
    ) {

        whichDog.style.visibility = 'visible';

    } else if (isN4) {

        document.theLayer.visibility = 'show';
    }
}

document.onmousedown = ddInit;

document.onmouseup = function () {

    ddEnabled = false;
    document.onmousemove = null;
};

</script>

<?php

$site_host = parse_url($SITE_URL, PHP_URL_HOST);
?>
<script>
  (function () {
    var currentHost = window.location.hostname;
    var targetHost  = <?php echo json_encode((string)$site_host, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;

    var normalize = function (h) { return h.replace(/^www\./, ''); };

    if (normalize(currentHost) !== normalize(targetHost)) {
      window.location.replace(
        <?php echo json_encode(rtrim($SITE_URL, "/"), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?> +
        window.location.pathname +
        window.location.search
      );
    }
  })();
</script>

<?php

require_once 'footer.php';
?>