<?php
// 
// HM-Portal 3.1.2
// for Woltlab Burning Board 2.1.x
// Old_Surehand (old_surehand@web.de)
// based on HPortal 2.5 by Trooper
//

$filename = "hmportal.php";

// Profiler on/off
// Needs certain insertions in the file class_db_mysql.php to work! 
$f_prof = 0;

if ($f_prof) $time_start = microtime();

require ("./global.php");
$lang->load("HMPORTAL,HMBOXES");
// more require()s after the engine part to keep this part fast.

//
// Engine: Open and close boxes  / style dropdown / language dropdown / poll voting
//

if (isset($_REQUEST['action'])) $action = $_REQUEST['action'];
else $action = "";
if (isset($_REQUEST['h_activ'])) $h_activ = intval($_REQUEST['h_activ']);
else $h_activ = 0;
if (isset($_REQUEST['h_boxid'])) $h_boxid = intval($_REQUEST['h_boxid']);
else $h_boxid = 0;
if (isset($_REQUEST['styleid'])) $styleid = intval($_REQUEST['styleid']);
else $styleid = "";
if (isset($_REQUEST['langid'])) $langid = intval($_REQUEST['langid']);
else $langid = "";

// open/close boxes
if(($action=='activ') && ($wbbuserdata['userid'])) {
  // note: this code does not presume that user entries and/or boxes exist.
  // It just has no effect if they don't.
  // (normally they should exist as this is only called from the portal itself)

  if($h_activ=='0') {
    $db->query("UPDATE bb".$n."_hm_portal_user 
                  SET h_activ = '0' 
                  WHERE h_userid ='".$wbbuserdata['userid']."' AND h_boxid = '$h_boxid'");
  }
  if($h_activ=='1') {
    $db->query("UPDATE bb".$n."_hm_portal_user 
                  SET h_activ = '1' 
                  WHERE h_userid ='".$wbbuserdata['userid']."' AND h_boxid = '$h_boxid'");
  }
}

// change user's board style
if(($action=='style') && ($wbbuserdata['userid'])) {
  if ($styleid !== "") {
    $styleid = intval($styleid);
    $db->query("UPDATE bb".$n."_users 
                  SET styleid = '$styleid' 
                  WHERE userid ='".$wbbuserdata['userid']."' ");
    header("Location: $filename?sid=$session[hash]");
    exit();
  }
} 

// change user's language pack
if(($action=='languagepack') && ($wbbuserdata['userid'])) {
  if ($langid !== "") {
    $langid = intval($langid);
    $db->query("UPDATE bb".$n."_users 
                  SET langid = '$langid' 
                  WHERE userid ='".$wbbuserdata['userid']."' ");
    header("Location: $filename?sid=$session[hash]");
    exit();
  }
} 

// vote in a poll
if ($action=='pollvote') {
  $lang->load("MISC");

  // Woltlab code (from pollvote.php) for poll voting
  if(!isset($pollid)) eval("error(\"".$lang->get4eval("LANG_GLOBAL_ERROR_FALSELINK")."\");");
  if(checkpermissions("can_vote_poll")) {
    // voted for anything at all? 
    if(!count($_POST['polloptionid'])) eval("error(\"".$lang->get4eval("LANG_MISC_POLLVOTE_ERROR1")."\");");
    // poll still valid?
    if($poll['timeout'] && time()>$poll['starttime']+$poll['timeout']*86400) eval("error(\"".$lang->get4eval("LANG_MISC_POLLVOTE_ERROR2")."\");");
    // too many options marked?
    if(count($_POST['polloptionid'])>$poll['choicecount']) {
      eval ("\$lang->items[LANG_MISC_POLLVOTE_ERROR3] = \"".$lang->get4eval("LANG_MISC_POLLVOTE_ERROR3")."\";");
      eval("error(\"".$lang->get4eval("LANG_MISC_POLLVOTE_ERROR3")."\");");
    }
    // already voted?
    if($wbbuserdata['userid']) $votecheck=$db->query_first("SELECT id AS pollid FROM bb".$n."_votes WHERE id='$pollid' AND votemode='1' AND userid='$wbbuserdata[userid]'");
    else $votecheck=$db->query_first("SELECT id AS pollid FROM bb".$n."_votes WHERE id='$pollid' AND votemode='1' AND ipaddress='".addslashes($REMOTE_ADDR)."'");
    if($votecheck['pollid']) eval("error(\"".$lang->get4eval("LANG_MISC_POLLVOTE_ERROR4")."\");");
    // everything ok, count vote
    $db->query("INSERT INTO bb".$n."_votes (id,votemode,userid,ipaddress) VALUES ('$pollid','1','$wbbuserdata[userid]','".addslashes($REMOTE_ADDR)."')");
    $polloptionsids=implode(",",$_POST['polloptionid']);
    $polloptionsids=preg_replace("/[^0-9,]/","",$polloptionsids);
    $db->query("UPDATE bb".$n."_polloptions SET votes=votes+1 WHERE polloptionid IN ($polloptionsids)");
  }
  header("Location: $filename?sid=$session[hash]");
  exit();
} 

################################################################################
################################# Portal darstellen ############################

// Woltlab includes
require ("./acp/lib/class_useronline.php");
require ("./acp/lib/class_parse.php");
require ("./acp/lib/class_wiw.php");

// own functions
require ("./hm-portal/hm_portal_functions.php");

// read options
$hmpopt = $db->query_first("SELECT * FROM bb".$n."_hm_portal_spec LIMIT 1");

// Dokumentation fuers Optionen-Array: 
//
// $hmpopt['boxlinks']    // Breite Boxen links (%)
// $hmpopt['boxrechts']   // Breite Boxen rechts (%)
// $hmpopt['boxinnen']    // Breite Boxen Mitte (%)
// $hmpopt['f_injektor']  // Boxinjektor ein/aus
// $hmpopt['injektorurl'] // Boxinjektor URL
// $hmpopt['injektorheight'] // Boxinjektor Höhe in Pixeln
// $hmpopt['f_ank']       // Ankuendigung an/aus
// $hmpopt['f_autopoll']  // Automatik-Umfrage an/aus
// $hmpopt['autopollid']  // Automatik-Umfrage Forums-ID
// $hmpopt['excllist']    // Liste exkludierter Foren
// $hmpopt['pev1']        // (reserviert)
// $hmpopt['pev2']        // Anzahl Events in Termine-Box
// $hmpopt['pev3']        // (reserviert)
// $hmpopt['newsboardid'] // Newsboard-Box boardid
// $hmpopt['a_newsboard'] // Newsboard-Box Anzahl
// $hmpopt['a_lt']        // Anzahl Threads in box_lastthreads
// $hmpopt['a_alt']       // Anzahl Posts in box_anzlastthreads
// $hmpopt['a_tt']        // Anzahl Threads in box_24news ("Top Themen der letzten Tage")
// $hmpopt['ttdays']      // Anzahl Tage rueckwaerts in box_24news ("Top Themen ... ")
// $hmpopt['a_wwd']       // Anzahl Threads in box_wwd ("Zuletzt online")
// $hmpopt['pollid']      // Umfrage-ID in der Umfragebox
// $hmpopt['f_boxtail']   // Soll der untere Balken angezeigt werden? 
// $hmpopt['f_gzipoff']   // Soll der gzip fuers Portal ausgeschaltet werden?
// $hmpopt['f_version']   // Versionsstring
// $hmpopt['a_nb1']       // Anzahl News in der Heise-Box
// $hmpopt['a_nb2']       // Anzahl News in der Golem-Box
// $hmpopt['a_nb(N)']     // Anzahl ... reserviert
// $hmpopt['boardlist']   // Forenliste fuer Spezial-Foren-Box
// $hmpopt['a_bbb']       // Anzahl Eintraege in der Gaestebuchbox
// $hmpopt['bbooklink']   // Link zum Gaestebuch
// $hmpopt['a_auc']       // Anzahl Eintraege in der Auktionsbox
// $hmpopt['clip_news']   // Kuerzlaenge in der Newsbox
// $hmpopt['clip_alt']    // Kuerzlaenge in der Letzte-Beitraege-Box
// $hmpopt['a_database']  // Anzahl Einträge in der Downloads-Box
// $hmpopt['clip_menu']   // Zeilenkuerzlaenge in der Forenuebersicht
// $hmpopt['a_newusers']  // Anzahl Eintraege in der "neueste User"-Box
// $hmpopt['a_topposters'] // Anzahl Eintraege in der Top-Poster-Box
// $hmpopt['a_nb3']       // Flag: Sollen folder icons in Boxen angezeigt werden?
// $hmpopt['a_nb4']       // Flag: Sollen thread icons in Boxen angezeigt werden?
// $hmpopt['a_nb5']       // Flag: Sollen Threads mit eigenen Beitraegen markiert werden?

// these fields were unused before, make sure they aren't out of range
if ($hmpopt['a_nb3']>1) $hmpopt['a_nb3'] = 1;
if ($hmpopt['a_nb4']>1) $hmpopt['a_nb4'] = 1;
if ($hmpopt['a_nb5']>1) $hmpopt['a_nb5'] = 1;

// fill list with dummies if needed
if ($hmpopt['excllist'] == "") $hmpopt['excllist'] = "-1";

// GZip off ?
if ($hmpopt['f_gzipoff']) $gziplevel='0';


// time and time zone for title bar
$currenttime = formatdate($wbbuserdata['timeformat'],time());
$toffset = (($wbbuserdata['timezoneoffset']>=0) ? ("+") : ("")).$wbbuserdata['timezoneoffset'];

// registered user or not?
$welcome="";
$quicklogin="";
$authname="";
if(!$wbbuserdata['userid']) {
  // guest

  // prepare login
  // this should be done in session.php, but NeedNewAuthentificationcode()
  // doesn't know about hmportal.php so it has to be done manually here
  if($allowloginencryption==1)
  {
    // generate new authentification code
    unset($authentificationcode);
    $authentificationcode=makeAuthentificationcode(0);
    $session['authentificationcode'] = $authentificationcode;
    $db->unbuffered_query("UPDATE bb".$n."_sessions SET authentificationcode = '".addslashes($authentificationcode)."' 
                                                    WHERE sessionhash = '".$session['hash']."' ",1);
  } 

  eval ("\$lang->items['LANG_HMPORTAL_WELCOME_WELC'] = \"".$lang->get4eval("LANG_HMPORTAL_WELCOME_WELC")."\";");
  eval ("\$lang->items['LANG_HMPORTAL_WELCOME_PREACH'] = \"".$lang->get4eval("LANG_HMPORTAL_WELCOME_PREACH")."\";");

  eval ("\$quicklogin = \"".$tpl->get("hm_portal_quicklogin")."\";");
  eval ("\$welcome = \"".$tpl->get("hm_portal_welcome")."\";");

  $authname='0';

} else {
  // registered user

  $quicklogin = "";
  $username = htmlconverter($wbbuserdata['username']);
  eval ("\$welcome = \"".$tpl->get("hm_portal_welcomeuser")."\";");

  $authname=$wbbuserdata['userid'];

  // user already in user table?
  $isit = $db->query("SELECT h_userid FROM bb".$n."_hm_portal_user 
                          WHERE h_userid='".$wbbuserdata['userid']."' ");
  if ($db->num_rows($isit)==0) {
    // User registered, but unknown to the portal => create DB entries
    $db->query("INSERT INTO bb".$n."_hm_portal_user (h_userid,h_boxid,h_activ)
                 SELECT '".$wbbuserdata['userid']."', h_boxid, ((h_activ_admin = 0) OR (h_activ_admin = 3))
                   FROM bb".$n."_hm_portal_boxen");
  }
}


//
// Make a list of boards that user can see/enter 
//

$permissioncache = array();
$canviewboardcache = array();
$canenterboardcache = array();

$permissioncache=getPermissions();

$result = $db->query("SELECT boardid, invisible 
                      FROM bb".$n."_boards 
                      WHERE invisible < 2 
                      ORDER BY boardid ASC");

while ($boards = $db->fetch_array($result)) {
  if(!isset($permissioncache[$boards['boardid']]['can_view_board'])
     || $permissioncache[$boards['boardid']]['can_view_board']==-1)
    $permissioncache[$boards['boardid']]['can_view_board']=$wbbuserdata['can_view_board'];
  if(!isset($permissioncache[$boards['boardid']]['can_enter_board'])
     || $permissioncache[$boards['boardid']]['can_enter_board']==-1)
    $permissioncache[$boards['boardid']]['can_enter_board']=$wbbuserdata['can_enter_board'];
  if($boards['invisible']==2 
     || ($boards['invisible']==1 && !$permissioncache[$boards['boardid']]['can_view_board'])) 
    continue;

  if ($permissioncache[$boards['boardid']]['can_view_board']) 
    $canviewboardcache[]  = "$boards[boardid]";   
  if ($permissioncache[$boards['boardid']]['can_enter_board'])
    $canenterboardcache[] = "$boards[boardid]";
}

// ... once again as comma seperated strings:
$boards_view_list  = implode(",",$canviewboardcache);
$boards_enter_list = implode(",",$canenterboardcache);

// avoid SQL error with "IN ()" with dummies
if ($boards_view_list  == "") $boards_view_list = "-1";
if ($boards_enter_list == "") $boards_enter_list = "-1";


// preload often used templates
$hm_boxhead_tpl = $tpl->get("hm_boxhead");        // Kopfzeile jeder Box
$hm_boxtail_tpl = $tpl->get("hm_boxtail");        // Fußzeile jeder Box
$hm_boxminusicon_tpl = $tpl->get("hm_boxminusicon"); // Minus-Icon bei Auswahlboxen

// preload icon paths
$iconset = $db->query("SELECT iconid, iconpath FROM bb".$n."_icons");
while ($iconset1 = $db->fetch_array($iconset)) {
  $iconpaths[$iconset1['iconid']] = replaceImagefolder($iconset1['iconpath']);
}

################################################################################
##########################  Main loop over boxes  ##############################

eval("\$tpl->output(\"".$tpl->get("hm_portal_head")."\");");

// collect boxes for display

if ($authname) {
  // registered user
  $showbox = $db->query("SELECT boxen.* , user.h_activ 
                         FROM bb".$n."_hm_portal_boxen AS boxen,
                              bb".$n."_hm_portal_user AS user,
                              bb".$n."_hm_portal_box2group AS b2g
                         WHERE boxen.h_boxid = user.h_boxid
                           AND user.h_userid = $authname
                           AND boxen.h_boxid = b2g.boxid
                           AND b2g.groupid IN (".implode(",",$wbbuserdata['groupids']).")
                         GROUP BY boxen.h_boxid
                         ORDER BY boxen.h_userbox_spalte, boxen.h_userbox_reihe ASC");
} else {
  // unregistered user (guest)
  // => no entries in bbN_hm_portal_user, only obey group permissions 
  $showbox = $db->query("SELECT boxen.* 
                         FROM bb".$n."_hm_portal_boxen AS boxen,
                              bb".$n."_hm_portal_box2group AS b2g
                         WHERE boxen.h_boxid = b2g.boxid
                           AND b2g.groupid IN (".implode(",",$wbbuserdata['groupids']).")
                         GROUP BY boxen.h_boxid
                         ORDER BY boxen.h_userbox_spalte, boxen.h_userbox_reihe ASC");
}

$alte_spalte = '';

while ($boxdata = $db->fetch_array($showbox)) {

  $spalte = $boxdata[h_userbox_spalte]; // spalte = column
  if ($spalte != $alte_spalte) {
    // start of a new column
    switch ($spalte) {
     case 'links': // left col
       eval("print(\"".$tpl->get("hm_portal_tl")."\");");
       break;
     case 'mitte': // center col
       eval("print(\"".$tpl->get("hm_portal_tend")."\");");
       eval("print(\"".$tpl->get("hm_portal_tm")."\");");
       if($hmpopt['f_ank']=='1') {
         include ("hm-portal/box_ankthread.php");
       }
       break;
     case 'rechts': // right col      
       eval("print(\"".$tpl->get("hm_portal_tend")."\");");
       eval("print(\"".$tpl->get("hm_portal_tr")."\");");
       break;
    }
    $alte_spalte = $spalte; // alte Spalte = old column
  }
  
  $actad = $boxdata['h_activ_admin'];
  $activ = $authname ? $boxdata['h_activ'] : '1' ; // guests can't close boxes
  $boxid = $boxdata['h_boxid'];

  $boxtitel = hmp_getlangvar($boxdata['h_boxtitel'],$lang, 0);
  
  if ($actad == '0'                                                    // obligatory box
      or ((($actad == '1') or ($actad =='3')) and ($activ == '1'))     // opt box (on)
      or (($actad == '2') and ($wbbuserdata['a_can_hmportal_use_app'])
          and ($activ == '1'))) {                                      // admin box on

    // show full box

    // profiler
    if ($f_prof) {
      $time_boxstart = microtime();
      $queries_count_vorbox = $db->queries_count;
      $queries_time_vorbox = $db->queries_time;
    }

    if ($authname and (($actad == '1') or ($actad =='2') or ($actad == '3'))) {   
      // opt. box or admin box => show minus icon
      eval("\$minusicon = \"".$hm_boxminusicon_tpl."\";");
    } else {   
      // obligatory box => no minus icon
      $minusicon = "";
    }
    $boxinclude = $boxdata[h_boxincl];
    $boxinhalt = $boxdata[h_boxinhalt]; // inhalt = contents

    if ($boxinclude == "") {
      // HTML or template box
      eval("print(\"".$hm_boxhead_tpl."\");");

      // if $boxinhalt holds the name of a template starting with
      // hm_ownbox_ or hm_box_at_ , use the template as box contents
      $first10 = substr($boxinhalt,0,10);
      if (($first10 == 'hm_ownbox_') || ($first10=='hm_box_at_')) {
        eval("\$tempvar = \"".$tpl->get(trim($boxinhalt))."\";");
        if ($tempvar!="") $boxinhalt=$tempvar;
      } else {
        // replace by the contents of a language variable if given
        $boxinhalt = hmp_getlangvar($boxinhalt, $lang, 0);
      }
      
      $boxinhalt = replaceImagefolder($boxinhalt); // replace {imagefolder}
      $boxinhalt = str_replace ( "{sid}", $session['hash'], $boxinhalt); 
                                                   // replace {sid}
      print($boxinhalt);
      eval("print(\"".$hm_boxtail_tpl."\");");

    } else {
      // PHP box 
      include ("./$boxinclude");
    }   

    // profiler
    if ($f_prof) {
      $time_boxend_x   = explode(" ",microtime());
      $time_boxstart_x = explode(" ",$time_boxstart);
      $time_boxload = round(($time_boxend_x[0] + $time_boxend_x[1]) - ($time_boxstart_x[0] + $time_boxstart_x[1]),3);
      $queries_count_box = ($db->queries_count) - $queries_count_vorbox;
      $queries_time_box = round(($db->queries_time - $queries_time_vorbox),3);
      print ("<center><span class=\"smallfont\">t = <b>".($time_boxload * 1000)." ms</b>");
      print ("; q = <b>".$queries_count_box."</b>; tq = <b>".($queries_time_box*1000)." ms</b>");
      print (".<br /></span></center><br />\n");
    }

  } elseif ($authname 
            and (($actad == '1') 
                 or ($actad =='3') // opt box closed
                 or (($actad == '2') and ($wbbuserdata['a_can_hmportal_use_app']))) // admin box closed
           ) {
    // show closed box (zu = closed)
    eval("print(\"".$tpl->get("hm_boxzu")."\");");
  } 
}
eval("print(\"".$tpl->get("hm_portal_tend")."\");");

################################################################################

$outstr = "print(\"".$tpl->get("hm_portal_tail")."\");";

if($f_prof) {
  $time_end   = explode(" ",microtime());
  $time_start = explode(" ",$time_start);
  $time_load = round(($time_end[0] + $time_end[1]) - ($time_start[0] + $time_start[1]),3);
  $queries_count = $db->queries_count;
  $queries_time = round($db->queries_time,3);
  $proftext = $lang->items['LANG_HMPORTAL_TAIL_PROFILER'];
  $proftext = str_replace("{time_load}",$time_load,$proftext);
  $proftext = str_replace("{queries_count}",$queries_count,$proftext);
  $proftext = str_replace("{queries_time}",$queries_time,$proftext);
}

// make the mywbb performance display hack work with the portal 
if ($pagestarttime) {
  $gensec=subtract_microtime($pagestarttime,microtime());
  $footer=str_replace("{gensec}",$gensec,$footer);
  $footer=str_replace("{sqlsec}",$sqlsec,$footer);
  $footer=str_replace("{sqlcount}",$sqlcount,$footer);
}

eval($outstr);

?>
