<? /*

Main script for Intellect Board 2 Project

(C) 2004-2006, XXXX Pro, United Open Project (http://www.openproj.ru)
Visit us online: http://intboard.ru

*/

$IBOARD=1;

error_reporting(E_ERROR | E_WARNING | E_PARSE |E_CORE_ERROR | E_CORE_WARNING);
set_error_handler("err_handler");
set_magic_quotes_runtime(0);
$start_time = microtime();

require("xaphpi.php");
require("common.php");
require("auth.php");
require("config/database.php");
require("config/iboard.php");
require("db/$DBdriver.php");
if (file_exists('addons.php')) require("addons.php");

// Очистка массива параметров от MagicQuotes, если они присутствуют
if (get_magic_quotes_gpc()) {
  strips($_GET);
  strips($_POST);
  strips($_COOKIE);
}

// Установка соединения с БД
if ($DBpersist) $link=db_pconnect($DBhost,$DBusername,$DBpassword,$DBname);
else $link=db_connect($DBhost,$DBusername,$DBpassword,$DBname);

// Обработка HURL, если они включены в настройках
if ($GLOBALS['opt_hurl']) require('hurl.php');

// Получение базовых переменных и их проверка
$forum =&getvar("f");
$topic =&getvar("t");
$step =&getvar('step');
$module =&getvar("m");
$action =&getvar("a");
$start =&getvar('st');

if (!$forum) $forum=0;
if (!$topic) $topic=0;

if ($GLOBALS['opt_gzip']) ob_start("ob_gzhandler");
else ob_start();

if (strpos($module,"/")!==false || strpos($module,"\\")!==false || strpos($module,".")!==false) global_error("Hack attempt! Module: ".$module,1);
if (!is_numeric($forum) || $forum<0) global_error("Hack attempt! Forum: ".$forum,1);
if (!is_numeric($topic) || $topic<0) global_error("Hack attempt! Topic: ".$topic,1);
if ($start && !is_numeric($start) && $start!="all" && $start!="new") global_error("Hack attempt! Start: ".$start);

$order =&getvar('o');
if (preg_match("/\W+/",$order)) global_error("HACK ATTEMPT: order=$order");

// Обработка ситуаций "шаг к следующей/предыдущей теме
if ($step=="next") {
  $sql = "SELECT t_id FROM ".$GLOBALS['DBprefix']."Topic WHERE t_fid=$forum AND t_id>$topic ORDER BY t_id LIMIT 1";
  $res=&db_query($sql,$link);
  if (db_num_rows($res)==0) header("Location: ".$GLOBALS['opt_url']."/index.php?t=$topic");
  list($topic)=db_fetch_row($res);
  db_free_result($res);
  header("Location: ".$GLOBALS['opt_url']."/index.php?t=$topic");
  exit();
}

if ($step=="prev") {
  $sql = "SELECT t_id FROM ".$GLOBALS['DBprefix']."Topic WHERE t_fid=$forum AND t_id<$topic ORDER BY t_id DESC LIMIT 1";
  $res=&db_query($sql,$link);
  if (db_num_rows($res)==0) header("Location: ".$GLOBALS['opt_url']."/index.php?t=$topic");
  list($topic)=db_fetch_row($res);
  db_free_result($res);
  header("Location: ".$GLOBALS['opt_url']."/index.php?t=$topic");
  exit();
}

$curtime=time();

