<?php
// +---------------------------------------------+
// |     Copyright © 2003 – 2006 Subdreamer, LLC |
// |     http://www.subdreamer.com               |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

define('IN_SUBDREAMER', true);
$rootpath = './';

// ########################### LOAD SUBDREAMER CORE ############################

include($rootpath . 'includes/core.php');

// ############################ LOAD MAIN SETTINGS #############################

$getmainsettings = $DB->query("SELECT varname, value FROM " . TABLE_PREFIX . "mainsettings");
for($i = 0; $setting = $DB->fetch_array($getmainsettings); $i++)
{
  $mainsettings[$setting['varname']] = $setting['value'];
}

// ############################# ENABLE GZIP COMPRESSION  ########################

if ( $mainsettings['gzipcompress'] == '1' &&
     @extension_loaded('zlib') &&
     @ini_get('zlib.output_compression') != '1' &&
     @ini_get('output_handler') != 'ob_gzhandler')
{
  // This setting can be used to adjust the amount of compression applied (1-9)
  // However it may not work depending on your hosting environment
  //ini_set('zlib.output_compression_level', 3);

  @ob_start('ob_gzhandler');
}


// ################################ MOD REWRITE ################################

if($mainsettings['modrewrite'] AND strlen($_SERVER['REQUEST_URI']) AND !strstr($_SERVER['REQUEST_URI'], '?') AND substr($_SERVER['REQUEST_URI'], -4) != '.php')
{
  // use to determine if the variable's values need addslashes
  $addslashses = get_magic_quotes_gpc() ? false : true;

  // first thing to do is get the real $_SERVER['REQUEST_URI']
  // because if Subdreamer is in a subfolder, then that subfolder will be part of the request_uri
  // for example, if url = http://localhost/subdreamer/ then the request_uri is /subdreamer/
  // so in a way, we have to subtract the url from the request_uri
  // and that can be done thanks to my buddy Oliver Reeves!

  // request_uri, get rid of the trailing slash
  $requesturi = substr($_SERVER['REQUEST_URI'], -1) == '/' ? substr($_SERVER['REQUEST_URI'], 0, -1) : $_SERVER['REQUEST_URI'];

  // pattern to get rid of the root url, ex: http://localhost
  // leaving only the subfolders, ex: /subdreamer/
  $subfolders = preg_replace("#https?://[^/]+(/?.*)#", "\$1", $sdurl);

  // now subtract the subfolders from the request_uri, and get the url with the variables
  // ex: var1/val1/var2/val2 (trailing slash removed above)
  $urlvariables = substr($requesturi, strlen($subfolders));

  // explode the url variables
  $variables = explode('/', $urlvariables);

  // at this point $variables should be an array with an odd number of values (cat/var1/val1)
  // so exit if it's not!
  if(!count($variables) % 2 != 0)
  {
    header("HTTP/1.0 404 Not Found"); // set the HTTP header
    PrintMessage($sdlanguage['url_not_found'] . '<br /><br /><a href="' . $sdurl . '">' . $sdlanguage['redirect_to_homepage'] . '</a>');
    exit;
  }

  if(strlen($variables[0]))
  {
    // before we loop the variable into the $_GET array, lets first grab the categoryid
    $urlcategoryname = $variables[0];

    // now clean the categoryname and addslashes:
    $urlcategoryname = $addslashes ? addslashes(PreClean($urlcategoryname)) : PreClean($urlcategoryname);

    if($category = $DB->query_first("SELECT categoryid FROM " . TABLE_PREFIX . "categories WHERE urlname = '$urlcategoryname'"))
    {
      // set the categoryid
      $_GET['categoryid'] = $category['categoryid'];

      // now it's time to create the variables
      // i = 1 because we're skipping the home category
      for($i = 1; $i < count($variables); $i = $i+2)
      {
        // ($i + 1 = value of variable, ex: var1/val1/ etc...)
        $variablevalue = $variables[$i + 1];

        // clean the values first
        $variablevalue = $addslashes ? addslashes(PreClean($variablevalue)) : PreClean($variablevalue);

        // variable names dont' have to be cleaned, because they are called directly
        $_GET[$variables[$i]] = $variablevalue;
      }
    }
    else
    {
      header("HTTP/1.0 404 Not Found"); // set HTTP header
      PrintMessage($sdlanguage['page_not_found'] . '<br /><br /><a href="' . $sdurl . '">' . $sdlanguage['redirect_to_homepage'] . '</a>');
      exit;
    }
  }
  else
  {
    // no strlen for category name probably means we've loaded the main url
    // ex:www.subdreamer.com
    $_GET['categoryid'] = 1;
  }
}



// ############################## GET CATEGORYID ###############################

$categoryid = (isset($_GET['categoryid']) AND ereg("^[0-9]+$", $_GET['categoryid'])) ? $_GET['categoryid'] : 1;



// ####################### ALTER TITLE AND META SETTINGS #######################

