<?php
/*	List of installed modules and module-specific variables	
	Copyright 2002, Intechnic Corporation, All rights reserved
*/

setcookie("CookiesTest", "1");

$ExtraVars = array();    

function ParseEnv()
{
	global $env, $var_list, $mod_prefix,$objSession, $SessionQueryString;

	/* parse individual sections */
	$env = isset($_GET['env']) ? $_GET['env'] : '';
	if ($env == "")
	{
	  $var_list["t"] = "index";
      if(is_array($mod_prefix))
      {      
      	
          foreach($mod_prefix as $key => $value)
          {
            if(strlen($key))
            {
                $parser_name = $key . "_ParseEnv";
                if(function_exists($parser_name))
                {
                    @$parser_name();
                }
            }
          }
          
      }
	}
	else
	{
       $envsections = explode(":", $env);
       foreach($mod_prefix as $key => $value)
       {
         if(strlen($key))
         {
           $parsed=FALSE;
           $parser_name = $key . "_ParseEnv";
           for($i=1; $i<sizeof($envsections); $i++)
           {
             $pieces = explode("-", $envsections[$i]);
             if(substr($pieces[0],0,strlen($key))==$key)
             {             
                $parsed=TRUE;
                if(function_exists($parser_name))
                {
                  $parser_name($envsections[$i]);
                }
             }
           }
           if(!$parsed)
           {
               if(function_exists($parser_name))
               {
                   @$parser_name();
               }
           }
         }
       }
       $req_vars = explode("-", $envsections[0]);
       $sid = $req_vars[0]; 
       if(!$SessionQueryString)
       {
         if(!strlen($sid) || $sid=="_")
         {       
       	   if($sid != "_")
           		$sid = $_COOKIE["sid"];
         }
         else
           $SessionQueryString = TRUE;                     
       }       
       $var_list["sid"] = $sid;
              
       $var_list["t"] = $req_vars[1];
       if( isset($_GET['dest']) )
          $var_list['dest'] = $_GET['dest'];        
    }
    
}

function LoadEnv()
{
    global $env, $var_list, $mod_prefix,$objSession;

	$env = $_GET["env"];
   // echo "Loading Variables..<br>\n";
	if ($env != "")
	{
        $envsections = explode(":", $env);
        foreach($mod_prefix as $key => $value)
        {
          if(strlen($key))
          {
            $parsed=FALSE;
            for($i=1; $i<sizeof($envsections); $i++)
            {
              $pieces = explode("-", $envsections[$i]);
              if(substr($pieces[0],0,strlen($key))==$key)
              {             
                $parsed=TRUE;
                break;
              }
            }
            if(!$parsed)
            {     
              $parser_name = $key . "_LoadEnv";
              //echo $parser_name;
              if(function_exists($parser_name))
              {
                 $parser_name();                 
              }
            }
            else
            {
                $parser_name = $key . "_SaveEnv";
                //echo $parser_name;
                if(function_exists($parser_name))
                {
                    $parser_name($envsections[$i]);
                }
            }
          }
        }
    }
}