// Анализ HTTP_ACCEPT_LANGUAEGE и выбор языка, который будет использоваться
$lang =&getvar("lang");
if ($lang) {
  if (file_exists($GLOBALS['opt_dir']."/langs/$lang/main.php")) $_SESSION['lang']=$lang;
  else $lang="";
}
if (!$lang && $_SESSION['lang']) {
  if (file_exists($GLOBALS['opt_dir']."/langs/".$_SESSION['lang']."/main.php")) $lang=$_SESSION['lang'];
  else $lang="";
}
if (!$lang && !$_SESSION['uid'] && $langlist=$_SERVER['HTTP_ACCEPT_LANGUAGE']) {
  $langs=explode(",",$langlist);
  foreach ($langs as $curlang) {
    list($langname,$langprior)=explode(";",$curlang);
    if (!$langprior) $langprior=1;
    if (file_exists($GLOBALS['opt_dir']."/langs/$langname/main.php") && $curprior>$langprior) {
      $lang=$langname;
      $langprior=$curprior;
    }
  }
}
if (strpos($lang,".")!==false || strpos($lang,"\\")!==false || strpos($lang,"/")!==false) unset($lang);

if (substr($action,0,3)!="do_" || getvar("preview") || getvar("more")) $do_mode=1;
else $do_mode=0;

// снижение приоритета UPDATE-операторов, если мы покказываем страницу, а не выполняем действие по обновлению
if ($GLOBALS['DBdriver']=='mysql' && (($GLOBALS['DBheavyload'] & 1)==1) && $do_mode==1) {
  $sql='SET LOW_PRIORITY_UPDATES=1';
  $res=&db_query($sql,$link);
}

$GLOBALS['inuser'] =& auth_process($lang);
$GLOBALS['inuserid'] =& $inuser['u_id'];

// Проверка на поискового бота
if ($GLOBALS['inuserid']<=3) {
  require('bots.php');
}

if ($inuserid>3) {
  $inuser['uw_count']=check_warnings($udata);
}

// Подгрузка языковых и стилевых модулей
load_lang("main.php");
if (!$do_mode || getvar('preview')) load_style("message.php");
load_lang("format.php");
load_lang("addons.php");
if ($do_mode) {
  load_style("main.php");
  load_style("common.php");
}
//setlocale(LC_ALL,$inuser['ln_locale']);

$passresult =& auth_checkpass($GLOBALS['inuser']);
if ($passresult==-1) error(MSG_e_u_ipchanged);
elseif ($passresult==-2) error(MSG_e_u_inactive);
elseif ($passresult==-3) error(MSG_e_badpassword);

$inuserbasic =& $inuser['u__level'];
if ($GLOBALS['inuserbasic']==1024 && $action!="do_logout") { // если пользователь -- System, отправляем его сразу в АЦ
  header("Location: ".$GLOBALS['opt_url']."/admin/index.php?IB2XPnew".$GLOBALS['DBprefix']."=".session_id());
  exit();
}
if ($GLOBALS['opt_status'] && $module!="profile" && $action!="do_login" &&
    $action!="login" && $inuserlevel<1000)
    if (trim($GLOBALS['opt_closetext'])) error($GLOBALS['opt_closetext']);
    else error(MSG_e_closed_status);

if (!$action && !$module && !$forum && !$topic && !getvar('ct') && $GLOBALS['opt_mainpage']) $forum=$GLOBALS['opt_mainpage'];