if(isset($_GET['p2_articleid']) AND ereg("^[0-9]+$", $_GET['p2_articleid']))
{
  if($article = $DB->query_first("SELECT title, metakeywords, metadescription FROM " . TABLE_PREFIX . "p2_news WHERE articleid = '" . $_GET['p2_articleid'] . "'"))
  {
    $mainsettings['websitetitle']    .= ' - ' . $article['title'];
    $mainsettings['metadescription'] .= ', ' . $article['metadescription'];
    $mainsettings['metakeywords']    .= ', ' . $article['metakeywords'];
  }
}

// ############################## SET PHP Options ##############################

@ini_set('arg_separator.output','&amp;'); // Get rid of '&' in links

@ini_set('session.use_trans_sid','0'); // Disable PHP adding session ids


// ################### SET LOCALE TIME AND HEADER INFORMATION ##################

$languageinfo = explode('|', $mainsettings['language']);

$charset = $languageinfo[2];

header("Content-Type: text/html; charset=$charset");




// ################################# GET LOGO  #################################

$logo = $mainsettings['currentlogo'];



// ################################# COPYRIGHT #################################
// please do not remove this unless you have purchased the branding free option

$copyright = $mainsettings['copyrighttext'];

if(!$mainsettings['bfo'])
{
  $copyright .= ' <a href="http://www.subdreamer.com" target="_blank" class="copyright">Website Created by Subdreamer CMS</a>';
}



// ############################### USER SYSTEM  ################################
// usersystem is fetched in core.php
// fix username and password for foreign chracters, this only needs to be done
// on the frontend, becuase subdreamer doesn't htmlspecialchars data in the backend.

if(isset($_POST['loginusername']) OR isset($_POST['loginpassword']))
{
  // IPB actually changes usernames from test' to test&#39;
  // so if using IPB don't unhtmlspecialchars the username & password
  // it should also be noted that subdreamer converts ' to &#039;
  // so if using IPB, not only will we not unhtmlspecialchars but we have to fix the single quote
  if($usersystem['name'] == 'Invision Power Board 2')
  {
    $_POST['loginusername'] = str_replace('&#039;', '&#39;', $_POST['loginusername']);
    $_POST['loginpassword'] = str_replace('&#039;', '&#39;', $_POST['loginpassword']);
  }
  else
  {
    $_POST['loginusername'] = unhtmlspecialchars($_POST['loginusername']);
    $_POST['loginpassword'] = unhtmlspecialchars($_POST['loginpassword']);
  }
}

// switch database?
if($usersystem['dbname'] != $dbname)
{
  // Subdreamer is being integrated with a Forum in a different database
  $DB->select_db($usersystem['dbname']);
  require($rootpath . 'includes/usersystems/' . $usersystem['queryfile']);
  $DB->select_db($dbname);
}
else
{
  // Subdreamer may be integrated with a forum in the same database,
  // or is using the Subdreamer User System
  require($rootpath . 'includes/usersystems/' . $usersystem['queryfile']);
}

unset($userinfo);
$userinfo = GetUserInfo($usersettings);
unset($usersettings);


// ############################### WEBSITE OFF? ################################

if($mainsettings['siteactivation'] == 'off')
{
  if($userinfo['offlinecategoryaccess'])
  {
    echo '<table width="100%" border="0" cellpadding="5" cellspacing="0" bgcolor="#FFFFFF">
          <tr>
            <td style="border: 4px solid #FF0000; font-size: 12px; color: #000000;" align="center"><b>Website in Offline Mode</b></td>
          </tr>
          </table>';
  }
  else
  {
    PrintMessage($mainsettings['offmessage']);
    exit();
  }
}



// ############################## CATEGORY ACCESS ##############################

if(!@in_array($categoryid, $userinfo['categoryviewids']))
{
  PrintMessage($sdlanguage['no_view_access'], 1);
  exit();
}


// ############################### IP Banned ? ################################

if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
elseif (isset($_SERVER['HTTP_VIA']))
{
  $ip = $_SERVER['HTTP_VIA'];
}
elseif (isset($_SERVER['REMOTE_ADDR']))
{
  $ip = $_SERVER['REMOTE_ADDR'];
}
else
{
  $ip = 'Banned';
}

if(IsIpBanned($ip))
{
  PrintMessage($sdlanguage['ip_banned'], 0);
  exit();
}


// ############################### SELECT DESIGN  ##############################