function BuildEnv($mod_prefix = false)
{  
    global $var_list,$m_var_list, $var_list_update, $mod_prefix, $objSession, $objConfig,
           $ExtraVars, $objThemes, $CurrentTheme, $SessionQueryString, $FrontEnd;
    
    static $theme;

    $env = "";  
    //echo "Query String: $SessionQueryString<br>\n";
    if(($objConfig->Get("CookieSessions")==0 || !$FrontEnd || ($objConfig->Get("CookieSessions")==2 && $SessionQueryString==TRUE)))
    {
    	if(!$objSession->UseTempKeys)
    	{
    	  $sessionkey = $objSession->GetSessionKey();
    	}
    	else
    	  $sessionkey = $objSession->Get("CurrentTempKey");
	  $env = $sessionkey;
    }
    $env .= "-";	
	if (isset($var_list_update["t"]))
    { 
    	if($var_list_update["t"]=="_referer_")
    	{
    		$var_list_update["t"] =$objSession->GetVariable("Template_Referer");
    	}
    	
        $t = $var_list_update["t"];         
        if(!is_numeric($t))
        {
            if(!is_object($theme))
               $theme = $objThemes->GetItem($m_var_list["theme"]);            
            $id = $theme->GetTemplateId($t);
            $var_list_update["t"] = $id;
        }
		$env .= $var_list_update["t"];
    }
	else
    {
        $t = $var_list["t"];
        if(!is_numeric($t))
        {
            if(!is_object($theme))
               $theme = $objThemes->GetItem($m_var_list["theme"]);           
            $id = $theme->GetTemplateId($t);
            $t = $id;            
        }
		$env .= $t; 
    }
    if(is_array($mod_prefix))
    {    
      foreach($mod_prefix as $key => $value)
	  {        
       	$builder_name = $key . "_BuildEnv";
        if(function_exists($builder_name))
        { 
        	$GLOBALS[$key.'_var_list_update']['test'] = 'test';
        	$env .= $builder_name();
        }
	  }
    }
    
    $extra = "";
    $keys = array_keys($ExtraVars);
    if(is_array($keys))
    {    
      for($i=0;$i<count($keys);$i++)   
      {
        $key = $keys[$i];

        $e = "&".$key."=".$ExtraVars[$key];
        $extra .= $e;
        $e = "";
      }
    }
    $env .= $extra;
    
	return $env;
}

function CategoryActionFunc($basename,$CatList)
{
    global $mod_prefix;

    foreach($mod_prefix as $key => $value)
	{        
       	$function_name = $key."_".$basename;
        if(function_exists($function_name))
        {
            $function_name($CatList);
        }
    }
}


function RegisterEnv($Var,$Value)
{
    global $ExtraVars;

    $ExtraVars[$Var] = $Value;    
}

function UnregisterEnv($Var)
{
    global $ExtraVars;

    unset($ExtraVars[$Var]);
}

function ModuleTagPrefix($name)
{
    global $modules_loaded;

    $ret = "";
    foreach($modules_loaded as $prefix=>$mod_name)
    {
        if($name==$mod_name)
        {
            $ret = $prefix;
            break;
        }
    }
    return $ret;
}

function ModuleEnabled($name)
{
    global $template_path;

    $a = array_keys($template_path);
    if(in_array($name,$a))
        return TRUE;
    return FALSE;
}

function GetModuleArray($array_name="mod_prefix")
{
    switch($array_name)
    {
    case "mod_prefix":
        global $mod_prefix;
        return $mod_prefix;
    break;
    case "admin":
        global $mod_prefix, $modules_loaded;
        $mod = array();
        if(is_array($mod_prefix) && is_array($modules_loaded))
        {        
          foreach ($mod_prefix as $key=>$value)
          {
            if(_ModuleLicensed($modules_loaded[$key]) || $key=="m")
            {
                $mod[$key] = $value;
            }
          }
        }
        return $mod;
    break;
    case "loaded":
        global $modules_loaded;
        return $modules_loaded;
    break;
    case "template":
        global $template_path;
        return $template_path;
    case "rootcat":
    		global $mod_root_cats;
        return $mod_root_cats;
    break;
    }
}