// Подгрузка данных о теме, если она передана в параметрах
if ($topic || $topicurl) {
  $sql = 'SELECT t.*, t.t__ratingsum/NULLIF(t__ratingcount,0) AS trating FROM  '.$GLOBALS['DBprefix'].'Topic t WHERE ';
  if ($topic) $sql.=' t_id="'.addslashes($topic).'"';
  else $sql.=' t_link="'.addslashes($topicurl).'"';
  $res =& db_query($sql,$link);
  if (db_num_rows($res)==0) {
    header('HTTP/1.1 404 Not Found');
    error(MSG_e_t_notexists,1);
  }
  $intopic =& db_fetch_array($res);
  db_free_result($res,$link);
  $GLOBALS['topic'] = $intopic['t_id'];
  if ($intopic['t_ratingcount']) $intopic['trating']=$intopic['t_ratingsim']/$intopic['t_ratingcount'];
  $intopic['pcount']=$intopic['t__pcount'];

  if (($GLOBALS['DBheavyload'] & 8)!=8) {
    // извлеченеи вспомогательных параметров темы -- наличия закладки, голосования и т.д.
    // таблица prefix_AdminEntry используется исключительно потому, что все остальные таблицы
    // должны присоединяться через LEFT JOIN, так как в них требуемой строки может и не быть
    $sql = 'SELECT bm.tid AS bmk, sb.tid AS subscr, v.pvid AS voted, tv.tid AS visited, pl.* '.
    ' FROM '.$GLOBALS['DBprefix']."AdminEntry ".
    'LEFT JOIN '.$GLOBALS['DBprefix'].'TopicView tv ON (tv.tid='.$topic.' AND tv.uid='.$GLOBALS['inuserid'].')'.
    'LEFT JOIN '.$GLOBALS['DBprefix'].'Bookmark bm ON (bm.tid='.$topic.' AND bm.uid='.$GLOBALS['inuserid'].') '.
    'LEFT JOIN '.$GLOBALS['DBprefix'].'Subscription sb ON (sb.tid='.$topic.' AND sb.uid='.$GLOBALS['inuserid'].') '.
    'LEFT JOIN '.$GLOBALS['DBprefix'].'Poll pl ON (pl_tid='.$topic.') '.
    'LEFT JOIN '.$GLOBALS['DBprefix'].'Vote v ON (v.tid='.$topic.' AND v.uid='.$GLOBALS['inuserid'].') '.
    'LIMIT 1';
    $res=&db_query($sql,$link);
    $tmp=&db_fetch_array($res);
    db_free_result($res);
    $intopic=array_merge($intopic,$tmp);
    unset($tmp);
  }
  else {
    $sql = 'SELECT tid FROM '.$GLOBALS['DBprefix'].'TopicView WHERE tid='.$topic.' AND uid='.$GLOBALS['inuserid'];
    $res=&db_query($sql,$link);
    list($tid)=db_fetch_row($res);
    db_free_result($res);
    $intopic['visited']=$tid;
    unset($tid);
  }

  $sql = 'SELECT p.p__time FROM '.$GLOBALS['DBprefix'].'Post p WHERE p.p_id='.$intopic['t__lastpostid'];
  $res=&db_query($sql,$link);
  list($lasttime)=db_fetch_row($res);
  db_free_result($res);
  $intopic['lasttime']=&$lasttime;
  unset($lasttime);

  $sql='SELECT p2.p_uid AS t_author FROM '.$GLOBALS['DBprefix'].'Post p2 WHERE p2.p_id='.$intopic['t__startpostid'];
  $res=&db_query($sql,$link);
  list($author)=db_fetch_row($res);
  db_free_result($res);
  $intopic['t_author']=&$author;
  unset($author);

  $GLOBALS['forum'] =& $intopic['t_fid'];
}

