<?php
session_start();
//powered by link
$array['poweredBy'] = '<span>site managed by <a href="https://www.freesites.com.au" target="_blank" title="freesites.com.au">freesites</a></span>';
$array['copyright'] = '&copy;';
//check if account is suspended, if so, show msg
if (file_exists('index.htm'))
{
    include 'index.htm';
    exit;
    die();
}
//classes
require_once 'class/mysql.php';
require_once 'functions.php';
require_once fileInclude('class/form_validation.php');
require_once fileInclude('class/site.php');
require_once fileInclude('class/page.php');
//path for images etc
$array['PATH'] = '/';
//fetch user's template and styler settings
$settings = settings('template,style,header,footer,folder,keywords,meta_desc,company_name,logo_width,coming_soon,share_buttons_on_all_pages');
$tagLineContent = strip_tags(stripslashes($settings['header']));
//if comming soon page setting is active
if (isset($_GET['viewMode']))
{
    setcookie('viewMode', 'y', strtotime("+24 hours"), '/');
    header("Location: /");exit;}
if ($settings['coming_soon'] == 'y' && $_COOKIE['viewMode'] != 'y')
{
    die('<html><head><title>Website coming soon</title><style>html {margin: 0; padding: 0; height: 100%;} body {margin: 0; padding: 0; height: 100%; background-color: #E5E5E5;}</style></head><body><table width="100%" border="0" cellspacing="0" cellpadding="0" style="height: 80%;"><tr><th><a href="https://www.freesites.com.au"><img src="//www.freesites.com.au/images/coming-soon/coming-soon.gif" title="This website is coming soon, Please check back later. If this is your site and you\'re ready to set it live, you can do so via the settings page in your site management area. www.freesites.com.au" border="0" /></a></th></tr></table></body></html>');exit;}
