<?php
/**
* simpleboard.php init file
* @package Simpleboard Forum
* @copyright (C) 2000 - 2004 TSMF / Jan de Graaff / All Rights Reserved
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @author Jan de Graaff
* Mambo Open Source is Free Software
**/
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// Dont allow direct linking

error_reporting(E_ALL ^ E_NOTICE);
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
global $_CONFIG;
$catid  = mosGetParam ( $_GET, 'catid' , '' );
$Itemid = mosGetParam ( $_GET, 'Itemid', '' );
$func   = mosGetParam ( $_GET, 'func'  , '' );
//If they're not put in with get requests, try post requests else default to value given
if ($catid  == '' ) $catid  = mosGetParam ( $_POST, 'catid' , '0'      );
if ($Itemid == '' ) $Itemid = mosGetParam ( $_POST, 'Itemid', '1'      );
if ($func   == '' ) $func   = mosGetParam ( $_POST, 'func'  , 'listcat');


//determine the used Mambo Version:
global $version, $mosConfig_lang;
$mambo_release   = _RELEASE=="_RELEASE" ? $_VERSION->RELEASE : _RELEASE;
$mambo_dev_level = _DEV_LEVEL=="_DEV_LEVEL" ? $_VERSION->DEV_LEVEL : 0;

if ( $mambo_release == "4.5" && $mambo_dev_level == "0" ) {
	// 4.5.0
	$PDF=0;
   $database->setQuery("SELECT cur_template FROM #__templates");
	$current_stylesheet=$database->loadResult();
	$css=$mls.'/templates/'.$current_stylesheet.'/css/template_css.css';
	//some global settings needed...
	$map=$mainframe->getCfg( 'absolute_path' );
	$sbp=$map.'/components/com_simpleboard';
	$mls=$mainframe->getCfg( 'live_site' );
	//oops.. sbs is wrong but I don't know where to change it so leaving it in... :-S
	$sbs=$mls.'/components/com_simpleboard';
	$sbs2=$mls.'index.php?option=com_simpleboard&amp;Itemid='.$_GET['Itemid'];
	$simpleboardAdminPath=$map.'/administrator/components/com_simpleboard';
	//get Simpleboards configuration params in
	include_once( $simpleboardAdminPath.'/simpleboard_config.php' );
} else {
	// 4.5.1
	$PDF=1;
	$database->setQuery("SELECT template FROM #__templates_menu where client_id ='0'");	
	$current_stylesheet=$database->loadResult();
	$mosConfig_lang=$mainframe->getCfg( 'lang' );
	$map=$mainframe->getCfg( 'absolute_path' );
	$sbp=$map.'/components/com_simpleboard';
	$mls=$mainframe->getCfg( 'live_site' );
	$css=$mls.'/templates/'.$current_stylesheet.'/css/template_css.css';
	//oops.. sbs is wrong but I don't know where to change it so leaving it in... :-S
	$sbs=$mls.'/components/com_simpleboard';
	$sbs2=$mls.'index.php?option=com_simpleboard&amp;Itemid='.$_GET['Itemid'];
	$simpleboardAdminPath=$map.'/administrator/components/com_simpleboard';	
	//get Simpleboards configuration params in
	include_once( $simpleboardAdminPath.'/simpleboard_config.php' );
	//the next call is 4.5.2+ specific:
	if ($mambo_release=="4.5" && $mambo_dev_level>"2") {
		$bPageTitle=true;
	}
}

//Get right Language file
if (file_exists($map.'/language/'.$mosConfig_lang.'.php')) {
  include($map.'/language/'.$mosConfig_lang.'.php');
} elseif (file_exists($map.'/language/english.php'))  {
  include($map.'/language/english.php');
} //else no language file available... don't include it either...