// Подгрузка данных о разделе, если он передан в параметрах
if ($forum || $forumurl) {
  $sql = "SELECT f.*, ct.*, tp.*, ua_level, lv_markall, lv_markcount, lv_time1, lv_time2 ".
  "FROM ".$GLOBALS['DBprefix']."ForumType tp, ".$GLOBALS['DBprefix']."Category ct, ".$GLOBALS['DBprefix']."Forum f ".
  "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=".$GLOBALS['inuserid']." AND ua.fid=f.f_id) ".
  "LEFT JOIN ".$GLOBALS['DBprefix']."LastVisit lv ON (lv.fid=f_id AND lv.uid=".$GLOBALS['inuserid'].") ".
  "WHERE f.f_tpid=tp.tp_id AND f.f_ctid=ct.ct_id ".
  "AND ".check_access('f_id');
  if ($forum) $sql.=' AND f.f_id="'.addslashes($forum).'"';
  else $sql.=' AND f.f_link="'.addslashes($forumurl).'"';
  $sql.=' LIMIT 1';
  $res =& db_query($sql,$link);
  if (db_num_rows($res)==0) {
    header('HTTP/1.1 404 Not Found');
    if (!$topic) error(MSG_e_f_notexists);
    else error(MSG_e_t_notexists);
  }
  $inforum =& db_fetch_array($res);
  db_free_result($res,$link);
  $GLOBALS['forum']=&$inforum['f_id'];

  if (!$intopic) {
    $sql = 'SELECT p.p__time FROM '.$GLOBALS['DBprefix'].'Post p WHERE p.p_id='.$inforum['f__lastpostid'];
    $res=&db_query($sql,$link);
    list($lasttime)=db_fetch_row($res);
    db_free_result($res);
    $inforum['lasttime']=&$lasttime;
    unset($lasttime);
  }

  $GLOBALS['inuser']['lv_markall']=&$inforum['lv_markall'];
  $GLOBALS['inuser']['lv_markcount']=&$inforum['lv_markcount'];
  $GLOBALS['inuser']['lv_time1']=&$inforum['lv_time1'];
  $GLOBALS['inuser']['lv_time2']=&$inforum['lv_time2'];

  if ($inforum['ua_level']>$inuserbasic && $inuserbasic!=-1) $inuserlevel=$inforum['ua_level'];
  else $inuserlevel=$inuserbasic;
  if (!$module) {
    $module = $inforum['tp_library'];
  }
  $flevel=$inforum['f_lmoderate'];

// принудительный редирект на новый вариант написания URL (со ссылок вида ?t=номер\
// или ссылок вида /раздел/номер/ на /раздел/название, если оно есть
  if ($GLOBALS['opt_hurl'] && strtoupper($_SERVER['REQUEST_METHOD'])=="GET") {
    if ((strpos($_SERVER['REQUEST_URI'],'/index.php')!==false && $intopic) ||
      ($intopic && (($intopic['t_link'] && !$topicurl) || ($inforum['f_link'] && !$forumurl)))) {
      $newurl=$GLOBALS['opt_url'];
      if (substr($newurl,-1,1)!='/') $newurl.='/';
      $newurl.=build_url($intopic);
      if (isset($_GET['p'])) $newurl.='p'.$_GET['p'].'.htm';
      elseif (isset($_GET['st'])) $newurl.=$_GET['st'].'.htm';
      $qstr = $_SERVER['QUERY_STRING'];
      $qstr = str_replace('t='.$intopic['t_id'],'',$qstr);
      $qstr = str_replace('f='.$intopic['t_fid'],'',$qstr);
      $qstr = str_replace('st='.$_GET['st'],'',$qstr);
      $qstr = str_replace('p='.$_GET['p'],'',$qstr);
    }
    elseif ((strpos($_SERVER['REQUEST_URI'],'/index.php')!==false && $inforum) ||
      ($inforum && $inforum['f_link'] && !$forumurl)) {
      $newurl=$GLOBALS['opt_url'];
      if (substr($newurl,-1,1)!='/') $newurl.='/';
      $newurl.=build_url($inforum);
      if ($GLOBALS['action']=='f_rules') $newurl.='f_rules.htm';
      elseif (isset($_GET['st'])) $newurl.=$_GET['st'].'.htm';
      $qstr = $_SERVER['QUERY_STRING'];
      $qstr = str_replace('f='.$inforum['f_id'],'',$qstr);
      $qstr = str_replace('st='.$_GET['st'],'',$qstr);
    }
    if ($newurl) {
      if ($qstr) $newurl.='?'.$qstr;
      $newurl=str_replace('?&','?',$newurl);
      $newurl=str_replace('&&','&',$newurl);
      header('HTTP/1.1 301 Moved Permanently');
      header('Location: '.$newurl);
      db_close($link);
      exit();
    }
  }

  build_mod_list($forum,$flevel);
}
else $inuserlevel=$inuserbasic;