//load page headet/footer vars
$array['head_code'] = '';
$array['header_msg'] = nl2br(stripslashes($settings['header']));
$settings['footer'] = $settings['footer'];
$array['footer'] = nl2br(stripslashes($settings['footer']));
$array['company_name'] = stripslashes($settings['company_name']);
$array['company_name_text'] = $array['company_name'];
$array['template'] = $array['template'];
//share buttons on all pages
$shareButtonsHtml = '';
if ($settings['share_buttons_on_all_pages'] == 'y')
{
    $shareButtonsHtml = '<div class="addthis_toolbox addthis_default_style" style="padding-top:10px;height:60px;clear:left;"><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_button_google_plusone" g:plusone:size="medium"></a><a class="addthis_counter addthis_pill_style"></a></div><script type="text/javascript" src="//s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4fc4fffc7c830cd2"></script>';
}
$logoAsFavIcon = '';
//if user uploaded an image, use image
if (file_exists('images/logo/logo.jpg'))
{
    $logowidth = ($settings['logo_width'] != '') ? ' width="'.$settings['logo_width'].'"' : '';
    $array['company_name'] = '<img src="'.$array['PATH'].'images/logo/logo.jpg?'.filemtime('images/logo/logo.jpg').'" alt="'.$setings['meta_desc'].'"'.$logowidth.' />';
    $logoAsFavIcon = '<link rel="icon" href="'.$array['PATH'].'images/logo/logo.jpg?'.filemtime('images/logo/logo.jpg').'" sizes="16x16" type="image/jpg" />';
}
if (file_exists('images/logo/logo.jpeg'))
{
    $logowidth = ($settings['logo_width'] != '') ? ' width="'.$settings['logo_width'].'"' : '';
    $array['company_name'] = '<img src="'.$array['PATH'].'images/logo/logo.jpeg?'.filemtime('images/logo/logo.jpeg').'" alt="'.$setings['meta_desc'].'"'.$logowidth.' />';
    $logoAsFavIcon = '<link rel="icon" href="'.$array['PATH'].'images/logo/logo.jpeg?'.filemtime('images/logo/logo.jpeg').'" sizes="16x16" type="image/jpeg" />';
}
if (file_exists('images/logo/logo.gif'))
{
    $logowidth = ($settings['logo_width'] != '') ? ' width="'.$settings['logo_width'].'"' : '';
    $array['company_name'] = '<img src="'.$array['PATH'].'images/logo/logo.gif?'.filemtime('images/logo/logo.gif').'" alt="'.$setings['meta_desc'].'"'.$logowidth.' />';
    $logoAsFavIcon = '<link rel="icon" href="'.$array['PATH'].'images/logo/logo.gif?'.filemtime('images/logo/logo.gif').'" sizes="16x16" type="image/gif" />';
}
if (file_exists('images/logo/logo.png'))
{
    $logowidth = ($settings['logo_width'] != '') ? ' width="'.$settings['logo_width'].'"' : '';
    $array['company_name'] = '<img src="'.$array['PATH'].'images/logo/logo.png?'.filemtime('images/logo/logo.png').'" alt="'.$setings['meta_desc'].'"'.$logowidth.' />';
    $logoAsFavIcon = '<link rel="icon" href="'.$array['PATH'].'images/logo/logo.png?'.filemtime('images/logo/logo.png').'" sizes="16x16" type="image/png" />';
}
/*Appearance*/
$appearanceCSS = '';
$table_check = $mysql->num_rows($mysql->do_query("show tables LIKE '%fs_appearance%'"));
if ($table_check == 1)
{
    $appearanceCSS = '<style type="text/css">';
//body
    $appearanceCSS .= 'body,p,div{';
    $body_colour = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'body_colour' LIMIT 1"));
    if (!empty($body_colour['value']))
    {
        $appearanceCSS .= 'color:#'.$body_colour['value'].';';
    }
    $body_font = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'body_font' LIMIT 1"));
    if (!empty($body_font['value']))
    {
        $appearanceCSS .= 'font-family:'.html_entity_decode($body_font['value']).';';
    }
    $body_size = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'body_size' LIMIT 1"));
    if (!empty($body_size['value']))
    {
        $appearanceCSS .= 'font-size:'.$body_size['value'].';';
    }
    $appearanceCSS .= '}';
    //h1
    $appearanceCSS .= 'h1, #header h1, #content h1{';
    $h1_colour = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'h1_colour' LIMIT 1"));
    if (!empty($h1_colour['value']))
    {
        $appearanceCSS .= 'color:#'.$h1_colour['value'].';';
    }
    $h1_font = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'h1_font' LIMIT 1"));
    if (!empty($h1_font['value']))
    {
        $appearanceCSS .= 'font-family:'.html_entity_decode($h1_font['value']).';';
    }
    $h1_size = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'h1_size' LIMIT 1"));
    if (!empty($h1_size['value']))
    {
        $appearanceCSS .= 'font-size:'.$h1_size['value'].';';
    }
    $appearanceCSS .= '}';
    //compnany name
    $appearanceCSS .= ' #header #logo{';
    $company_name_colour = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'company_name_colour' LIMIT 1"));
    if (!empty($company_name_colour['value']))
    {
        $appearanceCSS .= 'color:#'.$company_name_colour['value'].';';
    }
    $company_name_font = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'company_name_font' LIMIT 1"));
    if (!empty($company_name_font['value']))
    {
        $appearanceCSS .= 'font-family:'.html_entity_decode($company_name_font['value']).';';
    }
    $company_name_size = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'company_name_size' LIMIT 1"));
    if (!empty($company_name_size['value']))
    {
        $appearanceCSS .= 'font-size:'.$company_name_size['value'].';';
    }
    $appearanceCSS .= '}';
    //h2
    $appearanceCSS .= 'h2, #header #tagline, #header h2, #header, #header h3{';
    $h2_colour = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'h2_colour' LIMIT 1"));
    if (!empty($h2_colour['value']))
    {
        $appearanceCSS .= 'color:#'.$h2_colour['value'].';';
    }
    $h2_font = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'h2_font' LIMIT 1"));
    if (!empty($h2_font['value']))
    {
        $appearanceCSS .= 'font-family:'.html_entity_decode($h2_font['value']).';';
    }
    $h2_size = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'h2_size' LIMIT 1"));
    if (!empty($h2_size['value']))
    {
        $appearanceCSS .= 'font-size:'.$h2_size['value'].';';
    }
    $appearanceCSS .= '}';
    //link_colour
    $link_colour = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'link_colour' LIMIT 1"));
    if (!empty($link_colour['value']))
    {
        $appearanceCSS .= 'a,a:visited{color:#'.$link_colour['value'].';}';
    }
    //hover_link_colour
    $hover_link_colour = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'hover_link_colour' LIMIT 1"));
    if (!empty($hover_link_colour['value']))
    {
        $appearanceCSS .= 'a:hover{color:#'.$hover_link_colour['value'].';}';
    }
    //background image
    $s = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'show_background_tab' LIMIT 1"));
    if ($s['value'] == 'y')
    {
        $bgcss = '';
        $s = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'background_color' LIMIT 1"));
        if ($s['value'] != '')
        {
            $bgcss .= "background-color:#{$s['value']};";}
        $s = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'background_image' LIMIT 1"));
        if ($s['value'] != '')
        {
            $bgcss .= "background-image:url('/images/{$s['value']}');";}
        $s = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'background_position' LIMIT 1"));
        if ($s['value'] != '')
        {
            list($b1, $b2) = explode("|", $s['value']);
            $bgcss .= "background-position:$b2 $b1;";}
        $s = $mysql->get_array($mysql->query("value", "fs_appearance", "setting = 'background_tile' LIMIT 1"));
        if ($s['value'] != '')
        {
            $bgcss .= "background-repeat:{$s['value']};";}
        if (!empty($bgcss))
        {
            $appearanceCSS .= "body{".$bgcss."}";}
    }
    //appearance end
    $appearanceCSS .= '</style>';
}
//load tempalte
$head = ['</head>', '</HEAD>'];
$head_replace = $array['head_code'].$appearanceCSS."</head>";
$mainhtml = str_replace($head, $head_replace, $page->get_temp('templates/'.$settings['template'].'/index.htm'));
$mainhtml = str_replace('/index/{id};{pagename}/', '/{id}/{pagenamelink}/', $mainhtml);
//load the style sheet
$settings['style'] = (file_exists('templates/'.$settings['template'].'/layout.css')) ? 'layout' : $settings['style'];
$array['style'] = $array['PATH'].'templates/'.$settings['template'].'/'.$settings['style'];
//load page links
$Ribbonette_Rainbow = 1;
$Enfantine = 1;
$shop_page = array_merge(settings('shop_page'), $site->shop_settings('show_bestsellers_page,show_newarrivals_page,show_categories_sublinks,show_shopsearch_page,show_all_products_link,subcats_as_links'));
$linkhtml = explode('<!--pagelink-->', $mainhtml);
$mainhtml = $linkhtml[0];
$mobileMenuLinks = [];
$query = $mysql->query("ID,title,url", $mysql->perfix."pages", "status = 'Publish' AND ID != 2 AND sub = 0 AND hide_link = 'n' ORDER BY `order` ASC");
$z = 0;
while ($links = $mysql->get_array($query))
{
    $linkhml = $linkhtml[1];
    //Ribbonette_Rainbow li class, 6 colours in total
    if ($settings['template'] == 'Ribbonette_Rainbow')
    {
        $linkhml = str_replace('<li>', '<li class="nav-style'.$Ribbonette_Rainbow.'">', $linkhml);
        if ($Ribbonette_Rainbow == 6)
        {
            $Ribbonette_Rainbow = 0;
        }
        $Ribbonette_Rainbow++;
    }
    //Enfantine li class, 4 colours in total
    if ($settings['template'] == 'Enfantine')
    {
        $linkhml = str_replace('<li>', '<li class="nav-style'.$Enfantine.'">', $linkhml);
        if ($Enfantine == 4)
        {
            $Enfantine = 0;
        }
        $Enfantine++;
    }
    //add firstLink class to first item of the menu
    if ($z == 0)
    {
        $linkhml = (strstr($linkhml, 'class="')) ? str_replace('class="', 'class="firstLink ', $linkhml) : str_replace('<li', '<li class="firstLink"', $linkhml);
    }
    $z++;
    //page links
    $links_html .= str_replace('<li', '<li id="link'.$links['ID'].'"', $linkhml);
    $links_html = str_replace("/{id}/{pagenamelink}/", "/{id}/{pagenamelink}", $links_html);
    $links_html = str_replace('{pagename}', $links['title'], $links_html);
    $links_html = str_replace('{pagenamelink}', seo_str($links['title']), $links_html);
    $links_html = str_replace('{id}', $links['ID'], $links_html);
    $mobileMenuLinks['p'.$links['ID']] = ['/'.$links['ID'].'/'.seo_str($links['title']) => $links['title']];
    //sub pages
    $subsq = $mysql->query("ID,title,url", $mysql->perfix."pages", "status = 'Publish' AND sub = {$links['ID']} AND hide_link = 'n' ORDER BY `order` ASC");
    $anypages = $mysql->num_rows($subsq);
    if ($anypages > 0 || $links['ID'] == $shop_page['shop_page'])
    {
        $links_html = substr($links_html, 0, -5);
        $isPIDSubOfCurrent = $mysql->num_rows($mysql->query("ID", $mysql->perfix."pages", "ID = ".(int) $_GET['pid']." AND sub = {$links['ID']} LIMIT 1"));
        $subClass = ($_GET['pid'] == $links['ID'] || $isPIDSubOfCurrent == 1) ? 'menuSubActive' : 'menuSubNormal';
        $links_html .= '<div class="'.$subClass.'">';
        $mobileMenuLinks[$links['ID']][] = [];
        while ($subsdata = $mysql->get_array($subsq))
        {
            $links_html .= '<a href="/'.$subsdata['ID'].'/'.seo_str($subsdata['title']).'">'.stripslashes($subsdata['title']).'</a><br />';
            $mobileMenuLinks[$links['ID']][] = ['/'.$subsdata['ID'].'/'.seo_str($subsdata['title']) => stripslashes($subsdata['title'])];
        }
        //if parent page is a shop page, show shop related links as subpages
        if ($links['ID'] == $shop_page['shop_page'])
        {
            //new arrivals link
            if ($shop_page['show_newarrivals_page'] == 'y')
            {
                $links_html .= '<a class="shopParentCat" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/New-Arrivals">New arrivals</a><br />';
                $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/New-Arrivals' => 'New arrivals', 'padding' => true];
            }
            //best sellers link
            if ($shop_page['show_bestsellers_page'] == 'y')
            {
                $links_html .= '<a class="shopParentCat" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/Best-Sellers">Best sellers</a><br />';
                $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/Best-Sellers' => 'Best sellers', 'padding' => true];
            }
            //categories as sublinks
            if ($shop_page['show_categories_sublinks'] == 'y')
            {
                $catssubquery = $mysql->query("ID,name,url_key", "fs_shop_cats", "sub = 0 AND `live` = 'y' ORDER BY `order` ASC");
                while ($catsublinks = $mysql->get_array($catssubquery))
                {
                    $catssubquerysub = $mysql->query("name,url_key", "fs_shop_cats", "sub = {$catsublinks['ID']} AND `live` = 'y' ORDER BY `order` ASC");
                    $numSubs = $mysql->num_rows($catssubquerysub);
                    $shopcatisparent = ($numSubs > 0) ? ' hasSubCats' : '';
                    $links_html .= '<a class="shopParentCat'.$shopcatisparent.'" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/'.$catsublinks['url_key'].'">'.stripslashes($catsublinks['name']).'</a>';
                    $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/'.$catsublinks['url_key'] => stripslashes($catsublinks['name']), 'padding' => true];
                    //cat subs are links
                    if ($shop_page['subcats_as_links'] == 'y' && $numSubs > 0)
                    {
                        while ($catsublinkssub = $mysql->get_array($catssubquerysub))
                        {
                            $links_html .= '<a class="shopSubCat" style="margin-left:10px;" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/'.$catsublinkssub['url_key'].'">'.stripslashes($catsublinkssub['name']).'</a><br />';
                            $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/'.$catsublinkssub['url_key'] => stripslashes($catsublinkssub['name']), 'padding' => true];
                        }
                    }
                    $links_html .= '<br />';
                }
            }
            //search shop link
            if ($shop_page['show_shopsearch_page'] == 'y')
            {
                $links_html .= '<a class="shopParentCat" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/Search">Search shop</a><br />';
                $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/Search' => 'Search shop', 'padding' => true];
            }
            //all products page link
            if ($shop_page['show_all_products_link'] == 'y')
            {
                $links_html .= '<a class="shopParentCat" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/AllProducts">View all products</a><br />';
                $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/AllProducts' => 'View all products', 'padding' => true];
            }
            //basket link
            $links_html .= '<a class="shopParentCat basketLink" href="/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/Basket" style="font-weight:bold">Your shopping basket</a><br />';
            $mobileMenuLinks[$shop_page['shop_page']][] = ['/'.$shop_page['shop_page'].'/'.seo_str($links['title']).'/Basket' => 'Your shopping basket', 'padding' => true];
            //desktop currency converter
            $converter = $mysql->get_array($mysql->query("value", "fs_settings", "`name` = 'currency_converter' LIMIT 1"));
            if ($converter['value'] == 'y')
            {
                $h = '<a href="#" onclick="selectCurrency(\'AUD\');return false;" class="shopSubCat" style="margin-left:10px;">$ AUD</a><br />
				<a href="#" onclick="selectCurrency(\'NZD\');return false;" class="shopSubCat" style="margin-left:10px;">$ NZD</a><br />
				<a href="#" onclick="selectCurrency(\'HKD\');return false;" class="shopSubCat" style="margin-left:10px;">$ HKD</a><br />
				<a href="#" onclick="selectCurrency(\'USD\');return false;" class="shopSubCat" style="margin-left:10px;">$ USD</a><br />
				<a href="#" onclick="selectCurrency(\'GBP\');return false;" class="shopSubCat" style="margin-left:10px;">&pound; GBP</a><br />
				<a href="#" onclick="selectCurrency(\'EUR\');return false;" class="shopSubCat" style="margin-left:10px;">&euro; EUR</a>';
                $links_html .= '<a href="#" onclick="return false;" class="shopParentCat currencyLink"><strong>Change currency</strong></a>'.$h.'<br>';
            }
        }
        $links_html .= '</div>';
        $links_html .= '</li>';
    }
}
$mainhtml .= $links_html.$linkhtml[2];
//if current link is one being displayed, put a class on it
$mainhtml = str_replace('<li id="link'.$_GET['pid'].'"', '<li id="parentActive"', $mainhtml);
$parentId = $mysql->query("sub", "fs_pages", "ID = ".(int) $_GET['pid']." AND sub > 0 LIMIT 1");
if ($mysql->num_rows($parentId) == 1)
{
    $parentId = $mysql->get_array($parentId);
    $mainhtml = str_replace('<li id="link'.$parentId['sub'].'"', '<li id="parentActive"', $mainhtml);
}
//if the homepage is being disabled, make the menu li active
if ($_GET['pid'] == 1 || $_GET['pid'] == 0)
{
    $mainhtml = str_replace('<li id="link1"', '<li id="parentActive"', $mainhtml);
}
//get the vars from GET
$url = explode("/", $_SERVER['REQUEST_URI']);
$url['page'] = $url[3];
$url['pid'] = (int) $url[2];
//load page content
if ($url['pid'] == 0)
{
    $url['pid'] = 1;}