if (file_exists($simpleboardAdminPath.'/language/'.$mosConfig_lang.'.php')) {
  include_once($simpleboardAdminPath.'/language/'.$mosConfig_lang.'.php');
  //$lfile=$simpleboardAdminPath.'/language/'.$mosConfig_lang.'.php';
  $lfile=$mosConfig_lang;
} else {
  include_once($simpleboardAdminPath.'/language/english.php');
    //$lfile=$simpleboardAdminPath.'/language/english.php';
    $lfile='english';
}
//intercept the RSS request; we should stop afterwards
if ($func=='sb_rss') {
   include($map.'/components/com_simpleboard/sb_rss.php');
   die();
}
if ($func=='sb_pdf') {
	if ($PDF) {
	   include($map.'/components/com_simpleboard/sb_pdf.php');
	} else {
		echo "Sorry, PDF creation is not supported on Mambo 4.5.0";
	}
   die();
}
//Include the Community Builder language file if necessary
if ($sbConfig['cb_profile']) {
	//get the itemid for the Community Builder Component
	$database->setQuery("select id from #__menu where link='index.php?option=com_comprofiler'");
	$cbitemid=$database->loadResult();
	if (file_exists('administrator/components/com_comprofiler/language/'.$mosConfig_lang.'.php')) {
     	include_once('administrator/components/com_comprofiler/language/'.$mosConfig_lang.'.php');
  	} else {
  		include_once('administrator/components/com_comprofiler/language/english.php');
	}
}

//initialise some needed variables
$systime= time()+($sbConfig['board_ofset']*3600);
$board_title=$sbConfig['board_title'];
$fromBot=0;
$prefview=$sbConfig['default_view'];

//See if there's an icon pack installed
$useIcons=0;
if (file_exists($map.'/modules/mod_sbicons.php')) { include_once($map.'/modules/mod_sbicons.php');$useIcons=1;}

//extra forum configuration options. Don't change! 
require_once ($sbp.'/forum.conf'); //this must be here; don't move!

//Get the userid; sometimes the new var works whilst $my->id doesn't..?!?
   $my_id=$my->id;
//See if we're dealing with an administrator
   $aro_group = $acl->getAroGroup( $my->id );
   $is_admin = (strtolower($aro_group->name) == 'super administrator' || strtolower($aro_group->name) == 'administrator');
//Now we check if (s)he's an moderator
   if ($catid != "" && $my_id != 0)
   {
      $database->setQuery("select userid from #__sb_moderation where catid=$catid");
      $moderatorList=$database->loadObjectList();
      if (count($moderatorList)>0) {
         foreach($moderatorList as $ml) {
            //build an array with only moderator userids for comparison later on
            $modIDs[]=$ml->userid;
         }
         if (in_array($my_id, $modIDs)) {
            $is_moderator=1;
         } else {
            $is_moderator=0;
         }
      } else {
         $is_moderator=0;
      }
      //admins always are moderators:
      if ($is_admin) {
         $is_moderator=1;
      }
   } else {
      $is_moderator=0;
   }