// Фиксация даты последнего визита в раздел
if ($inuserid>3 && $action!="do_mark_read") {
  $userlast1=$GLOBALS['inuser']['lv_time1'];
  $userlast2=$GLOBALS['inuser']['lv_time2'];
  if (!$GLOBALS['opt_visittime']) $GLOBALS['opt_visittime']=120;
  if ($userlast1<$curtime-$GLOBALS['opt_visittime']*60) $userlast2=$userlast1;
  $userlast1=$curtime;
  if (!$userlast2) $userlast2=0;

  $sql = "UPDATE ".$GLOBALS['DBprefix']."LastVisit SET  lv_time1=$userlast1, lv_time2=$userlast2 WHERE uid=$inuserid AND fid=$forum";
  $res=&db_query($sql,$link);
  if (db_affected_rows($res)==0) {
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."LastVisit WHERE uid=$inuserid AND fid=$forum";
    $res =& db_query($sql,$link);
    $sql = "INSERT INTO ".$GLOBALS['DBprefix']."LastVisit (uid,fid,lv_time1,lv_time2,lv_markall,lv_markcount) ".
    "VALUES ($inuserid,$forum,$userlast1,$userlast2,".intval($GLOBALS['inuser']['lv_markall']).",".intval($GLOBALS['inuser']['lv_markcount']).")";
    $res=&db_query($sql,$link);
  }
}

// Проверка модуля и действия
if (!$module) $module = "main";
if (!$action && !$forum) $action ="view";
elseif (!$action && $forum) $action = $inforum['tp_template']."_view";

if ($module!="main" || getvar('ct')!=0 || $forum!=0) $locations=array("<a href=\"index.php\">$opt_title</a>");
else $locations=array();

// Подгрузка модуля и стиля к нему
if (!is_file($opt_dir."/".$module.".php")) global_error(MSG_e_nomodule." ".$module.".php");
load_style("$module.php");
require ($opt_dir."/".$module.".php");

if ($module==$inforum['tp_template']) $locations=call_user_func($module."_locations",$locations);
else $locations=locations($locations);

if ($topic) $lasttime=$intopic['lasttime'];
elseif ($forum && !$topic) $lasttime=$inforum['lasttime'];
else $lasttime=$curtime;
$lasttime=max($lasttime,$_SESSION['login_time']);

if (isset($_POST['continue'])) {
  main_action();
  header("HTTP/1.1 204 No Content");
  exit();
}

// Проверка на то, что нужно вывести статус 304 (если в теме/разделе не было изменений за последние 21 день)
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  $condtime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
  if ($condtime>0 && $condtime>$lasttime && $lasttime<($curtime-21*24*60*60)) {
    header("HTTP/1.1 304 Not Modified");
    db_close();
    exit();
  }
}

// Вывод заголовка
header("HTTP/1.1 200 OK");
header("Content-Type: text/html; charset=".$GLOBALS['inuser']['ln_charset']);
if ($GLOBALS['inuserid']<3) header("Cache-Control: public, must-revalidate");
else header("Cache-Control: private, must-revalidate");
if ($lasttime>($curtime-21*24*60*60) || !$lasttime) $lasttime=$curtime;
header("Last-Modified: ".date("r",$lasttime));
//header("Expires: ".date("r",time()+60));
if (strtoupper($_SERVER['REQUEST_METHOD'])=='HEAD') {
  db_close();
  exit();
}

// Выполнение операций с логами и списками присутствующих
$ip = iptonum(getip());
if ($opt_log==2 || ($opt_log==1 && $inuserid>3)) {
  $sid = session_id();
  $fname=log_file_name($curtime);
  $fh=fopen($fname,'a');
  flock($fh,LOCK_EX);
  fputs($fh,$GLOBALS['inuserid'].'|'.$GLOBALS['inuser']['u__name'].'|'.getip().'|'.md5($sid.$_SERVER['HTTP_USER_AGENT']).'|'.$curtime.'|'.$GLOBALS['action'].'|'.$GLOBALS['module'].'|'.$GLOBALS['forum'].'|'.$GLOBALS['topic'].'|'.$_SERVER['HTTP_REFERER'].'|'.$_SERVER['HTTP_USER_AGENT']."\n");
  fclose($fh);
}