$url['pid'] = (isset($_GET['pid'])) ? (int) $_GET['pid'] : $url['pid'];
$pubSQL = ($_COOKIE['viewMode'] == 'y' || isset($_GET['junk'])) ? '' : "AND status = 'Publish'";
$pubSQL = ($url['pid'] == 2) ? '' : $pubSQL;
$query = $mysql->query("ID,title,content,seotitle,seokeywords,seodesc,password,meta_tags,url", $mysql->perfix."pages", "ID = {$url['pid']} $pubSQL LIMIT 1");
if ($mysql->num_rows($query) == 0)
{
    header("location: ".httpOrHttps()."://".$_SERVER['HTTP_HOST']."/2/Error");
    exit;
}
$content = $mysql->get_array($query);
//if page has a redirect URL, redirect to it
if (!empty($content['url']))
{
    header("location: ".$content['url']);
    exit;
}
//seo title
$mainhtml = str_replace(' - {company_name_text} - {keywords}', '', $mainhtml);
$array['page_title'] = (!empty($content['seotitle'])) ? stripslashes($content['seotitle']) : stripslashes($content['title']).' - '.stripslashes($array['company_name_text']).' - '.stripslashes($settings['keywords']);
//seo keywords
$array['keywords'] = (!empty($content['seokeywords'])) ? stripslashes($content['seokeywords']) : stripslashes($settings['keywords']);
//seo desc
$array['meta_desc'] = (!empty($content['seodesc'])) ? stripslashes($content['seodesc']) : stripslashes($settings['meta_desc']);
//add google fonts meta tag in header
if (!strstr($mainhtml, '/jquery/'))
{
    $mainhtml = str_replace("</head>", '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script></head>', $mainhtml);
}
$mainhtml = str_replace("</head>", '<script src="//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js" type="text/javascript"></script><script src="//www.freesites.com.au/src/LiveEditor1.7.3/scripts/common/webfont.js" type="text/javascript"></script></head>', $mainhtml);
//if the site has a blog, include the RSS meta tag
$b = settings('blog_page,company_name');
if ((int) $b['blog_page'] > 0)
{
    $mainhtml = str_replace("</head>", '<link rel="alternate" type="application/atom+xml" title="Blog Posts from '.$b['company_name'].'" href="'.httpOrHttps().'://'.$_SERVER['HTTP_HOST'].'/inc/blog/blog.xml" /></head>', $mainhtml);
}
//if page has any meta_tags, inject it
if (!empty($content['meta_tags']))
{
    $mainhtml = str_replace("</head>", stripslashes($content['meta_tags']).'</head>', $mainhtml);
}
//show the mobile menu link just above content div
$mainhtml = str_replace('<div id="content">', '<a href="#my-menu" class="ShowForMobile mobileNavToggle"><span>Menu</span></a><div id="content">', $mainhtml);
//load the content into right spot on the template
$con = explode('<!--content-->', $mainhtml);
$mainhtml = str_replace("<h1>{page_title}</h1>", "", $con[0]);
$content['content'] = str_replace(['//<![CDATA[', '//]]>'], "", $content['content']); //remove javascript comments from javascript so it can run
//if the page is in one of the add-on pages, dont show the content of the page it self, replace it with the add-on content
$mainhtml .= '<!--tc-->';
$addon = [];
$b = settings('blog_page,shop_page');
$addon[] = $b['blog_page'];
$addon[] = $b['shop_page'];
if (!in_array($url['pid'], $addon))
{
    $mainhtml .= stripslashes($content['content']);
}
//include the inc folder files
$fp = opendir('inc/');
while ($files = readdir($fp))
{
    if ($files != "." && $files != ".." && $files != ".htaccess" && $files != ".DS_Store" && $files != "z_passwordpages" && $files != "slideshow" && $files != "poll" && $files != "form")
    {
        if (file_exists("inc/$files/index.php"))
        {
            include fileInclude("inc/$files/index.php");
        }
    }
}
$mainhtml .= '<!--tc-->';
//include these add-ons n their own since they work with the page content, such as replacnig user placed tags
include fileInclude("inc/slideshow/index.php");
include fileInclude("inc/poll/index.php");
include fileInclude("inc/form/index.php");
//put the password pages addon as the last include
include fileInclude("inc/z_passwordpages/index.php");
$page->page = $mainhtml.$shareButtonsHtml.$con[1];
//if 404 error page is being displayed, fix the home link
if ($url['pid'] == 2)
{
    $page->page = str_replace('/index/1/Home', "/", $page->page);
}
$page->replace_tags($array);
//see if any functions are being called by the page html
preg_match_all("(\{(.+?)\})", $page->page, $functions);
if (is_array($functions[1]))
{
    foreach ($functions[1] as $key => $call)
    {
        if (method_exists($site, $call))
        {
            $array[$call] = call_user_func([$site, $call]);
        }
    }
    $page->replace_tags($array);
}
//add a message to the content when user is viewing the site with videMode cookie
if ($settings['coming_soon'] == 'y' && $_COOKIE['viewMode'] == 'y')
{
    $m = '<div style="background-color:#CE0000;padding:15px;color:#ffffff;" align="center">Your web site is in OFFLINE mode, only you are able to view it. If you are ready for others to view it, please go to the settings page in your site management area. This message will be removed once your site is live.</div>';
    $page->page = str_replace("<BODY>", "<body>", $page->page);
    $page->page = str_replace("<body>", "<body>".$m, $page->page);
}
//add head_code contents just before the end head tag
$settings = settings('head_code');
$page->page = str_replace("</head>", stripslashes($settings['head_code'])."</head>", $page->page);
//tagline settings, inject CSS code into the head if tagline settings are defined
$tagCSS = '';
$tagLineSettings = settings('tagline_size,tagline_colour,tagline_align,tagline_font');
//if tagline it self is empty
if (empty($tagLineContent))
{
    $tagCSS .= '#header #tagline,#tagline{display:none;}';
}
//tagline_size
if (!empty($tagLineSettings['tagline_size']) && !empty($tagLineContent))
{
    $tagCSS .= '#header #tagline,#tagline{font-size:'.$tagLineSettings['tagline_size'].';}';
}
//tagline_colour
if (!empty($tagLineSettings['tagline_colour']) && !empty($tagLineContent))
{
    $tagCSS .= '#header #tagline,#tagline{color:#'.$tagLineSettings['tagline_colour'].';}';
}
//tagline_align
if (!empty($tagLineSettings['tagline_align']) && !empty($tagLineContent))
{
    $tagCSS .= '#header #tagline,#tagline{text-align:'.$tagLineSettings['tagline_align'].';';
    if ($tagLineSettings['tagline_align'] == 'left' || $tagLineSettings['tagline_align'] == 'right')
    {
        if (!empty($tagLineContent))
        {
            $tagCSS .= 'padding-'.$tagLineSettings['tagline_align'].':30px;';
        }
    }
    $tagCSS .= '}';
}
//tagline_font
if (!empty($tagLineSettings['tagline_font']) && !empty($tagLineContent))
{
    $tagCSS .= '#header #tagline,#tagline{font-family:'.str_replace('&#8218;', ',', $tagLineSettings['tagline_font']).';}';
}
//inject tagline css
$taglineCSS = (!empty($tagCSS)) ? '<style type="text/css">'.$tagCSS.'</style>' : '';
$page->page = str_replace("</head>", $taglineCSS."</head>", $page->page);
//inject mobile css files and css
$settings = settings('enable_mobile_site');
if ($settings['enable_mobile_site'] == 'n')
{
    $code = '<style type="text/css">.ShowForMobile {display:none;}</style>';
    $page->page = str_replace("</head>", $code."</head>", $page->page);
}
if ($settings['enable_mobile_site'] == 'ylight' || $settings['enable_mobile_site'] == 'ydark')
{
    //update the layout.css href with min width
    $tUsed = settings('template');
    $o = '<link rel="stylesheet" type="text/css" href="/templates/'.$tUsed['template'].'/layout.css" />';
    $r = '<link rel="stylesheet" type="text/css" href="/templates/'.$tUsed['template'].'/layout.css" media="screen and (min-width: 700px)" />';
    $r .= '<!--[if lt IE 9]><link rel="stylesheet" type="text/css" href="/templates/'.$tUsed['template'].'/layout.css" /><![endif]-->';
    //add mobile menu js and css
    $c = '<script src="https://www.freesites.com.au/addons/mobileMenu.js" type="text/javascript"></script><script type="text/javascript">jQuery(document).ready(function(){jQuery("#my-menu").mmenu();});</script>';
    $page->page = str_replace('jquery.min.js" type="text/javascript"></script>', 'jquery.min.js" type="text/javascript"></script>'.$c, $page->page);
    $c = '<link rel="stylesheet" type="text/css" href="//www.freesites.com.au/addons/mobileMenu.css" media="screen and (max-width: 699px)" />';
    $page->page = str_replace("</head>", $c."</head>", $page->page);
    $page->page = str_replace($o, $r, $page->page);
    //inject mobile css
    $mobileCSS = ($settings['enable_mobile_site'] == 'ylight') ? '//www.freesites.com.au/addons/mobile.css' : '//www.freesites.com.au/addons/mobile-dark.css';
    $t = settings('template');
    if (file_exists('templates/'.$t['template'].'/addons/mobile.css'))
    {
        $mobileCSS = '/templates/'.$t['template'].'/addons/mobile.css';
    }
    //if there is a tablet css file for this template, add it
    $tablet = '<link rel="stylesheet" type="text/css" href="//www.freesites.com.au/addons/tablet.css" media="screen and (min-width: 700px) and (max-width: 1000px)" />';
    if (file_exists('templates/'.$t['template'].'/addons/tablet.css'))
    {
        $tablet = '<link rel="stylesheet" type="text/css" href="/templates/'.$t['template'].'/addons/tablet.css" media="screen and (min-width: 700px) and (max-width: 1000px)" />';
    }
    //view port should be right after opening head tag
    $page->page = str_replace("<head>", "<head><meta name=viewport content=\"width=device-width, initial-scale=1\" />", $page->page);
    $code = '<style type="text/css">.ShowForMobile{display:none;}</style>'.$tablet.'<link rel="stylesheet" type="text/css" href="'.$mobileCSS.'" media="screen and (max-width: 699px)" />';
    $page->page = str_replace("</head>", $code."</head>", $page->page);
    //inject a dropdown menu for mobile use
    $hm = '<style type="text/css">@media (min-width: 700px){#my-menu{display:none;}}#my-menu:not(.mm-menu){display:none;}</style><!--[if lt IE 9]><style type="text/css">#my-menu{display:none;}</style><![endif]-->';
    $page->page = str_replace("</head>", '</head>'.$hm, $page->page);
    $menu = '<nav id="my-menu"><ul>';
    foreach ($mobileMenuLinks as $key => $link)
    {
        $url = key($link);
        if (sizeof($link) == 1)
        {
            preg_match("/[0-9]+/", $url, $match);
            if ($_SERVER['HTTP_HOST'] == 'www.allpurposetrailers.com.au')
            {
                $menu .= (array_key_exists((int) $match[0], $mobileMenuLinks)) ? '<li><span>'.$link[$url].'</span>' : '<li><a href="'.$url.'">'.$link[$url].'</a></li>';
            }
            else
            {
                $menu .= (array_key_exists((int) $match[0], $mobileMenuLinks)) ? '<li><a href="'.$url.'">'.$link[$url].'</a>' : '<li><a href="'.$url.'">'.$link[$url].'</a></li>';
            }
        }
        else
        {
            $menu .= '<ul>';
            foreach ($link as $key => $sub)
            {
                $url = key($sub);
                if (!empty($url))
                {
                    $menu .= '<li>';
                    $menu .= '<a href="'.$url.'">'.$sub[$url].'</a>';
                    $menu .= '</li>';
                }
            }
            $menu .= '</ul></li>';
        }
    }
    //mobile currency converter
    $converter = $mysql->get_array($mysql->query("value", "fs_settings", "`name` = 'currency_converter' LIMIT 1"));
    if ($converter['value'] == 'y')
    {
        $h = '<ul><li><a href="#" onclick="selectCurrency(\'AUD\');return false;">$ AUD</a></li><li><a href="#" onclick="selectCurrency(\'NZD\');return false;">$ NZD</a></li><li><a href="#" onclick="selectCurrency(\'HKD\');return false;">$ HKD</a></li><li><a href="#" onclick="selectCurrency(\'USD\');return false;">$ USD</a></li><li><a href="#" onclick="selectCurrency(\'GBP\');return false;">&pound; GBP</a></li><li><a href="#" onclick="selectCurrency(\'EUR\');return false;">&euro; EUR</a></li></ul>';
        $menu .= '<li><span>Change currency</span>'.$h.'</li>';
    }
    $menu .= '</ul></nav>';
    $page->page = str_replace('<body>', '<body>'.$menu, $page->page);
}
$page->page = str_replace('<ul id="nav"><li>', '<ul id="nav"><li class="firstLink">', $page->page);
//create a line for view basket + sub of basket items
$array['basketLineHeader'] = '';
$array['mobileBasketCounter'] = '';
$basketLineHeaderItems = 0;
$s = settings('shop_page');
if ($s['shop_page'] > 0)
{
    $t = $site->pageTitle($s['shop_page']);
    $seo_pageTitle = seo_str($t);
    $query = $mysql->query("(price*qty) as price,qty", "fs_shop_cart", "owner = '{$_SESSION['owner']}' AND temp = 'y'");
    $basketLineHeaderItems = 0;
    $basketLineHeadertotal = 0;
    while ($data = $mysql->get_array($query))
    {
        $basketLineHeadertotal += $data['price'];
        $basketLineHeaderItems += $data['qty'];
    }
    $i = ($basketLineHeaderItems == 1) ? '' : 's';
    $converter = $mysql->get_array($mysql->query("value", "fs_settings", "`name` = 'currency_converter' LIMIT 1"));
    $array['basketLineHeader'] = ($converter['value'] == 'y') ? '<a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'/Basket" title="View my basket">'.number_format($basketLineHeaderItems).' item'.$i.' in my basket - <span class="pgAmount" price="'.number_format($basketLineHeadertotal, 2, '.', '').'">'.number_format($basketLineHeadertotal, 2, '.', '').'</span></a>' : '<a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'/Basket" title="View my basket">'.number_format($basketLineHeaderItems).' item'.$i.' in my basket - $'.number_format($basketLineHeadertotal, 2).'</a>';
    $mobileBasketCounter = '<script>jQuery(\'a.mobileNavToggle\').before(\'<a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'/Basket" class="ShowForMobile mobileBasketLink">View Basket ('.number_format($basketLineHeaderItems).')</a>\');</script>';
    $page->page = str_replace('</head>', '<link rel="stylesheet" type="text/css" href="https://www.freesites.com.au/addons/mobileBasket.css"></style></head>', $page->page);
}
$page->page = str_replace('</body>', $mobileBasketCounter.'</body>', $page->page);
$page->replace_tags($array);
//inject the awesome.css style sheet in head from liveEditor1.7.3
$page->page = str_replace('</head>', '<link rel="stylesheet" type="text/css" href="https://www.freesites.com.au/src/LiveEditor1.7.3/scripts/style/awesome.css"></style></head>'.$menu, $page->page);
//add curreny convert js
$converter = $mysql->get_array($mysql->query("value", "fs_settings", "`name` = 'currency_converter' LIMIT 1"));
if ($converter['value'] == 'y')
{
    $js = '<script type="text/javascript" language="javascript">function pgcLoad(){var tag=document.createElement("script");tag.setAttribute("type","text/javascript");tag.setAttribute("language", "javascript");tag.setAttribute("src","https://www.cloudtools.com.au/converter/currency.js?api_key=38a32d6b40dd8ce7c0c5d23594d8897d"); document.getElementsByTagName("head")[0].appendChild(tag);}setTimeout("pgcLoad()",10);</script>';
    $page->page = str_replace('</body>', $js.'</body>', $page->page);
}
//add logo as the favicon
if (!empty($logoAsFavIcon) && !file_exists('favicon.ico'))
{
    $page->page = str_replace('</head>', $logoAsFavIcon.'</head>', $page->page);
}
//bro track to foot of all sites
//$page->page = str_replace('</body>', '<script src="https://www.cloudtools.com.au/whatbrowser/i.js?api_key=38a32d6b40dd8ce7c0c5d23594d8897d"></script></body>', $page->page);
//add last update stamp to all css files to get around caching
if (file_exists('lastupdate.txt'))
{
    $s = file_get_contents('lastupdate.txt');
    $page->page = str_replace(['.css"', '.CSS"', '.js"'], ['.css?'.$s.'"', '.CSS?'.$s.'"', '.js?'.$s.'"'], $page->page);
}
//if SSL is enabled, replace all site http:// to https://
if (httpOrHttps() == 'https')
{
    $page->page = str_replace('http://'.$_SERVER['REDIRECT_SSL_TLS_SNI'], 'https://'.$_SERVER['REDIRECT_SSL_TLS_SNI'], $page->page);
}
//inject fit video js above head
$page->page = str_replace('</head>', '<script src="https://www.freesites.com.au/addons/fitVideo.js"></script><script>$(document).ready(function(){$("div#content").fitVids();});</script></head>', $page->page);
//change to UTF encoding
$page->page = str_replace('text/html; charset=iso-8859-1', 'UTF-8', $page->page);
//convert all http://www.freesite to https
$page->page = str_replace('http://www.freesites', 'https://www.freesites', $page->page);
$page->page = str_replace('{basketItems}', $basketLineHeaderItems, $page->page);
//show page
$page->output();