function admin_login()
{	
    global $objSession,$login_error, $objConfig,$g_Allow,$g_Deny;
   
    //echo "<pre>"; print_r($objSession); echo "</pre>";
	
	if( GetVar('help_usage') == 'install' ) return true;
	
    $env_arr = explode('-', $_GET['env']);
    $get_session_key = $env_arr[0];
    $admin_login = isset($_POST['adminlogin']) && $_POST['adminlogin']; // $_POST['adminlogin'] != 1
    if(!$objSession->ValidSession() || ($objSession->GetSessionKey() != $get_session_key && !$admin_login)) {
      	if( isset($_GET['expired']) && ($_GET['expired'] == 1) ) 
    		$login_error = admin_language("la_text_sess_expired");
      	
    	return FALSE;
    	//echo "Expired<br>";
    }
    
	if ($objSession->HasSystemPermission("ADMIN") == 1)
		return TRUE;

    if(count($_POST)==0 || $_POST["adminlogin"]!=1)
      return FALSE;		
    $login=$_POST["login"];
    $password = $_POST["password"];
    
    if (strlen($login) && strlen($password))
    {    
      if(!_IpAccess($_SERVER['REMOTE_ADDR'],$g_Allow,$g_Deny))
      {
    	  $login_error = admin_language("la_text_address_denied");
    	  return FALSE;
      }
      $valid = $objSession->Login($login, md5($password));
      $hasperm = ($objSession->HasSystemPermission("ADMIN") == 1);
      if (($login=="root" || $hasperm) && $valid)
      {     	        	 
          if(_ValidateModules())
          {          
            return TRUE;
          }
          else
              $login_error = "Missing or invalid In-Portal License";
      }
	  else
	  {
	  	if(!$hasperm && $valid)
	  	{
	  		$login_error = admin_language("la_text_nopermissions");
	  	}
	  	else
	  	{
	  	  $login_error = admin_language("la_Text_Access_Denied");
	  	}
	  	return FALSE;
	  }
	}
    else
    {
    	if(!strlen($login))
    	{
    	  $login_error = admin_language("la_Text_Missing_Username");
    	}
    	else
    	  if(!strlen($password))
    	  	$login_error = admin_language("la_Text_Missing_Password");
        return FALSE;
    }
}


#---------------------------------------------------------------------------

function _EnableCookieSID()
{
	global $var_list, $objConfig;

	if((!$_COOKIE["sid"] && $objConfig->Get("CookieSessions")>0 && strlen($var_list["sid"])<2 && !headers_sent()) 
		|| strlen($_COOKIE["sid"])>0)
		{
		  return TRUE;	
		}
		else
		 return FALSE;	
}

function _IsSpider($UserAgent)
{
  global $robots, $pathtoroot;

  $lines = file($pathtoroot."robots_list.txt");

  if(!is_array($robots))
  {  
    $robots = array();
   for($i=0;$i<count($lines);$i++)
    { 
      $l = $lines[$i];
      $p = explode("\t",$l,3);
      $robots[] = $p[2];
    }
  }
  return in_array($UserAgent,$robots);
}

function _StripDomainHost($d)
{
  	$dotcount = substr_count($d,".");
	if($dotcount==3)
	{
	   $IsIp = TRUE;
	   for($x=0;$x<strlen($d);$x++)
	   {
	   	  if(!is_numeric(substr($d,$x,1)) && substr($d,$x,1)!=".")	
	   	  {
	   	    $IsIp = FALSE;
	   	    break;
	   	  } 
	   }	   
	}
	if($dotcount>1 && !$IsIp)
	{
		$p = explode(".",$d);
		$ret = $p[count($p)-2].".".$p[count($p)-1];
	}
	else
	  $ret = $d;
	return $ret;
}

function _MatchIp($ip1,$ip2)
{
  $matched = TRUE;
  	 
  $ip = explode(".",$ip1);
  $MatchIp = explode(".",$ip2);
  for($i=0;$i<count($ip);$i++)
  {
  	if($i==count($MatchIp))
  	  break;
  	if(trim($ip[$i]) != trim($MatchIp[$i]) || trim($ip[$i])=="*")
   	{
   		$matched=FALSE;
   		break;
   	}
  }
  return $matched;
}

function _IpAccess($IpAddress,$AllowList,$DenyList)
{	
  $allowed = explode(",",$AllowList);
  $denied = explode(",",$DenyList);

  $MatchAllowed = FALSE;
  for($x=0;$x<count($allowed);$x++)
  {
  	 $ip = explode(".",$allowed[$x]);
  	 
	 $MatchAllowed = _MatchIp($IpAddress,$allowed[$x]);  	 
  	 if($MatchAllowed)
  	   break;
  }	
  $MatchDenied = FALSE;
  for($x=0;$x<count($denied);$x++)
  {
  	 $ip = explode(".",$denied[$x]);
  	 
	 $MatchDenied = _MatchIp($IpAddress,$denied[$x]);  	 
  	 if($MatchDenied)
  	   break;
  }	
  
  $Result = (($MatchAllowed && !$MatchDenied) || (!$MatchAllowed && !$MatchDenied) || 
  			($MatchAllowed && $MatchDenied));
  return $Result;
}