// Фиксация пользователя в таблице присутствующих
// Удаляем старые записи об этом пользователе, если он только что вошел, чтобы не было дублей
if (isset($_POST['inusername']) && $GLOBALS['inuserid']>3) {
  $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Present WHERE pu_uid=".$GLOBALS['inuserid'];
  $res=&db_query($sql,$link);
}

$sql = "UPDATE ".$GLOBALS['DBprefix']."Present SET pu_ip=".$ip.', '.
'pu_uname="'.$GLOBALS['inuser']['u__name'].'", pu_lasttime='.$curtime.', '.
'pu_module="'.$GLOBALS['module'].'", pu_action="'.$GLOBALS['action'].'", pu_tid="'.$topic.'", pu_fid="'.$forum.'", '.
'pu_hits=pu_hits+1, pu_uid='.$GLOBALS['inuserid'].', pu_hidden='.$GLOBALS['inuser']['u_hidden'].' ';
if (isset($_POST['inusername']) && $GLOBALS['inuserid']>3) {
  $sql2=$sql.'WHERE pu_uid=1 AND pu_ip='.$ip;
}
elseif ($GLOBALS['inuserid']>3) $sql2=$sql.'WHERE pu_uid='.$GLOBALS['inuserid'];
else $sql2=$sql.'WHERE pu_uid=1 AND pu_ip='.$ip;
$res=&db_query($sql2,$link);

// если подходящей записи не было обнаружено
if (db_affected_rows($res)==0) {
  $sql = "INSERT INTO ".$GLOBALS['DBprefix']."Present SET pu_ip=".iptonum(getip()).', '.
  'pu_uname="'.$GLOBALS['inuser']['u__name'].'", pu_lasttime='.$curtime.', '.
  'pu_module="'.$GLOBALS['module'].'", pu_action="'.$GLOBALS['action'].'", pu_tid="'.$topic.'", pu_fid="'.$forum.'", '.
  'pu_uid='.$GLOBALS['inuserid'].', pu_hits=1, pu_hidden='.$GLOBALS['inuser']['u_hidden'];
  $res=&db_query($sql,$link);
}

// Очистка таблицы присутствующих и кеша пользователей от устарвеших записей
$todaytime=mktime(0,0,0,date('m',$curtime),date('d',$curtime),date('Y',$curtime));
if ($GLOBALS['opt_logclean']<$todaytime) {
  $oldtime = mktime(0,0,0,date('m',$curtime),date('d',$curtime)-$GLOBALS['opt_keeplogs'],date('Y',$curtime));
  $oldfname=log_file_name($oldtime);
  if (file_exists($oldfname)) unlink ($oldfname);

  $sql ="DELETE FROM ".$GLOBALS['DBprefix']."Present WHERE pu_lasttime<".($GLOBALS['curtime']-2*24*60*60);
  $res=&db_query($sql,$link);

  $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Online";
  $res=&db_query($sql,$link);

  $GLOBALS['opt_logclean']=$GLOBALS['curtime'];
  options_save();
}

// Вызов основного шаблона
if ($do_mode) {
  if ($GLOBALS['inuser']['st_integrated']==1) require($opt_dir.'/styles/'.$GLOBALS['inuser']['st_file'].'/template.php');
  else require($opt_dir."/config/tmplate1.php");
}
else require($opt_dir."/config/tmplate2.php");

ob_end_flush();
db_close($link);
exit();

function main_action() {
  $funcs = get_defined_functions();
  if (array_search($GLOBALS['action'],$funcs['user'])===false) global_error("Undefined action: ".$GLOBALS['action'],1);
  if (!isset($_POST['continue'])) ob_flush();
  call_user_func($GLOBALS['action']);
  session_write_close();
}

function time_diff() {
  $curtime = microtime();
  $tdif = gettimedif($GLOBALS['start_time'],$curtime);
  main_time_diff(sprintf("%.4f",$tdif),$GLOBALS['query_count'],sprintf("%.4f",$GLOBALS['query_time']));
}