$design = $DB->query_first("SELECT d.maxplugins, d.designpath, s.name as skinname FROM " . TABLE_PREFIX . "designs d, " . TABLE_PREFIX . "categories c, " . TABLE_PREFIX . "skins s
                            WHERE c.categoryid = '$categoryid' AND d.designid = c.designid AND s.skinid = d.skinid");



// ############################ GET DESIGN'S PLUGINS  ##########################

$customplugincount = 0;
$getplugins = $DB->query("SELECT pluginid FROM " . TABLE_PREFIX . "pagesort WHERE categoryid = '$categoryid' ORDER BY displayorder");

// store plugins
for($i = 0; $i < $design['maxplugins']; $i++)
{
  $plugins = $DB->fetch_array($getplugins);

  if(substr($plugins['pluginid'], 0, 1) == 'c')
  {
    // it's a custom plugin
    $custompluginid  = substr($plugins['pluginid'], 1);

    if(@in_array($custompluginid, $userinfo['custompluginviewids']))
    {
      $getcustomplugin = $DB->query_first("SELECT displayname, plugin, includefile FROM " . TABLE_PREFIX . "customplugins WHERE custompluginid = '$custompluginid'");

      $customplugin[]     = $getcustomplugin['plugin'];
      $custompluginfile[] = $getcustomplugin['includefile'];

      $pluginname[$i] = $getcustomplugin['displayname'];
      $pluginpath[$i] = 'plugins/customplugins.php';
    }
    else
    {
      $pluginname[$i] = '';
      $pluginpath[$i] = 'plugins/p1_empty/empty.php';
    }
  }
  else
  {
    // it's a normal plugin
    $plugin = $DB->query_first("SELECT pluginpath, displayname, authorname FROM " . TABLE_PREFIX . "plugins WHERE pluginid = '".$plugins['pluginid']."'");

    if(file_exists('plugins/' . $plugin['pluginpath']))
    {
      if(@in_array($plugins['pluginid'], $userinfo['pluginviewids']))
      {
        $pluginname[$i] = $plugin['displayname'];
        $pluginpath[$i] = 'plugins/' . $plugin['pluginpath'];
      }
      else
      {
        $pluginname[$i] = '';
        $pluginpath[$i] = 'plugins/p1_empty/empty.php';
      }
    }
    else
    {
      $pluginname[$i] = '';
      $pluginpath[$i] = 'plugins/error.php';
    }
  }

}



// ############################## GET CATEGORIES  ##############################

// if user is not logged in then do not display member only categories
$getcategories = $DB->query("SELECT categoryid, name, link, target, image, hoverimage FROM " . TABLE_PREFIX . "categories WHERE parentid = 0 ORDER BY displayorder");

for($i = 0; $category = $DB->fetch_array($getcategories); $i++)
{
  // combine category title with HTML's title?
  if($category['categoryid'] == $categoryid AND $mainsettings['categorytitle'])
  {
    $mainsettings['websitetitle'] .= ' - ' . $category['name'];
  }

  if(@in_array($category['categoryid'], $userinfo['categorymenuids']))
  {
    if(strlen($category['image']))
    {
      // hover image
      if(strlen($category['hoverimage']))
      {
        $categoryname[$i] = '<img name="sdhover' . $category['categoryid'] . '" src="' . $sdurl. 'images/' . $category['image'] . '" alt="' . $category['name'] . '" border="0" onMouseOver="Rollover(' . $category['categoryid'] . ', \'' . $sdurl. 'images/' . $category['hoverimage'] . '\', true)" onMouseOut="Rollover(' . $category['categoryid'] . ', \'' . $sdurl. 'images/' . $category['image'] . '\', false)" />';
      }
      else
      {
        $categoryname[$i] = '<img src="' . $sdurl. 'images/' . $category['image'] . '" alt="' . $category['name'] . '" />';
      }
    }
    else
    {
      $categoryname[$i] = $category['name'];
    }

    $categorylink[$i] = strlen($category['link']) ? $category['link'] : RewriteLink('index.php?categoryid=' . $category['categoryid']);

    $categorytarget[$i] = strlen($category['target']) ? $category['target'] : '_self';
  }
  else
  {
    $i--;
  }
}

$categoryrows = $i;



// ############################### LOAD DESIGN  ################################

// add an extra main setting for skins
$mainsettings['skinheader'] = iif(strlen($sdurl), '<base href="' . $sdurl . '"/>') . '
                                                          <script type="text/javascript">
                              <!--
                                                            var TMenu_path_to_files="'.$sdurl.'includes/javascript/hovermenu/";
                              //-->
                                                          </script>
                              <script type="text/javascript" src="includes/javascript/skin_functions.js"></script>
                              <script type="text/javascript" src="includes/javascript/hovermenu/menu.js"></script>';

if(empty($design['designpath']))
{
  $errormsg = '<b>Error: The specified url could not be found.</b><br />
               The page may have been deleted.<br /><br />
               <a href="index.php">Click here to load the home section.</a>';

  PrintMessage($errormsg);
}
else if(is_file('skins/'.$design['designpath']))
{
  if(!include('skins/'.$design['designpath']))
  {
    $errormsg = '<b>Error: Problem including the file:</b><br />
                ' . $design['designpath'] . '<br /><br />
                 <a href="index.php">Click here to load the home section.</a>';
    PrintMessage($errormsg);
  }
}
else
{
  $errormsg = "<b>Error: Failed to load the files for skin '" . $design['skinname'] . "'.</b><br />
               The file '" . 'skins/'.$design['designpath']. "' does not exist.<br /><br />
               <a href='index.php'>Click here to load the home section.</a>";

  PrintMessage($errormsg);
}



// ############################# CLOSE CONNECTION  #############################

$DB->close();

?>