if ($sbConfig['regonly'] && !$my->id)
{
   echo _FORUM_UNAUTHORIZIED. "<br />";
   echo _FORUM_UNAUTHORIZIED2;
}
else if ($sbConfig['board_offline'] && !$is_admin)
{
   echo $sbConfig['offline_message'];
}
else
{
//Initial settings; lots of cookie baking things and session tracking...

  // ob_start();
   $new_sb_user=0;
   $previousVisit=0;

   /* Session administration. For security reasons, we will want to initialize it with every
    * Access to Simpleboard. If we'd pass it with posts or pass it through cookies, we would
    * introduce the risk that someone starts 'leeching' on other sessions... we do not want that.
    * After a perion of 30 minutes if inactivity, the priviliges are reset.
    */
      //try to get an existing sessions to recycle - if n/a this is a new user
      $database->setQuery("SELECT * from #__sb_sessions where userid=".$my->id);
      $sbSessionArray=$database->loadObjectList();
      $sbSession=$sbSessionArray[0];

      if ($sbSession->userid=="")
         {//new session, first access
            $previousVisit=time()-1314000;//minus 1 year; you gotta draw the line somewhere...
            $new_sb_user=1;
         }
      else
         {$previousVisit=$sbSession->lasttime;}//user has been here before; this was the last time

      if ($new_sb_user != 1)
      {//get session information, update last time timestamp.

         $inactivePeriod=($sbSession->lasttime)+1800;
         if ($inactivePeriod<$systime){//grant them 30 minutes of inactivity; then recheck privileges and try to send them back where they came from
            $database->setQuery("UPDATE #__sb_sessions SET allowed='na', readtopics='' where userid=$my->id");
            $database->query();
            setcookie("sboard_settings[prevvisit]",$sbSession->lasttime,time()+31536000,'/');
            echo '<script language="javascript">setTimeout("window.location.reload( true )",100);</script>';
         }

         $database->setQuery("UPDATE #__sb_sessions SET lasttime=$systime where userid=$my->id");
         $database->query();
      }
   //Some things should only occur once so first check if we got a new user
   //(user switched to another userid) or a totally new user who just logged on
   //(in both cases the member_id cookie doesn't match the actual user... check..
   //pseudo: if (empty cookie or cookie_id isn't userid) then new user
   if ($settings[member_id]=="" || $settings[member_id] != $my->id) {
      //other or new user
      $new_sb_user=1;
      $allowed_forums = "";
   }
   //New User: Set who this is in a session cookie:
   //pseudo: if (empty_cookie or new user) then set cookie
   if ($settings[member_id]=="" || $new_sb_user==1 || $markaction=="allread")
   {
      setcookie("sboard_settings[member_id]",$my->id,time()+31536000,'/');
      //$previousVisit=$previousVisit+($sbConfig['board_ofset']*3600);
      setcookie("sboard_settings[prevvisit]",$previousVisit,time()+31536000,'/');
      if($markaction=="allread"){
         echo "<script> alert('"._GEN_ALL_MARKED."'); window.location='".sefRelToAbs('index.php?option=com_simpleboard&Itemid='.$Itemid)."'; </script>\n";
      }
   }

   //Initial:: get the user's profile if (s)he's registered. If there's no profile
   //for a registered user, we assume (s)he's here for the first time, so we
   //create one. This should only occur once every session!
   //pseudo: if (new user and ( userid isn't empty or userid isn't zero)
   if ($new_sb_user==1 && (""!=$my->id || 0!=$my->id)){
      $prefview="";//reset value
	  $database->setQuery("select view from #__sb_users where userid=$my->id");
      $prefview=$database->loadResult();
      if ($prefview==""){
         //assume there's no profile; set userid and the default view type as prefered view type.
         if ($sbConfig['default_view']=="threaded") {
         	if ($sbConfig['cb_profile']) { $database->setQuery("update #__comprofiler set sbviewtype='_UE_SB_VIEWTYPE_THREADED' where user_id=$my->id"); }
         	$database->setQuery("insert into #__sb_users (userid,view) values ('$my->id','threaded')");
         	if (!$database->query()){echo _PROBLEM_CREATING_PROFILE;}
         } else {
            if ($sbConfig['cb_profile']) { $database->setQuery("update #__comprofiler set sbviewtype='_UE_SB_VIEWTYPE_FLAT' where user_id=$my->id"); }
         	$database->setQuery("insert into #__sb_users (userid,view) values ('$my->id','flat')");
         	if (!$database->query()){echo _PROBLEM_CREATING_PROFILE;}
         }
         $prefview=$sbConfig['default_view'];
         if($is_admin)
         {//admin is always a moderator on Simpleboard
         $database->setQuery("UPDATE #__sb_users SET moderator='1' WHERE userid='$my->id'");
         $database->query();
         }
		setcookie("sboard_settings[current_view]",$prefview,time()+31536000,'/');
      }

      //initialize the user session tracking
	if ($sbSession->userid==""){
		$database->setQuery("INSERT INTO #__sb_sessions (userid,allowed,lasttime,readtopics) values ($my->id, 'na', $systime,'')");
        if (!$database->query())
			die("Serious db problem:".$database->getErrorMsg());
	}
    else {
		$database->setQuery("UPDATE #__sb_sessions SET allowed='na', lasttime=$systime, readtopics='' where userid=$my->id");
        if (!$database->query())
			die("Serious db problem:".$database->getErrorMsg());
    }
  }
   
   if ($sbConfig['cb_profile'] && (""!=$my->id || 0!=$my->id)) {
	$database->setQuery("select sbviewtype from #__comprofiler where user_id=$my->id");
	$sbviewtype=$database->loadResult();
	  if ($sbviewtype == "_UE_SB_VIEWTYPE_THREADED") {
		$prefview="threaded";
	  } else {
		$prefview="flat";
	  }
	setcookie("sboard_settings[current_view]",$prefview,time()+31536000,'/');
	}

   //Initial:: determining what kind of view to use... from profile, cookie or default settings.
   //pseudo: if (no view is set and the cookie_view is not set)
   if ($view=="" && $settings[current_view]=="")
   {
      //pseudo: if there's no prefered type, use SB's default view otherwise use prefered view from profile
      //and then set the cookie right
      $view=$prefview==""?$default_view:$prefview;
      setcookie("sboard_settings[current_view]",$view,time()+31536000,'/');
   }
   //pseudo: otherwise if (no view set but cookie isn't empty use view as set in cookie
   else if ($view=="" && $settings[current_view]!="")
   {
      $view=$settings[current_view];
   }

   //check if the Itemid is set correctly
   if ($Itemid==1 or $Itemid == "")
   {
      $database->setQuery("select id from #__menu where link='index.php?option=com_simpleboard'");
      $Itemid=$database->loadResult();

   }

   //Get the max# of posts for any one user
   $database->setQuery("SELECT max(posts) from #__sb_users");
   $maxPosts=$database->loadResult();
   
   //Finally, check if the catid requested is a parent category, because if it is
   //the only thing we can do with it is 'listcat' and nothing else
   if ($func == "showcat" || $func == "view" || $func == "post"){
      $database->setQuery("SELECT parent FROM #__sb_categories WHERE id='$catid'");
      $strCatParent=$database->loadResult();
      if ( $strCatParent=="0") $func="listcat";
   }

   switch ($func) {

      #########################################################################################
      case 'sb_rss':
         include($map.'/components/com_simpleboard/sb_rss.php');
      break;
      #########################################################################################
      case 'post':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include ($map."/components/com_simpleboard/smile.class.php");
         include($map.'/components/com_simpleboard/post.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'view':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include ($map."/components/com_simpleboard/smile.class.php");
         include($map.'/components/com_simpleboard/view.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'faq':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/faq.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'showcat':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include ($map."/components/com_simpleboard/smile.class.php");
         include($map.'/components/com_simpleboard/showcat.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'listcat':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/listcat.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'delcat':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/delcat.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'review':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include ($map."/components/com_simpleboard/smile.class.php");
         include($map.'/components/com_simpleboard/moderate_messages.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'rules':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/rules.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'moderate':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/moderation.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'userprofile':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include ($map."/components/com_simpleboard/smile.class.php");
         include($map.'/components/com_simpleboard/userprofile.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'upload':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/avatar_upload.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'latest':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/latestx.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'search':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/search.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      case 'markThisRead':
         // get all already read topics
         $database->setQuery("SELECT readtopics FROM #__sb_sessions WHERE userid=$my->id");
         $allreadyRead=$database->loadResult();
         /* Mark all these topics read */
         $database->setQuery("SELECT thread FROM #__sb_messages WHERE catid=$catid and thread not in ('$allreadyRead') GROUP BY THREAD");
         $readForum=$database->loadObjectList();

         $readTopics='--';
         foreach ($readForum as $rf){
            $readTopics=$readTopics.','.$rf->thread;
         }
         $readTopics=str_replace('--,','',$readTopics);

         if ($allreadyRead != ""){
            $readTopics=$readTopics.','.$allreadyRead;
         }

         $database->setQuery("UPDATE #__sb_sessions set readtopics='$readTopics' WHERE userid=$my->id");
         $database->query();
         echo "<script> alert('"._GEN_FORUM_MARKED."'); window.history.go(-1); </script>\n";
      break;
      #########################################################################################
      case 'karma':
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         include($map.'/components/com_simpleboard/sb_karma.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
      #########################################################################################
      default:
         if ($sbConfig['header']!="") echo "<div class=\"contentheading\">".stripslashes($sbConfig['header'])."</div>";
         if ($catid=="")$catid=0;
         include($map.'/components/com_simpleboard/listcat.php');
         if ($footer!="") echo "<div class=\"sb_footer\">$footer </div>";
      break;
   }//hctiws
}//esle

//General function for printing debug messages to the screen.
function debug($msg){
echo "DEBUG: $msg<br />";
}

function fmodReplace($x,$y)
{ //function provided for older PHP versions which do not have an fmod function yet
   $i = floor($x/$y);
   // r = x - i * y
   return $x - $i*$y;}

function check_image_type(&$type)
{
   switch( $type )
   {
      case 'jpeg':
      case 'pjpeg':
      case 'jpg':
      case 'JPEG':
      case 'PJPEG':
      case 'JPG':
         return '.jpg';
         break;
      case 'gif':
      case 'GIF':
         return '.gif';
         break;
      case 'png':
      case 'PNG':
         return '.png';
         break;
   }

   return false;
}
//error_reporting(E_ALL);
?>