function menu() {
  $link = $GLOBALS['link'];
  if ($GLOBALS['opt_submenu']) $menusql="AND tp_menu=1";
  else $menusql="AND f_parent=0";
  $sql = "SELECT ct.ct_name,ct.ct_id,f.f_title,f.f_id FROM ".$GLOBALS['DBprefix']."Category ct, ".$GLOBALS['DBprefix']."Forum f, ".$GLOBALS['DBprefix']."ForumType tp ".
  "WHERE f.f_ctid=ct.ct_id AND f_tpid=tp_id $menusql AND ".check_access('f_id').
  " ORDER BY ct_sortfield,f_sortfield";
  $res =& db_query($sql,$link);
  menu_start();
  while ($fdata=&db_fetch_array($res)) {
    if ($fdata['ct_name']!=$oldcat) {
      if ($oldcat) menu_cat_end();
      menu_cat_entry($fdata);
      $oldcat=$fdata['ct_name'];
    }
    menu_entry($fdata);
  }
  menu_cat_end();
  menu_end();
}

function announce($id='') {
  if ($GLOBALS['opt_announce']==2 || ($GLOBALS['opt_announce']==1 && $GLOBALS['module']=="main" && $GLOBALS['action']=="view")) {
    announce_form($id);
  }
}

function err_handler($errno, $errstr, $errfile, $errline) {
  if ($errno & (E_ALL ^ E_NOTICE) && $errno!=2) {
    $errfile = substr($errfile,strrpos($errfile,"/")+1);
    global_error("$errfile (line $errline)"." - ".$errstr." ($errno) ");
  }
}

function global_error($errtext,$notfound=0) {
  global $link;
  if ($link) db_close($link);
  if (!headers_sent()) {
    if (!$notfound) header('HTTP/1.1 503 Service Unavailable');
    else header('HTTP/1.1 404 Not Found');
  }
  $fh=fopen("config/error.log","a");
  $errtext=str_replace("\r","",$errtext);
  $errtext=str_replace("<br />","\n",$errtext);
  $str="Date: ".date("r",time()).", IP: ". $_SERVER['REMOTE_ADDR'].",".$_SERVER['HTTP_X_FORWARDED_FOR'];
  $str.=", User: ".$GLOBALS['inuserid']." - ".$GLOBALS['inuser']['u__name'];
  $str.=", Module: ".$GLOBALS['module'].", Action: ".$GLOBALS['action'];
  $str.=", Request string: ".$_SERVER['REQUEST_URI']."\n".$errtext."\n";
  fputs($fh,$str);
  fclose($fh); ?>
<html><head><title><?=$opt_title;?></title>
<link rel="stylesheet" href="styles/abstract/abstract.css" type="text/css">
</head>
<body bgcolor="#DCDCDC">
<table border="0" cellspacing="1" class="innertable" align=center border=1 width="90%"><tr>
<td class="tablehead">GLOBAL FORUM ERROR: <?=nl2br(str_replace("&amp;quot;","&quot;",htmlspecialchars($errtext)));?>
<tr>
<td><ul><li><a href="<?=$_SERVER['HTTP_REFERER'];?>">Goto previous page</a>
<li><a href="index.php">Goto main page</a></li>
</table></body></html>
<? exit();
}

function check_point($name) {
  $GLOBALS['checkpoints'][$name]=sprintf("%.4f",gettimedif($GLOBALS['start_time'],microtime()));
}

function list_checks() {
  if (is_array($GLOBALS['checkpoints'])) {
    foreach ($GLOBALS['checkpoints'] as $name=>$value) echo "$name - $value<br>";
  }
}

function gettimedif($start,$stop) {
    list($startusec,$startsec) = explode(" ",$start);
    list($stopusec,$stopsec) = explode(" ",$stop);
    return ($stopsec-$startsec)+($stopusec-$startusec);
}