function _ValidateModules()
{
    global $i_Keys, $objConfig, $g_License;

    $lic = base64_decode($g_License);
    _ParseLicense($lic);
    
    $modules = array();
    //echo "License: ".$lic."<br>";
    $domain = _GetDomain();    
    //echo "Domain: ".$domain."<br>";
    if(!_IsLocalSite($domain))
    {    
    	$domain = _StripDomainHost($domain);
    	//echo "New domain: $domain<br>";
//    	echo "<pre>"; print_r($i_Keys); echo "</pre>";
        for($x=0;$x<count($i_Keys);$x++)
        {
            $key = $i_Keys[$x];
            if(strlen(stristr($key["domain"],$domain)))            
            {
                $modules = explode(",",$key["mod"]);
                //echo "Modules: $modules";
            }
        }            
        if(count($modules)>0)
        {        	    
            return TRUE;
        }
    }
    else 
      return TRUE;    
    return FALSE;
}

function _ModuleLicensed($name)
{
    global $i_Keys, $objConfig, $pathtoroot;
	$vars = parse_portal_ini($pathtoroot."config.php");

	while($key = key($vars))
	{
  		$key = "g_".$key;
  		global $$key;
  		$$key = current($vars); //variable variables
  		if(strlen($$key)>80)
  		{
  		  $lic = base64_decode($$key);
  		}   		  
  		next($vars);
	}    
    //$lic = base64_decode($g_License);
    _ParseLicense($lic);
    $modules = array();
    if(!_IsLocalSite(_GetDomain()))
    {    
        for($x=0;$x<count($i_Keys);$x++)
        {
            $key = $i_Keys[$x];
            if(strlen(stristr(_GetDomain(),$key["domain"])))             
            {
                //echo "ok<br>";
            	$modules = explode(",",$key["mod"]);            	
            }
        }            
        if(in_array($name,$modules)) {
        	//echo "ok<br>";
            return TRUE;
        }
    }
    else {
        return TRUE;
    }

    return FALSE;
}

function _GetDomain()
{
	global $objConfig, $g_Domain;
	
	if($objConfig->Get("DomainDetect"))
	{
		$d = $_SERVER['HTTP_HOST'];
	}
	else
	  $d = $g_Domain;
	  
	return $d;	
}

function _keyED($txt,$encrypt_key)
{
 $encrypt_key = md5($encrypt_key);
 $ctr=0;
 $tmp = "";
 for ($i=0;$i<strlen($txt);$i++)
 {
     if ($ctr==strlen($encrypt_key)) $ctr=0;
        $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1); 
      $ctr++;
 }
 return $tmp;
}


function _decrypt($txt,$key)
{
    $txt = _keyED($txt,$key);
    $tmp = ""; 
    for ($i=0;$i<strlen($txt);$i++) 
    {
        $md5 = substr($txt,$i,1);
        $i++;
        $tmp.= (substr($txt,$i,1) ^ $md5);
   }
    return $tmp; 
} 

function LoadFromRemote()
{
    return "";
}

function DLid()
{
    global $lid;
    echo $lid."\n";
    die();
}

function _LoadLicense($LoadRemote=FALSE)
{
    global $pathtoroot, $objConfig;
    
    $f = $pathtoroot."intechnic.php";
    if(file_exists($f))
    {
        $contents = file($f);
        $data = base64_decode($contents[1]);
    }
    else
        if($LoadRemote)
            return $LoadFromRemote;   
   return $data;
}

function _VerifyKey($domain,$k)
{
    $key = md5($domain);
    $lkey = substr($key,0,strlen($key)/2);
    $rkey = substr($key,strlen($key)/2);
    $r = $rkey.$lkey;
    if($k==$r)
        return TRUE;
    return FALSE;
}

function _ParseLicense($txt)
{
  global $i_User, $i_Pswd, $i_Keys;

  $data = _decrypt($txt,"beagle");
  $i_Keys = array();
  $lines = explode("\n",$data);
  for($x=0;$x<count($lines);$x++)
  {
      $l = $lines[$x];
      $p = explode("=",$l,2);
      switch($p[0])
      {
      case "Username":
          $i_User = $p[1];
      break;
      case "UserPass":
          $i_Pswd = $p[1];
      break;
      default:
        if(substr($p[0],0,3)=="key")
        {            
            $parts = explode("|",$p[1]);
            if(_VerifyKey($parts[0],$parts[1]))
            {
                unset($K);
                $k["domain"]=$parts[0];
                $k["key"]=$parts[1];
                $k["desc"]=$parts[2];
                $k["mod"]=$parts[3];
                $i_Keys[] = $k;         
            }
        }
      break;
      }
  }
}

function _IsLocalSite($domain)
{
    $localb = FALSE; 
    if(substr($domain,0,3)=="172")
    {
        $b = substr($domain,0,6);
        $p = explode(".",$domain);
        $subnet = $p[1];
        if($p[1]>15 && $p[1]<32)
            $localb=TRUE;
    }
    if($domain=="localhost" || $domain=="127.0.0.1" || substr($domain,0,7)=="192.168" ||
       substr($domain,0,3)=="10." || $localb || strpos($domain,".")==0)
    {
        return TRUE;
    }
    return FALSE;
}
//echo "Before Stuff<br>";
LogEntry("Loading Modules\n");
/* get the module list from the database */
$adodbConnection = GetADODBConnection();	
$sql = "SELECT Name, Path, Var,TemplatePath, RootCat from ".GetTablePrefix()."Modules where Loaded=1 ORDER BY LoadOrder";
$rs = $adodbConnection->Execute($sql);

while($rs && !$rs->EOF)
{
    $key = $rs->fields["Var"];
    $mod_prefix[$key] = $rs->fields["Path"];
    $modules_loaded[$key] = $rs->fields["Name"];
    $name = $rs->fields["Name"];
    $template_path[$name] = $rs->fields["TemplatePath"];
    $mod_root_cats[$name] = $rs->fields["RootCat"];
   // echo $key . "=". $modules_loaded[$key]."<br>\n";
    $rs->MoveNext();
}

LogEntry("Loading Module Parser scripts\n");
/* for each module enabled, load up parser.php */
//foreach($mod_prefix as $key => $value)
$LogLevel++;
if(is_array($mod_prefix))
{
  foreach($mod_prefix as $key => $value)
  {	

      $mod = $pathtoroot . $value . "parser.php";	 
//      LogEntry("Loading parser $mod \n");
      require_once($mod);
          
  }
}
$LogLevel--;
LogEntry("Finished Loading Module Parser scripts\n");
/*now each module gets a look at the environment string */

$SessionQueryString = FALSE;

if(!isset($FrontEnd)) $FrontEnd = false;

if($FrontEnd != 1)
  $SessionQueryString = TRUE;

if(is_array($mod_prefix))
    ParseEnv(); 

/* create the session object */

$ip = $_SERVER["REMOTE_ADDR"];

if ( !isset($var_list['sid']) ) $var_list['sid'] = '';
if ( !isset($_GET['env']) ) $_GET['env'] = '';

if(strlen($var_list["sid"])==0 && strlen($_GET["env"])>0 && $objConfig->Get("CookieSessions")==2)
{   
    if(_IsSpider($_SERVER["HTTP_USER_AGENT"]))
    {    
        $UseSession = FALSE;
    }
    else
    {
        /* switch user to GET session var */
        if (!$_COOKIE['sid']) {
        	$SessionQueryString = TRUE;
        }
        //else {
        	//$SessionQueryString = FALSE;
        //}
        $UseSession = TRUE;
    }
}
else {
    $UseSession = TRUE;
}
    
if($var_list["sid"]=="_")
  $var_list["sid"]="";    

/*setup action variable*/
$Action = isset($_REQUEST['Action']) ? $_REQUEST['Action'] : '';

if($Action=="m_logout")
{
   $u = new clsUserSession($var_list["sid"] ,($SessionQueryString && $FrontEnd==1));
   $u->Logout();
   unset($u);	
   $var_list_update["t"] = "index";  
   $var_list["t"] = "";
   $var_list["sid"]="";
   setcookie("login","",time()-3600);
   setcookie("sid","",time()-3600);   
}

$CookieTest = isset($_COOKIE["CookiesTest"]) ? $_COOKIE["CookiesTest"] : '';
$HTTP_REFERER = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

if ( ($CookieTest == 1)  || !strstr($HTTP_REFERER, $_SERVER['SERVER_NAME'].$objConfig->Get("Site_Path"))) {
	$SessionQueryString = FALSE;
}

if ($FrontEnd != 1) {
	$SessionQueryString = TRUE;
}

$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));

if($UseSession)
{  
  if(!$objSession->ValidSession())
  { 
    /* Get rid of Invalid Session and make a brand new one*/
//    echo "Dumping Session ".$var_list["sid"]."<br>";
    unset($var_list["sid"]);
	$objSession->GetNewSession();
    	$var_list["sid"] = $objSession->GetSessionKey();
	$var_list_update["sid"]=$objSession->GetSessionKey();
    if(is_numeric($m_var_list["theme"]))       
      $objSession->SetThemeName($m_var_list["theme"]);  
    if($objConfig->Get("CookieSessions")>0 && !$SessionQueryString && !headers_sent())
        setcookie("sid",$var_list["sid"]);
    //echo "New Session: ".$objSession->GetSessionKey()."<br>\n";
    if(isset($_COOKIE["login"]) && $Action != "m_logout" && $FrontEnd==1)
    {
        $parts = explode("|",$_COOKIE["login"]);
        $username = $parts[0];
        $pass = $parts[1];
        $objSession->Login($username,$pass);
    }
  }
  else
  { //echo "Update Session<br>";
    if($objSession->Get("Language")!=$m_var_list["lang"])
    {
      $objSession->Set("Language",$m_var_list["lang"]);
    }
    $objSession->LoadSessionData();
    $objSession->UpdateAccessTime(); 
    $objSession->Update();
    LoadEnv();
  }
}

if(is_numeric($var_list["t"]))
{
	if( !isset($CurrentTheme) ) $CurrentTheme = null;
  if(!is_object($CurrentTheme))
     $CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
  
  $var_list["t"] = $CurrentTheme->GetTemplateById($var_list["t"]);
  $objSession->Set("Theme",$CurrentTheme->Get("Name"));
}
/*create the global current user object */
$UserID=$objSession->Get("PortalUserId");
$objCurrentUser = new clsPortalUser($UserID);
$objLanguageCache = new clsLanguageCache($m_var_list["lang"]);

/* include each module's action.php script */
LogEntry("Loading Module action scripts\n");

## Global Referer Template
$_local_t = $var_list["t"];	

if(is_array($mod_prefix))
{
 foreach($mod_prefix as $key => $folder_name)
 {
    if($FrontEnd==0 || !is_numeric($FrontEnd) || $FrontEnd==2)
    { 
	  $rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
	  $admin = $objConfig->Get("AdminDirectory");
	  if( !strlen($admin) ) $admin = "admin";
	  $adminURL = $rootURL.$admin;
      $imagesURL = $adminURL."/images"; 	
      if(_ModuleLicensed($modules_loaded[$key]))
      {           	  
        $mod = $pathtoroot.$folder_name."module_init.php";
        if( file_exists($mod) ) require_once($mod);    	 
      	      	
        $mod = $pathtoroot.$folder_name."action.php";
        if( file_exists($mod) ) require_once($mod);  

        $mod = $pathtoroot.$folder_name."searchaction.php";
        if( file_exists($mod) ) require_once($mod);
      }
    }
    if($FrontEnd==1 || $FrontEnd==2)
    {
    	$mod = $pathtoroot.$folder_name."module_init.php";
        if(file_exists($mod))
          require_once($mod);      	
        $mod = $pathtoroot.$folder_name."frontaction.php";
        if(file_exists($mod))
          require_once($mod);      
    }
  }
}

if (strstr($_SERVER['SCRIPT_NAME'], 'install')) {
	$objSession->Delete();
}

if( !isset($SearchPerformed) ) $SearchPerformed = false;
if($SearchPerformed == true) $objSearch->BuildIndexes();
LogEntry("Finished Loading Module action scripts\n");
?>