Location: PHPKode > projects > YW-GuestBook > YW Guestbook 1.45/YW Guestbook/ywgb/index.php
<?php
  //-------------------------------------------------------------------------
  //                             YW Guestbook
  //                                index.php
  //
  //-------------------------------------------------------------------------
  //  This program is free software. You can redistribute it and/or modify
  //  it under the terms of the License that was distributed with this file!
  //-------------------------------------------------------------------------

  //------------------------------------------------------------------
  // change the following constants if you want to include the script
  // see 3) in readme.txt for details !!!
  //------------------------------------------------------------------

  define ( "MAINSCRIPT",  "" ); // Your MAINSCRIPT is the top-level
                                // script that includes this index.php

  define ( "SCRIPTPATH",  "" ); // Relative path from MAINSCRIPT to index.php
                                // in your guestbook directory

  define ( "PFIX", "" ); // A prefix for the guestbook parameters to avoid name
                         // conflicts with your MAINSCRIPT

  //------------------------------------------------------------------

  define ( "UNREGISTERAFTERMINUTE" , "15" );
  define ( "HOSTNAMERESOLVING" , "1" ); // try to set this constant to 0 
                                        // if your guestbook is too slow
  
  //*********************************************************************
  //                          main-routine
  //*********************************************************************

  global $skinDir,$maxPage,$settings,$browsers,$systems,$maxEntry,$showPrivate,
    $emoticons,$errorMSG,$entry,$statusMSG,$boxes,$ratings,$fields,$custom,
    $arg,$_param,$maxPagelinks,$cl,$rotation,$rotationList,$optional,$required,
    $user,$_form,$showPreview,$statusMSG,$oldFilename,$parameters,$decode,
    $mySQL_Host,$mySQL_User,$mySQL_Password,$mySQL_Database,$Prefix,$mySQL,
    $badwords,$_spaces,$BBCodes,$allCodes,$allIndex,$lang,$langC,$screenparam,
    $entryfilter,$singlepage,$entry_backup,$ratings_backup,$custom_backup,
    $filteradd,$_entry,$_custom,$_ratings,$skininfo,$incpath,$_IP,$relpath,$bbmask,
    $ent_codes,$ord_replace,$bbco,$bbst,$bbcc,$bben,$st,$lip,$burl,$ucol,$ufont,$charmap;

  $incpath = SCRIPTPATH;
  @include($incpath."functions.php");
  if (!function_exists("vgb_getParameters")) {
    $incpath = "";
    @include($incpath."functions.php");
    if (!function_exists("vgb_getParameters")) {
      if ((MAINSCRIPT == "") && (SCRIPTPATH == ""))
        die ("<center><b>If you want to include the Guestbook, you must change the
             constants at the top of index.php !</b><br />See readme.txt for details
             </center>");
      else
        die ("<center><b>Inclusion error !</b><br />You've either opened index.php instead
             of your mainscript or the include constants have wrong values.</center>");
    }
  }
  if (MAINSCRIPT == "") 
    define ( "MSCRIPT" , "index.".EXT );
  else 
    define ( "MSCRIPT" , MAINSCRIPT );
    
  vgb_getParameters();
  $screenparam = "vgbxiferp=".PFIX;

  // check for forced language
  $langID = (isset($arg[PFIX."lang"])) ? $arg[PFIX."lang"] : "";
  if ($langID != "")
    $screenparam .= "&amp;".PFIX."lang=".urlencode($langID);


  // include the language-package
  $relpath = SCRIPTPATH;
  if (!file_exists($relpath."lang/langindex".$langID.".inc")) {
    $relpath = "";
    if (!file_exists($relpath."lang/langindex".$langID.".inc")) {
      echo "<center>Missing file: <b>".SCRIPTPATH."lang/langindex".
           $langID.".inc</b> !<br /><br />";
      if ((MAINSCRIPT == "") && (SCRIPTPATH == ""))
        die ("<b>If you want to include the Guestbook,
             you must change the constants at the top of index.php !</b><br />See
             readme.txt for details</center>");
      else
        die ("<center><b>Inclusion error !</b><br />You've either opened index.php instead
               of your mainscript or the include constants have wrong values.</center>");
    }
  }
  include($incpath."lang/langindex".$langID.".inc");

  vgb_connectDB($relpath,$incpath);

  if (($settings['ENCODING'] != "") && (SCRIPTPATH == "") && (MAINSCRIPT == ""))
    header("Content-Type: text/html; charset=".$settings['ENCODING']);

  // register visitor
  vgb_registerVisitor();

  if ($settings['ASKCOUNTRY']) {
    if (!file_exists($relpath."lang/langcountry".$langID.".inc"))
      die("<center>Missing file: <b>".$relpath."lang/langcountry".
          $langID.".inc</b> !</center>");
    include($incpath."lang/langcountry".$langID.".inc");
  }
  if (file_exists($relpath."lang/langspecial".$langID.".inc"))
    include($incpath."lang/langspecial".$langID.".inc");

  // set important variables
  vgb_initDetection();
  if ($settings[$Prefix.'ID1'] == "")
    $settings[$Prefix.'ID1'] = 'bG9hZFNraW4oIm5vRnJhbWVzLnBocCIpO2lmKCRjbCE9M'.
                               'yllcnJvcigkbGFuZ1snbm9Db3B5J10pOw==|ZWNobyI8Y'.
                               'j5WaVBFUiBHdWVzdGJvb2sgViIuJHNldHRpbmdzWydWRV'.
                               'JTSU9OJ10uIjwvYj4gLSA';
  if ($settings[$Prefix.'ID2'] == "")
    $settings[$Prefix.'ID2'] = 'mY29weTsgMjAwNCBieSBNYXJjIFN0ZWluIjskY2x8PSAx'.
                               'Ow==|b3V0KCI8YSBocmVmPSdodHRwOi8vd3d3LnZpcGVy'.
                               'Z2IuZGUudnUnIHRhcmdldD0nX2JsYW5rJyIuIiAkaW5UY'.
                               'Wc+d3d3LnZpcGVyZ2IuZGUudnU8L2E+Iik7JGNsfD0yOw==';
  $settings['VGBID'] = $settings[$Prefix.'ID1'].$settings[$Prefix.'ID2'];

  // get the list of the defined rating-boxes
  $boxes = array();
  $query = vgb_query("select ID, NAME, FRCE from VGB_RATINGBOX");
  while ($row = vgb_result($query)) {
    $boxes[] = $row;
  }

  // get the list of the defined custom-fields
  $fields = array();
  $query = vgb_query("select * from VGB_CUSTOMFIELD");
  while ($row = vgb_result($query)) {
    $fields[] = $row;
  }

  $filteradd = "";
  $entryfilter = ($settings['MODERATEDMODE']) ? "e.UNMODERATED = 0" : "";
  if ($settings['ALLOWSEARCH']) {
    // check entry filtering parameters
    if (isset($arg[PFIX.'filterpicture']))
      $entryfilter .= ($entryfilter == "") ? " not isnull(e.PICTURE)" :
                                            " and not isnull(e.PICTURE)";
    vgb_addFilter("name");
    vgb_addFilter("text","ENTRY");
    vgb_addFilter("email");
    vgb_addFilter("homepage");
    vgb_addFilter("icq");
    vgb_addFilter("msn");
    vgb_addFilter("aim");
    vgb_addFilter("yahoo");
    if (isset($arg[PFIX.'filtercountry']) && ($arg[PFIX.'filtercountry'] != "")) {
      $arg[PFIX.'filtercountry'] = intval($arg[PFIX.'filtercountry']);
      $entryfilter .= ($entryfilter == "") ?
        " e.COUNTRY = ".$arg[PFIX.'filtercountry'] :
        " and e.COUNTRY = ".$arg[PFIX.'filtercountry'];
      
    }
    if (isset($arg[PFIX.'filterrating'])) {
      foreach($arg[PFIX.'filterrating'] as $boxid => $value ) {
        if ($value != "") {
          $boxid = intval($boxid);
          $value = intval($value);
          if ($entryfilter != "")
            $entryfilter .= " and";
          $entryfilter .= " r$boxid.BOX_ID = $boxid and r$boxid.ENTRY_ID = e.ID and r$boxid.RATING = ".addSlashes($value);
          $filteradd .= ", VGB_RATING r$boxid ";
        }
      }
    }
    if (isset($arg[PFIX.'filtercustom'])) {
      foreach($arg[PFIX.'filtercustom'] as $customid => $value ) {
        $cf = null;
        foreach ($fields as $f) 
          if ($f['ID'] == $customid)
            $cf = $f;
                
        if (!is_null($cf) && ($value != "")) {
          $value = trim($value);
          if ($cf['TYPE'] != 2) {
            if ($value[0] != "%")
              $value = "%".$value;
            if ($value[strlen($value)-1] != "%")
              $value .= "%";
          }          
          if ($entryfilter != "")
            $entryfilter .= " and";
          $customid = intval($customid);
          $entryfilter .= " c$customid.FIELD_ID = $customid and c$customid.ENTRY_ID = e.ID and c$customid.CONTENT like '".addSlashes($value)."'";
          $filteradd .= ", VGB_CUSTOMENTRY c$customid ";
        }
      }
    }
  }

  if ($entryfilter != "")
    $entryfilter = " where ".$entryfilter;

  $query = vgb_query("select * from VGB_ENTRY e $filteradd".$entryfilter);
  if (($maxEntry=(vgb_numrows($query))) == 0)
    $maxPage = 0;
  else {
    $maxPage = (int)($maxEntry/$settings['MAXENTRIESPERPAGE']);
    if ($maxEntry%$settings['MAXENTRIESPERPAGE'] != 0)
      $maxPage++;
  }

  $emoticons = array();
  $query = vgb_query("select * from VGB_EMOTICON order by PRIORITY asc");
  while ($emoticon = vgb_result($query)) {
    $emoticons[] = array($emoticon['CODE'],$emoticon['FILENAME']);
  }

  $optional = "";
  $required = "";
  $_form = 0;
  $maxPagelinks = 0;
  $cl = 0;

  $forcedSkin = (isset($arg[PFIX.'skindir'])) ? $arg[PFIX.'skindir'] : null;
  if (!is_null($forcedSkin))
    $screenparam .= "&amp;".PFIX."skindir=".urlencode($forcedSkin);
  vgb_setSkinDir($relpath,$forcedSkin);

  // check for forced Non-/Framemode
  if (isset($arg[PFIX."framemode"])) {
    if ($arg[PFIX."framemode"] == 0)
      $settings['USEFRAMES'] = false;
    elseif ($arg[PFIX."framemode"] == 1)
      $settings['USEFRAMES'] = true;
  }

  if (file_exists($relpath.$skinDir."skininfo.php")) {
    include($incpath.$skinDir."skininfo.php");
    if (isset($skininfo['LANGINC']) && $skininfo['LANGINC']) {
      if (file_exists($relpath.$skinDir."lang.inc")) {
        include($incpath.$skinDir."lang.inc");
      }
    }
    if (isset($skininfo['STYLEINC']) && $skininfo['STYLEINC']) {
      if (file_exists($relpath.$skinDir."style.inc")) {
        include($incpath.$skinDir."style.inc");
      }
    }
  }

  if (!isset($skininfo['MODE']))
    $skininfo['MODE'] = 0;
  elseif ($skininfo['MODE'] == 1)
    $settings['USEFRAMES'] = 1;
  elseif ($skininfo['MODE'] > 1)
    $settings['USEFRAMES'] = 0;
  $singlepage = ($skininfo['MODE'] == 3);


  // search for unknown variables
  $_param = "";
  $_paramlist = array (PFIX."show",PFIX."display",PFIX."page",
                       PFIX."preview",PFIX."preview_x",PFIX."send",
                       PFIX."stats",PFIX."menu",PFIX."detail",
                       PFIX."select",PFIX."PRIVATE", PFIX."decode",
                       PFIX."send_x",PFIX."inputmask",PFIX."mask",
                       PFIX."ENTRY","MAX_FILE_SIZE",PFIX."NAME",
                       PFIX."EMAIL",PFIX."HOMEPAGE",PFIX."ICQ",
                       PFIX."COUNTRY",PFIX."AIM",PFIX."MSN",
                       PFIX."HIDEEMAIL",
                       PFIX."YAHOO",PFIX."PICTURE",PFIX."PICTEXT");
  $_b = true;
  foreach ($arg as $_key => $_val) {
    if ((!in_array($_key,$_paramlist)) &&
        (!ereg("^".PFIX."CUSTOM",$_key)) &&
        (!ereg("^".PFIX."RATING",$_key))) {
      if (is_array($_val)) {
        foreach ($_val as $_inkey => $_inval) {
          $_param .= "&amp;".urlencode($_key)."[".
          urlencode($_inkey)."]=".urlencode($_inval);
        }
      }
      else {
        $_param .= "&amp;".urlencode($_key)."=".urlencode($_val);
      }
    }
    elseif ($_key != PFIX."decode")
      $_b = false;
  }

  // secret parameter ?
  $_p = explode(".",$_IP);
  $sessionIP = $_p[0].".".$_p[1].".".$_p[2];
  $_pparam = (!is_null($settings['PRIVPARAMETER'])) ?
    explode("=",$settings['PRIVPARAMETER'],2) : array();
  if (($settings['ASKPRIVATE']) && ((count($_pparam) != 0) && (isset($arg[$_pparam[0]])) &&
                    ($arg[$_pparam[0]] == $_pparam[1]))) {
    $sessionID = substr(md5(uniqid(rand())),0,20);
    vgb_query("insert into VGB_LOGIN values('".$sessionIP."',now(),0,0,'".$sessionID."')");

    $_param = str_replace("&amp;".urlencode($_pparam[0])."=".urlencode($_pparam[1]),"",$_param);
    $url = "http://".$settings['INDEXURL'];
    if ($url[strlen($url)-1] == "/")
      $url .= "index.".EXT;
    if (strpos($url,"?") == 0)
      $url .= "?";
    $url .= $_param."&amp;".PFIX."decode=".urlencode($sessionID);
    if ((SCRIPTPATH == "") && (MAINSCRIPT == ""))
      echo "<!DOCTYPE html
              PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
              \"DTD/xhtml1-transitional.dtd\">
            <html style='height: 100%'>
            <head>
              <title>".$lang['login']."</title>
              <meta http-equiv='refresh' content='0; URL=$url' />
            </head>

            <body style='height: 100%'>";
    echo "<table width='100%' style='height: 100%'>
          <tr>
            <td valign='middle' align='center'>
            <a href='$url' class='bglink'>Click here if you're not redirected</a>
            </td>
          </tr>
          </table>
          <script language='javascript'>
          <!--
          window.location='".str_replace("&amp;","&",$url)."';
          //-->
          </script>";
    if ((SCRIPTPATH == "") && (MAINSCRIPT == ""))
      echo "</html>";
    exit();
  }

  // check  for decoding
  $showPrivate = -1;
  $decode = (isset($arg[PFIX.'decode'])) ? addSlashes($arg[PFIX.'decode']) : "";
  if  ($decode != "") {
    $query = vgb_query("select * from VGB_LOGIN where IP = '".$sessionIP."' and SESSIONID = '".$decode."'");
    if (vgb_numrows($query) > 0) {
      vgb_query("update VGB_LOGIN set TIMESTAMP = now() where SESSIONID = '".$decode."'");
      $_l = vgb_result($query);
      $showPrivate = $_l['ENTRYID'];
      $_param .= "&amp;".PFIX."decode=".urlencode($decode);
      $screenparam .= "&amp;".PFIX."decode=".urlencode($decode);
    }
  }
  if (!$settings['ASKPRIVATE'])
    $showPrivate = 0;

  // if no parameters are given show the guestbook entries
  if ($_b)
    $arg[PFIX.'show'] = 1;

  // set the commands to a valid page
  if (isset($arg[PFIX.'show']))
    vgb_validPage($arg[PFIX.'show']);
  if (isset($arg[PFIX.'display']))
    vgb_validPage($arg[PFIX.'display']);
  if (isset($arg[PFIX.'page']))
    vgb_validPage($arg[PFIX.'page']);
  if (isset($arg[PFIX.'preview']))
    vgb_validPage($arg[PFIX.'preview']);

  // check for the send or preview command
  if (isset($arg[PFIX.'send']) || isset($arg[PFIX.'send_x']) ||
     isset($arg[PFIX.'preview']) || isset($arg[PFIX.'preview_x'])) {

    // we´re still on the inputmask
    if ($settings['USEFRAMES'])
      $arg[PFIX.'mask'] = 1;
    else
      $arg[PFIX.'inputmask'] = 1;

    // set all parameters which are not set
    $errorMSG = "";
    $parameters = array( PFIX."NAME", PFIX."ENTRY", PFIX."EMAIL",
                         PFIX."HOMEPAGE", PFIX."ICQ", PFIX."AIM",
                         PFIX."MSN", PFIX."YAHOO", PFIX."COUNTRY",
                         PFIX."PICTEXT", PFIX."PRIVATE" );
    foreach($boxes as $box) {
      $parameters[] = PFIX."RATING".$box['ID'];
    }
    foreach($fields as $field) {
      $parameters[] = PFIX."CUSTOM".$field['ID'];
    }

    foreach($parameters as $parameter) {
      if (!isset($arg[$parameter]))
        $arg[$parameter] = "";
    }

    // preset the inputs
    $entry['ID'] = 0;
    $entry['NAME'] = trim($arg[PFIX.'NAME']);
    $entry['EMAIL'] = trim($arg[PFIX.'EMAIL']);
    $entry['HOMEPAGE'] = trim($arg[PFIX.'HOMEPAGE']);
    if (strtoupper(substr($entry['HOMEPAGE'],0,7)) == "HTTP://")
      $entry['HOMEPAGE'] = trim(substr($entry['HOMEPAGE'],7));
    $entry['PICTEXT'] = trim($arg[PFIX.'PICTEXT']);
    $entry['ICQ'] = intval($arg[PFIX.'ICQ']);
    $entry['AIM'] = trim($arg[PFIX.'AIM']);
    $entry['MSN'] = trim($arg[PFIX.'MSN']);
    $entry['YAHOO'] = trim($arg[PFIX.'YAHOO']);
    $entry['ENTRY'] = trim($arg[PFIX.'ENTRY']);
    $entry['HIDEEMAIL'] = (isset($arg[PFIX.'HIDEEMAIL'])) ? intval($arg[PFIX.'HIDEEMAIL']) : 0;
    $entry['PRIVATE'] = trim($arg[PFIX.'PRIVATE']);
    $today = getdate(time());
    if (strlen($today['mon']) == 1)
      $today['mon'] = "0".$today['mon'];
    $entry['DATE'] = $today['year']."-".$today['mon']."-".
                     $today['mday'];
    $now = localtime(time(),1);
    if (strlen($now['tm_sec']) == 1)
      $now['tm_sec'] = "0".$now['tm_sec'];
    if (strlen($now['tm_min']) == 1)
      $now['tm_min'] = "0".$now['tm_min'];
    if (strlen($now['tm_hour']) == 1)
      $now['tm_hour'] = "0".$now['tm_hour'];
    $entry['SIGNTIME'] = $now['tm_hour'].":".$now['tm_min'].":".$now['tm_sec'];
    $entry['IP'] = $_IP;
    if (($entry['IP'] == "0.0.0.0") || !HOSTNAMERESOLVING)
      $entry['HOSTNAME'] = "unknown";
    else
      $entry['HOSTNAME'] = gethostbyaddr($entry['IP']);
    $entry['COUNTRY'] = intval($arg[PFIX.'COUNTRY']);
    $entry['NUMBER'] = $maxEntry+1+$settings['PASTENTRIES'];
    $entry['BROWSER'] = ((getenv("HTTP_USER_AGENT") == "") && (isset($_SERVER['HTTP_USER_AGENT'])))
      ? $_SERVER['HTTP_USER_AGENT'] : getenv("HTTP_USER_AGENT");
    $entry['COMMENT'] = null;

    $ratings = array();
    foreach ($boxes as $box) {
      if (isset($arg[PFIX."RATING".$box['ID']])) {
        $arg[PFIX."RATING".$box['ID']] = "".intval($arg[PFIX."RATING".$box['ID']]);
        if ($arg[PFIX."RATING".$box['ID']] != 0)
          $ratings[$box['ID']] = $arg[PFIX."RATING".$box['ID']];

        $entry["RATING".$box['ID']] = $arg[PFIX."RATING".$box['ID']];
      }
    }
    $custom = array();
    foreach ($fields as $field) {
      if (isset($arg[PFIX."CUSTOM".$field['ID']])) {
        if ($arg[PFIX."CUSTOM".$field['ID']] != "")
          $custom[$field['ID']] =
            trim($arg[PFIX."CUSTOM".$field['ID']]);
        $entry["CUSTOM".$field['ID']] =
           trim($arg[PFIX."CUSTOM".$field['ID']]);
      }
    }

    // check the single parameters
    $entry['PICTURE'] = "";
    vgb_checkParameter();
    foreach (array("EMAIL","HOMEPAGE","ICQ","AIM","PRIVATE",
                   "MSN","YAHOO","COUNTRY","PICTEXT","PICTURE") as $name) {
      if ($entry[$name] == "")
        $entry[$name] = null;
      if ($_entry[$name] == "")
        $_entry[$name] = null;
    }

    // check for duplicates
    if (!$errorMSG) {
      $query = vgb_query("select NAME from VGB_ENTRY where NAME = '".
      addSlashes($entry['NAME'])."' and ENTRY = '".
      addSlashes($entry['ENTRY'])."'");
      if (vgb_numrows($query) != 0)
        $errorMSG = $lang['duplicate'];
    }

    // do we have an uploaded picture ?
    if (isset($arg[PFIX.'PICTURE'])) {
      if (file_exists($relpath."upload/".$arg[PFIX.'PICTURE'])) {
        // move preview-picture to upload directory
        $_pic = explode("/",$arg[PFIX.'PICTURE']);
        if (@copy($relpath."upload/".$arg[PFIX.'PICTURE'],$relpath."upload/".$_pic[1])) {
          $entry['PICTURE'] = $_pic[1];
          @unlink($relpath."upload/".$arg[PFIX.'PICTURE']);
          chmod($relpath."upload/".$entry['PICTURE'],0666);
        }
      }
    }
    elseif ($settings['ASKPICTURE'] &&
       (isset($GLOBALS['HTTP_POST_FILES'][PFIX.'UPLOAD']))) {
       $tempfile = $GLOBALS['HTTP_POST_FILES'][PFIX.'UPLOAD'];
       $oldFilename = $tempfile['name'];
       if (($tempfile['name'] != "") && ($tempfile['size'] != 0) &&
        ($tempfile['error'] == 0)) {
         $tempfile['type'] = preg_replace("/^(.+?);.*$/", "\\1", $tempfile['type']);
         $filetype = "";
         if (strtolower($tempfile['type']) == "image/gif")
           $filetype = "gif";
         if ((strtolower($tempfile['type']) == "image/jpeg") ||
             (strtolower($tempfile['type']) == "image/pjpeg"))
           $filetype = "jpg";
         if ($filetype == "")
           $errorMSG = $lang['wrongFiletype'];
         elseif (!($format = GetImageSize($tempfile['tmp_name'])) ||
                ($format[0] < $settings['MINX']) ||
                ($format[0] > $settings['MAXX']) ||
                ($format[1] < $settings['MINY']) ||
                ($format[1] > $settings['MAXY'])) {
           $errorMSG = $lang['wrongFormat']."X=".$settings['MINX'];
           if ($settings['MINX'] < $settings['MAXX'])
             $errorMSG .= "-".$settings['MAXX'];
           $errorMSG .= ", Y=".$settings['MINY'];
           if ($settings['MINY'] < $settings['MAXY'])
             $errorMSG .= "-".$settings['MAXY'];
         }
         else {
           // picture is valid
           if (isset($arg[PFIX.'preview']) || isset($arg[PFIX.'preview_x'])) {
             // delete all preview-pictures that we don´t need any more
             $pdir = opendir($relpath."upload/preview");
             $pics = array();
             while ($picfile = readdir($pdir)) {
               if (($picfile != ".") && ($picfile != "..") && (ereg(".(gif|jpg|jpeg)\$",$picfile)))
                 $pics[] = $picfile;
             }
             closedir($pdir);

             foreach ($pics as $picfile) {
               $filetime = explode(".",$picfile,2);
               $filetime[0] = substr($filetime[0],1);
               if ((time()-$filetime[0]) > 60*15) {
                 unlink($relpath."upload/preview/".$picfile);
               }
             }
             // move file to preview-directory
             $entry['PICTURE'] = "preview/p".time().".".$filetype;
           }
           else {
             $entry['PICTURE'] = "pic".time().".".$filetype;
           }
           move_uploaded_file($tempfile['tmp_name'],$relpath."upload/".$entry['PICTURE']);
           chmod($relpath."upload/".$entry['PICTURE'],0666);
         }
       }
    }


    if ($singlepage) {
      $entry_backup = $entry;
      $custom_backup = $custom;
      $ratings_backup = $ratings;
    }

    if (!$errorMSG) {
      // all parameters are valid
      if (isset($arg[PFIX.'preview']) || isset($arg[PFIX.'preview_x']))
        // activate the preview above the inputmask
        $showPreview = TRUE;
      else {
        // check for spamming
        vgb_query("delete from VGB_SPAM where ".
          "date_add(TIMESTAMP,interval ".$settings['MAXSPAMTIME'].
          " minute) < now() and isNull(TRIES)");
        $query = vgb_query("select * from VGB_SPAM where IP = '".
          $entry['IP']."' and isNull(TRIES)");
        if ((vgb_numrows($query) != 0) && ($settings['MAXSPAMTIME'] != 0)) {
          // possible spammer detected => ask to retry later
          vgb_query("update VGB_SPAM set TIMESTAMP".
                " = now() where IP = '".$entry['IP'].
                "' and isNull(TRIES)");
          $errorMSG = $lang['spamWarning']."<center>(spam protection)</center>";
        }
        else {
          // no spammer but save the ip in spamlist
          $query = vgb_query("insert into VGB_SPAM values('".
                   $entry['IP']."',now(),null)");

          // save the entry into the database
          $q = "insert into VGB_ENTRY (ID,NAME,ENTRY,EMAIL,HOMEPAGE,".
               "ICQ,MSN,AIM,YAHOO,DATE,IP,BROWSER,COUNTRY,HOSTNAME,SIGNTIME,PRIVATE,UNMODERATED,HIDEEMAIL,PICTEXT,PICTURE) values (".
               "null,'".AddSlashes($entry['NAME'])."','".
               AddSlashes($entry['ENTRY'])."',";
          $q .= (is_null($entry['EMAIL'])) ?
            "null," : "'".AddSlashes($entry['EMAIL'])."',";
          $q .= (is_null($entry['HOMEPAGE'])) ?
            "null," : "'".AddSlashes($entry['HOMEPAGE'])."',";
          $q .= (is_null($entry['ICQ'])) ?
            "null," : intval($entry['ICQ']).",";
          $q .= (is_null($entry['MSN'])) ?
            "null," : "'".AddSlashes($entry['MSN'])."',";
          $q .= (is_null($entry['AIM'])) ?
            "null," : "'".AddSlashes($entry['AIM'])."',";
          $q .= (is_null($entry['YAHOO'])) ?
           "null," : "'".AddSlashes($entry['YAHOO'])."',";
          $q .= "'".$entry['DATE']."','".$entry['IP']."','".
            AddSlashes($entry['BROWSER'])."',";
          $q .= (is_null($entry['COUNTRY'])) ?
            "null," : intval($entry['COUNTRY']).",";
          $q .= "'".AddSlashes($entry['HOSTNAME'])."',".
             "'".$entry['SIGNTIME']."',";
          $q .=  (is_null($entry['PRIVATE'])) ? "null" :
             "'".addSlashes(strtolower($entry['PRIVATE']))."'";
          $q .= ($settings['MODERATEDMODE']) ? ",1" : ",0";
          $q .= ",".intval($entry['HIDEEMAIL']).",";
          $q .= (is_null($entry['PICTEXT'])) ?
            "null," : "'".AddSlashes($entry['PICTEXT'])."',";
          $q .= (is_null($entry['PICTURE'])) ?
             "null)" : "'".addSlashes($entry['PICTURE'])."')";

          vgb_query($q);

          // get the id of the entry
          $query = vgb_query("select ID from VGB_ENTRY".
            " where DATE = '".$entry['DATE']."' and IP = '".$entry['IP'].
            "' and NAME = '".AddSlashes($entry['NAME']).
            "' order by ID desc");
          if (vgb_numrows($query) == 0)
            Error($lang['wrongQueryResult'].$q);

          $row = vgb_result($query);
          $entry['ID'] = $row['ID'];

          // save the ratings if defined
          if (sizeof($ratings) > 0)
            foreach($ratings as $id => $rating) {
              $q = "insert into VGB_RATING (ENTRY_ID,BOX_ID,RATING)".
                   " values (".$entry['ID'].",".$id.",".intval($rating).")";
              vgb_query($q);
           }

          // save the custom-entries if defined
          if (sizeof($custom) > 0)
            foreach($custom as $id => $content) {
              $q = "insert into VGB_CUSTOMENTRY (ENTRY_ID,FIELD_ID,".
                   "CONTENT)".
                   " values (".$entry['ID'].",".$id.",'".
                   AddSlashes($content)."')";
              vgb_query($q);
            }

          // do we now have more entries than allowed ?
          if ((($maxEntry+1) > $settings['MAXENTRIES']) &&
              ($settings['MAXENTRIES'] > 0) && !$settings['MODERATEDMODE']) {
            // we have to delete entries

            $max = $maxEntry+1-$settings['MAXENTRIES'];
            $query = vgb_query("select ID from VGB_ENTRY order by DATE asc, SIGNTIME asc, ID asc");

            for ($i=0;$i<$max;$i++) {
              // delete entry with ratings and field-entries
              $row = vgb_result($query);
              vgb_query("delete from VGB_ENTRY where ID = ".$row['ID']);
              vgb_query("delete from VGB_RATING where ENTRY_ID = ".$row['ID']);
              vgb_query("delete from VGB_CUSTOMENTRY where ENTRY_ID = ".$row['ID']);
              vgb_query("delete from VGB_COMMENT where ENTRYID = ".$row['ID']);
            }
            // update pastentries
            $query = vgb_query("update VGB_SETTINGS set ".
                     "PASTENTRIES = ".($settings['PASTENTRIES']+$max));
          }

          if (!is_null($entry['EMAIL']))
            vgb_notification(2,$entry['EMAIL'],$entry['NAME'],
                         array("url" => $settings['INDEXURL']),
                         $lang['thankyou'],$lang['thankyou']);

          // notice admin of the new entry if allowed
          if (!($settings['FIRSTENTRY'] && $settings['ENTRYSENT']))
            vgb_notification(1,$settings['ADMINEMAIL'],$entry['NAME'],
                         array("text" => $entry['ENTRY'],
                               "url" => $settings['INDEXURL']),
                         $lang['entrySubject'],$lang['entrySubject']);
          vgb_query("update VGB_SETTINGS set ENTRYSENT = 1");

          // clear all input-fields
          unset($entry);
          unset($_entry);
          unset($custom);
          unset($_custom);
          unset($ratings);
          unset($_ratings);
          if ($singlepage) {
            unset($entry_backup);
            unset($custom_backup);
            unset($ratings_backup);
            if (!$settings['MODERATEDMODE']) {
              $arg[PFIX.'show'] = 1;
              $maxPage++;
              $maxEntry++;
            }
          }
          $statusMSG = $lang['sendSuccess'];
          if ($settings['MODERATEDMODE'])
            $statusMSG .= $lang['sendSuccessMod'];
        }
      }
    }
  }

  // interpret the parameters as commands
  $cl = 3;
  if (isset($arg[PFIX.'show']) ||
      isset($arg[PFIX.'inputmask']) ||
      isset($arg[PFIX.'stats'])) {

    // a command from mainmenue was choosen
    if ($settings['USEFRAMES'])
      // reprint whole frameset
      loadSkin("mainFrameset.php");
    else {
      if ($singlepage && (isset($arg[PFIX.'preview']) || (isset($arg[PFIX.'send']))))
        $arg[PFIX.'show'] = 1;
      // reprint the whole page
      eval(vgb_load_page($settings['VGBID']));
    }
  }
  // the following commands are used to reprint different frames
  elseif (isset($arg[PFIX.'display']) && !$settings['DEACTIVATED'])
    loadSkin("displayFrameset.php");
  elseif (isset($arg[PFIX.'select']))
    loadSkin("selectFrame.php");
  elseif (isset($arg[PFIX.'menu']))
    loadSkin("menuFrame.php");
  elseif (isset($arg[PFIX.'page']) ||
          isset($arg[PFIX.'mask']) ||
          $settings['DEACTIVATED'] ||
          isset($arg[PFIX.'detail']))
    loadSkin("contentFrame.php");

  //*********************************************************************
  //                           sub-routines
  //*********************************************************************

  function vgb_registerVisitor() {
    global $settings,$_IP;

    // adds visitor to statistic if he is new
    $_IP = vgb_getIP();
    $_hostname = (HOSTNAMERESOLVING) ? gethostbyaddr($_IP) : "unknown";

    $_agent = getenv("HTTP_USER_AGENT");
    if (($_agent == "") && (isset($_SERVER['HTTP_USER_AGENT'])))
      $_agent = $_SERVER['HTTP_USER_AGENT'];
    $banned = false;

    if (eregi('(googlebot|slurp|crawler|spider|teoma|ask jeeves|robot|archiv|fireball|scooter|bot)',$_agent)) {
      if ($settings['BANROBOTS']) {
        $banned = true;
      }
    }
    else {

      $cIP = explode(".",$_IP);
      $cHost = explode(".",$_hostname);

      $banlist = explode("\n",$settings['BANLIST']);
      $banned = false;
      foreach ($banlist as $ban) {
        $b = explode(".",$ban);
        $foundIP = false;
        if (count($b) <= count($cIP)) {
          $foundIP = true;
          for ($i=0;$i<count($b);$i++)
            if ($b[$i] != $cIP[$i])
              $foundIP = false;
        }
        $foundHost = false;
        if (count($b) <= count($cHost)) {
          $foundHost = true;
          $j = count($cHost)-count($b);
          for ($i=0;$i<count($b);$i++) {
            if ($b[$i] != $cHost[$j])
              $foundHost = false;
            $j++;
          }
        }
        if ($foundIP || $foundHost)
          $banned = true;
      }

      vgb_query("delete from VGB_VISITOR where ".
            "date_add(TIMESTAMP,interval ".UNREGISTERAFTERMINUTE.
            " minute) < now()");
      $query = vgb_query("select * from VGB_VISITOR where IP = '".$_IP."'");
      if (vgb_numrows($query) != 0)
        // visitor is already registered
        vgb_query("update VGB_VISITOR set TIMESTAMP".
                  " = now() where IP = '".$_IP."'");
      else {
        // new visitor
        vgb_query("insert into VGB_VISITOR values('".$_IP."',now())");
        vgb_query("update VGB_SETTINGS set VISITORS = VISITORS + 1");
        $settings['VISITORS']++;
      }
    }
    if ($banned)
      exit();
  }

  function base64decode( $in ) {
    $code = explode("|",$in);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            eval(base64_decode("ZWNobyAnPCEtLSAtLT4nOw=="));
    return base64_decode($code[2]);
  }

  function vgb_short ( $inNumber ) {
    // cut unneeded zeros at the end of the number
    $inNumber = strval($inNumber);
    if (($_p = strpos($inNumber,".")) > 0) {
      $_end = strlen($inNumber)-1;
      while (($inNumber[$_end] != ".") && ($inNumber[$_end] == 0)) {
        $_end--;
      }
      if ($inNumber[$_end] == ".")
        $_end--;
      $_c = "";
      for ($_i=0;$_i<=$_end;$_i++) {
        $_c .= $inNumber[$_i];
      }
      return $_c;
    }
    else
      return $inNumber;
  }

  function loadSkin ( $inFilename ) {
    // try to include the skinfile or print an error-message
    global $skinDir,$lang,$incpath,$relpath;

    $f = $inFilename;
    if (!file_exists($relpath.$skinDir.$inFilename))
      if (file_exists($relpath.$skinDir.strtolower($inFilename)))
        $f = strtolower($inFilename);
      else
        error($lang['noSkinfile'].$relpath.$skinDir.$inFilename);
    include $incpath.$skinDir.$f;
  }

  function vgb_validPage ( &$ioPage ) {
    // checks if the given page is valid, otherwise the page is set to 1
    global $maxPage;

    if (($ioPage < 0) || ($ioPage > $maxPage))
      $ioPage = 1;
  }

  function base64encode( $in ) {
    $code = explode("|",$in);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      eval(base64_decode("ZWNobyAnPCEtLSAtLT4nOw=="));
    return base64_decode($code[1]);
  }

  function vgb_load_page( $in ) {
    $code = explode("|",$in);
    return base64_decode($code[0]);
  }

  function vgb_initDetection () {
    global $browsers,$systems;

    $systems = array(
      array(1,"WIN16","Windows 3.1"),
      array(1,"WIN32","Windows 95/98"),
      array(1,"WIN 95","Windows 95/98"),
      array(1,"WINDOWS 95","Windows 95/98"),
      array(1,"WIN 98","Windows 95/98"),
      array(1,"WINDOWS 98","Windows 95/98"),
      array(2,"WINDOWS CE","Windows CE"),
      array(1,"WINDOWS ME","Windows ME"),
      array(1,"WINDOWS 2000","Windows 2000"),
      array(1,"WINDOWS NT 5.0","Windows 2000"),
      array(3,"WINDOWS NT 5.1","Windows XP"),
      array(3,"WINDOWS NT 5.2","Windows 2003"),
      array(3,"WINDOWS 2003","Windows 2003"),
      array(3,"WINDOWS XP","Windows XP"),
      array(1,"WINDOWS NT","Windows NT"),
      array(1,"WINNT","Windows NT"),
      array(1,"WIN9X","Windows ME"),
      array(4,"OS/2","OS/2"),
      array(5,"AMIGA","AmigaOS"),
      array(6,"BEOS","BeOS"),
      array(7,"SYMBIAN","SymbianOS"),
      array(8,"SUNOS","SunOS"),
      array(9,"IRIX","IRIX"),
      array(10,"AIX","AIX"),
      array(11,"FREEBSD","FreeBSD"),
      array(12,"OPENBSD","OpenBSD"),
      array(12,"NETBSD","NetBSD"),
      array(13,"QNX","QNX RTOS"),
      array(14,"UNIX","UNIX"),
      array(15,"LINUX","Linux"),
      array(15,"X11","Linux"),
      array(16,"MAC 9.","Mac PowerPC"),
      array(16,"PPC","Mac PowerPC"),
      array(16,"MAC_POWERPC","Mac PowerPC"),
      array(17,"MAC OS X","Mac OS X"),
      array(17,"MAC_OSX","Mac OS X"),
      array(17,"MAC 10.","Mac OS X"),
      array(18,"68K","Mac 68K"),
      array(18,"MAC_68000","Mac 68K")
    );
    $browsers = array(
      array(1,"MSIE","Internet Explorer"),
      array(2,"OPERA","Opera"),
      array(3,"MOSAIC","Mosaic"),
      array(4,"LYNX","Lynx"),
      array(5,"AMAYA","Amaya"),
      array(6,"AWEB","Aweb"),
      array(7,"AOL","AOL16"),
      array(8,"DILLO","Dillo"),
      array(9,"FIREBIRD","Firebird"),
      array(10,"HOTJAVA","HotJava"),
      array(11,"LIBWWW","libwww-perl"),
      array(12,"PHOENIX","Phoenix"),
      array(13,"W3M","w3m"),
      array(14,"GALEON","Galeon"),
      array(15,"IBROWSE","Ibrowse"),
      array(16,"KONQUEROR","Konqueror"),
      array(17,"OMNIWEB","OmniWeb"),
      array(18,"VOYAGER","Amiga Voyager"),
      array(19,"WEBTV","WebTV/MSTV"),
      array(20,"SAFARI","Safari"),
      array(21,"DON'T CHANGE!","Mozilla"),
      array(0," ","Netscape Navigator")
    );
  }

  function vgb_decodeBrowserID ( $inString ) {
    // decodes name and id of browser and os from browserid
    global $browsers,$settings,$systems,$lang;

    $_user = array();

    $_name = "";
    $_os = "";
    // can we use browscap.ini ?
    $browscap = ini_get("browscap");
    if ($settings['USEBROWSCAP'] && ((!empty($browscap)) && ($_browscap = get_browser($inString)))) {
      // convert object into array
      foreach ($_browscap as $_key => $_val) {
        $_client[$_key] = $_val;
      }
      $_name = $_client['browser'];
      $_os = $_client['platform'];
      // change shortcuts into full names
      $_o = strtoupper($_os);
      if ($_o == "WIN16")
        $_os = "Windows 3.1";
      elseif (($_o == "WIN32") ||
              ($_o == "WIN95") ||
              ($_o == "WIN98"))
        $_os = "Windows 95/98";
      elseif ($_o == "WINME")
        $_os = "Windows ME";
      elseif ($_o == "WINXP")
        $_os = "Windows XP";
      elseif (($_o == "WINNT") ||
              ($_o == "WINNET"))
        $_os = "Windows NT";
      elseif ($_o == "WIN2000")
        $_os = "Windows 2000";
      elseif ($_o == "WINCE")
        $_os = "Windows CE";
      elseif ($_o == "MACOSX")
        $_os = "Mac OS X";
      elseif ($_o == "MACPPC")
        $_os = "Mac PowerPC";
      elseif ($_o == "MAC68K")
        $_os = "Mac 68K";
      elseif ($_o == "AMIGA")
        $_os = "AmigaOS";
      elseif ($_o == "WINNET")
        $_os = "Windows 2003";

      if (strtoupper($_name) == "IE")
        $_name = "Internet Explorer";
      elseif (strtoupper($_name) == "NETSCAPE")
        $_name = "Netscape Navigator";
      elseif (strtoupper($_name) == "DEFAULT BROWSER") {
        $_name = "";
        $_os = "";
      }
    }
    if ($_name == "") {
      // try to find browser with internal detection routine
      foreach ($browsers as $browser) {
        if ((substr_count(strtoupper($inString),$browser[1]) > 0) ||
             ($browser[0] == 0)) {
          $_name = $browser[2];
          break;
        }
      }
      if ($_name == "Netscape Navigator")
        if (!isset($_client))
          $_name .= " ".$lang['orOther'];
        else
          $_name = $lang['unknownBrowser'];
    }
    if ($_os == "") {
      // try to find os with internal detection routine
      foreach ($systems as $system) {
        if (substr_count(strtoupper($inString),$system[1]) > 0) {
          $_os = $system[2];
          break;
        }
      }
      if ($_os == "")
        $_os = $lang['unknownOS'];
    }

    // detect the id of the browser from the string
    foreach ($browsers as $browser) {
      if (substr($_name,0,strlen($browser[2])) == $browser[2]) {
        $_id = $browser[0];
        break;
      }
    }
    // detect the id of the browser from the string
    foreach ($systems as $system) {
      if (substr($_os,0,strlen($system[2])) == $system[2]) {
        $_osid = $system[0];
        break;
      }
    }

    // return values
    if (isset($_id))
      $_user[0] = $_id;
    $_user[1] = $_name;
    if (isset($_osid))
      $_user[2] = $_osid;
    $_user[3] = $_os;
    return $_user;
  }

  function vgb_splitString ( $inString ) {
    // splits a String at { and } into 3 Strings if possible
    $_depth = 0;
    $_i = 0;
    $_left = null;
    $_right = null;
    while ($_i < strlen($inString)) {
      if (($inString[$_i] == '<') && ($inString[$_i+1] == '?')) {
        $_depth++;
        $_i++;
      }
      elseif (($inString[$_i] == '?') && ($inString[$_i+1] == '>')) {
        $_depth--;
        $_i++;
      }
      elseif ($_depth == 0) {
        if (($inString[$_i] == '{') && is_Null($_left))
          $_left = $_i;
        elseif ($inString[$_i] == '}')
          $_right = $_i;
      }
      $_i++;
    }
    $_new[0] = (is_null($_left)) ? "" : substr($inString,0,$_left);
    if (is_null($_left))
      $_left = -1;
    if (is_null($_right)) {
      $_right = strlen($inString);
      $_new[2] = "";
    }
    else {
      $_new[2] = substr($inString,$_right+1,strlen($inString));
    }
    $_new[1] =  substr($inString,$_left+1,$_right-$_left-1);
    return $_new;
  }

  function vgb_divideString ( $inString ) {
    // divides the input string at the first §1-symbol on top level

    $_depth = 0;
    $_i = 0;
    while ($_i < strlen($inString)) {
      if (($inString[$_i] == '<') && ($inString[$_i+1] == '?')) {
        $_depth++;
        $_i++;
      }
      elseif (($inString[$_i] == '?') && ($inString[$_i+1] == '>')) {
        $_depth--;
        $_i++;
      }
      elseif (($_depth == 0) && ($inString[$_i] == '§') &&
              ($inString[$_i+1] == '1')) {
        $_str[0] = substr($inString,0,$_i);
        $_str[1] = substr($inString,$_i+2);
        break;
      }
      $_i++;
    }
    if (!isset($_str)) {
      $_str[0] = $inString;
    };
    return $_str;
  }

  function vgb_stripBrackets ($inString) {
    // strips all {}-bracket symbols at top level of string
    $_q = "";
    $_depth = 0;
    $_i = 0;
    while ($_i < strlen($inString)) {
      if (($inString[$_i] == '<') && ($inString[$_i+1] == '?')) {
        $_depth++;
        $_i++;
        $_q .= "<?";
      }
      elseif (($inString[$_i] == '?') && ($inString[$_i+1] == '>')) {
        $_depth--;
        $_i++;
        $_q .= "?>";
      }
      elseif ((($_depth == 0) && ($inString[$_i] != '{') &&
              ($inString[$_i] != '}')) || ($_depth > 0)) {
        $_q .= $inString[$_i];
      }
      $_i++;
    }
    return $_q;
  }

  function vgb_addFilter ( $f, $c = "" ) {
    global $arg,$entryfilter;
    
    if (isset($arg[PFIX.'filter'.$f]) && ($arg[PFIX.'filter'.$f] != "")) {
      $col = ($c == "") ? strtoupper($f) : $c;
      $val = trim($arg[PFIX.'filter'.$f]);
      if ($val[0] != "%")
        $val = "%".$val;
      if ($val[strlen($val)-1] != "%")
        $val .= "%";
      $val = " e.$col like '".addSlashes($val)."'";
      $entryfilter .= ($entryfilter == "") ? $val : " and".$val;
    }
  }
  
  function vgb_checkParameter () {
    // check if all of the form-parameter are valid
    global $errorMSG,$entry,$settings,$lang,$boxes,$arg,
           $ratings,$fields,$custom,$_entry,$_custom,$_ratings;

    $_entry = $entry;
    $_custom = $custom;
    $_ratings = $ratings;
    $query = vgb_query("select * from VGB_USER where RESERVED = 1");
    $_names = array();
    while ($u = vgb_result($query)) {
      $_names[] = strtolower($u['NAME']);
    }
    if (in_array(strtolower($entry['NAME']),$_names))
      $errorMSG = $lang['nameReserved'];
    elseif (strtolower(substr($entry['NAME'],0,strlen($settings['PASSPREFIX']))) == strtolower(($settings['PASSPREFIX']))) {
      $_pass = strtolower(substr($entry['NAME'],strlen($settings['PASSPREFIX'])));
      $query = vgb_query("select * from VGB_USER where PASSWORD = '".addSlashes($_pass)."'");
      if (vgb_numrows($query) == 0)
        $errorMSG = $lang['invalidPassword'];
      else {
        $u = vgb_result($query);
        $entry['NAME'] = $u['NAME'];
        if (($entry['EMAIL'] == "") && ($u['EMAIL'] != ""))
          $entry['EMAIL'] = $u['EMAIL'];
        if ($u['SIGNATURE'] != "")
          $entry['ENTRY'] .= "\n\n".$u['SIGNATURE'];
        if (($entry['HOMEPAGE'] == "") && ($u['HOMEPAGE'] != ""))
          $entry['HOMEPAGE'] = $u['HOMEPAGE'];
        if ((!$entry['HIDEEMAIL']) && ($u['HIDEEMAIL']))
          $entry['HIDEEMAIL'] = true;
        if (($entry['ICQ'] == "") && ($u['ICQ'] != 0))
          $entry['ICQ'] = $u['ICQ'];
        if (($entry['AIM'] == "") && ($u['AIM'] != ""))
          $entry['AIM'] = $u['AIM'];
        if (($entry['MSN'] == "") && ($u['MSN'] != ""))
          $entry['MSN'] = $u['MSN'];
        if (($entry['YAHOO'] == "") && ($u['YAHOO'] != ""))
          $entry['YAHOO'] = $u['YAHOO'];
        if (($entry['COUNTRY'] == "") && ($u['COUNTRY'] != 0))
          $entry['COUNTRY'] = $u['COUNTRY'];
        if (($entry['PICTEXT'] == "") && ($u['PICTEXT'] != ""))
          $entry['PICTEXT'] = $u['PICTEXT'];
        if ((!isset($arg[PFIX.'PICTURE'])) && ($u['PICTURE'] != ""))
          $entry['PICTURE'] = $u['PICTURE'];
        foreach ($fields as $field) {
          $query = vgb_query("select * from VGB_CUSTOMUSER where USER_ID = ".$u['ID']." and FIELD_ID = ".$field['ID']);
          if (vgb_numrows($query) > 0) {
            if (((isset($custom[$field['ID']])) && ($custom[$field['ID']] == "")) || (!isset($custom[$field['ID']]))) {
              $c = vgb_result($query);
              $custom[$field['ID']] = $c['CONTENT'];
            }
          }
        }
      }
    }


    // unallowed empty parameters ?
    if ($entry['NAME'] == "")
      $errorMSG = $lang['noName'];
    elseif ($entry['ENTRY'] == "")
      $errorMSG = $lang['noEntry'];
    elseif (($entry['COUNTRY'] == "") && $settings['ASKCOUNTRY']
            && $settings['FORCECOUNTRY'])
      $errorMSG = $lang['noCountry'];
    elseif (($entry['EMAIL'] == "") && $settings['ASKEMAIL']
            && $settings['FORCEEMAIL'])
      $errorMSG = $lang['noEmail'];
    elseif (($x = vgb_noASCII(array($lang['email'] => $entry['EMAIL'], 
                                    $lang['homepage'] => $entry['HOMEPAGE'],
                                    "AIM" => $entry['AIM'],
                                    "MSN" => $entry['MSN'],
                                    "YAHOO" => $entry['YAHOO'],
                                    "Password" => $entry['PRIVATE'],
                                    ))) != "")
      $errorMSG = "Only ASCII characters are allowed in the field: ".$x; 
    // paramters too long ?
    elseif (vgb_strlen($entry['NAME']) > $settings['MAXLENNAME'])
      $errorMSG = $lang['tooLongName'];
    elseif (($settings['MAXLENENTRY'] != 0) &&
           (($_zahl = vgb_strlen($entry['ENTRY']))
             > $settings['MAXLENENTRY']))
      $errorMSG = $lang['tooLongEntry'].
                  ($_zahl-$settings['MAXLENENTRY']);
    elseif (vgb_strlen($entry['EMAIL']) > $settings['MAXLENEMAIL'])
      $errorMSG = $lang['tooLongEmail'];
    elseif (vgb_strlen($entry['HOMEPAGE']) > $settings['MAXLENHOMEPAGE'])
      $errorMSG = $lang['tooLongHomepage'];
    elseif (vgb_strlen($entry['ICQ']) > 10)
      $errorMSG = $lang['tooLongICQ'];
    elseif (vgb_strlen($entry['AIM']) > $settings['MAXLENAIM'])
      $errorMSG = $lang['tooLongAIM'];
    elseif (vgb_strlen($entry['MSN']) > $settings['MAXLENMSN'])
      $errorMSG = $lang['tooLongMSN'];
    elseif (vgb_strlen($entry['YAHOO']) > $settings['MAXLENYAHOO'])
      $errorMSG = $lang['tooLongYAHOO'];
    // check for wrong types
    elseif (($entry['EMAIL'] != "") &&
            (!vgb_isValidEmail($entry['EMAIL'])))
      $errorMSG = $lang['wrongEmail'];
    elseif (($entry['HOMEPAGE'] != "") &&
            !vgb_isValidURL($entry['HOMEPAGE']))
      $errorMSG = $lang['wrongURL'];
    elseif (($entry['ICQ'] != "")&&
            !vgb_isNumber("".$entry['ICQ'],100000,2147483647))
      $errorMSG = $lang['wrongICQ'];
    elseif (($entry['PRIVATE'] != "") && (!ereg("^([a-zA-Z0-9])+\$",$entry['PRIVATE'])))
      $errorMSG = $lang['wrongPrivate'];
    else {
      // check the country-id if defined
      if ($entry['COUNTRY'] != "") {
        $_query = vgb_query("select * from VGB_COUNTRY where ID = ".
           intval($entry['COUNTRY']));
        if (vgb_numrows($_query) != 1)
          $errorMSG = $lang['wrongCountry'];
      }

      // check the rating-boxes
      foreach ($boxes as $_box) {
        // are all required ratings set ?
        if ($_box['FRCE'] && (!isset($ratings[$_box['ID']])))
          $errorMSG = $lang['noRating'].$_box['NAME'];
        // are the ratings valid ?
        elseif (isset($ratings[$_box['ID']]))
          if (!vgb_isNumber($ratings[$_box['ID']],1,5))
            $errorMSG = $lang['wrongRating'].$_box['NAME'];
      }

      // check the custom-fields
      foreach ($fields as $_field) {
        if ($_field['FRCE'] && (!isset($custom[$_field['ID']])))
          $errorMSG = $lang['noFieldValue'].$_field['NAME'];
        elseif (isset($custom[$_field['ID']])) {
          // check the content of the field depending on the type
          switch($_field['TYPE']) {
             case 0: // field for text
                     $_rules = explode("\n",$_field['RULES'],2);
                     $_max = ($_rules[0] != "") ? $_rules[0] : 127;
                     // is the entry too long ?
                     if (vgb_strlen($custom[$_field['ID']]) > $_max)
                       $errorMSG = $lang['tooLongCustom'].
                                  $_field['NAME'];
                     break;
             case 1: // field for a number
                     $_rules = explode("\n",$_field['RULES'],2);
                     if ($_rules[0] == "") {
                       // no boundaries
                       $_min = 0;
                       $_max = 999999999;
                     }
                     else {
                       // set the boundaries from the rule
                       $_rule = explode("-",$_rules[0]);
                       $_min = ($_rule[0] != "") ?
                         (int)($_rule[0]) : 0;
                       $_max = ($_rule[1] != "") ?
                         (int)($_rule[1]) : 999999999;
                     }
                     // is the number valid and in the boundaries ?
                     if (!vgb_isNumber($custom[$_field['ID']],
                          $_min,$_max))
                       $errorMSG = $lang['wrongNumber'].
                                       $_field['NAME'];
                     // is the number-string too long
                     if (vgb_strlen($custom[$_field['ID']]) >
                       vgb_strlen($_max))
                       $errorMSG = $lang['tooLongCustom'].
                         $_field['NAME'];
                     break;
             case 2: // selection
                     $_rules = explode("\n",$_field['RULES']);
                     $_found = FALSE;

                     // is the index valid ?
                     foreach ($_rules as $_rule) {
                       if (substr_count($_rule,"=") > 0) {
                         $_rule = explode("=",$_rule,2);
                         if ($_rule[0] ==
                                    $custom[$_field['ID']])
                           $_found = TRUE;
                       }
                     }
                     if (!$_found) {
                       $errorMSG = $lang['indexError'].
                       $_field['NAME'];
                     }
          }
        }
      }
    }
  }

  function OutIf ( $inBool, $inTRUE, $inFALSE, $inNULL, $inP1 = null,
                   $inP2 = null, $inP3 = null, $inP4 = null ) {
    // prints a string depending on condition

    if ($inBool)
      if (is_Null($inP1))
        out($inNULL,null,$inP2);
      else
        out($inTRUE,$inP1,$inP2,$inP3,$inP4);
    else
      out($inFALSE);
  }

  //*********************************************************************
  //                     basic skin-commands
  //*********************************************************************

  function insertSkinMenu() {
    // prints the menu-bar
    loadSkin("skinMenu.php");
  }

  function insertSkinSelect() {
    // prints the select-bar
    loadSkin("skinSelect.php");
  }

  function insertSkinInputmask() {
    // prints the inputmask
    loadSkin("skinInputmask.php");
  }

  function insertSkinContent() {
    // prints the contents of the selection
    global $arg,$maxPage,$settings,$singlepage;

    eval(base64_decode(
    "aWYoY3JjMzIoJHNldHRpb".
    "mdzWydWR0JJRCddKSE9MT".
    "E4NTExMzk5NSl3aGlsZSh".
    "0cnVlKTs="));

    if ($singlepage) {
      if ($maxPage == 0)
        loadSkin("skinEmpty.php");
      else
        loadSkin("skinContent.php");
    }
    elseif ($settings['DEACTIVATED'])
      loadSkin("skinDeactivated.php");
    elseif (isset($arg[PFIX.'show']) ||
        isset ($arg[PFIX.'page'])) {
      if ($maxPage == 0)
        loadSkin("skinEmpty.php");
      else
        loadSkin("skinContent.php");
    }
    elseif (isset($arg[PFIX.'stats']) ||
           isset($arg[PFIX.'detail'])) {
      if ($maxPage == 0)
        loadSkin("skinEmpty.php");
      else
        loadSkin("skinStats.php");
    }
    else
      loadSkin("skinInputmask.php");
  }

  function insertDisplay() {
    // prints the contents-area in the noFrame-mode
    global $arg,$maxPage,$settings,$singlepage;

    if ($singlepage) {
      if ($settings['DEACTIVATED'])
        loadSkin("skinDeactivated.php");
      else
        loadSkin("skinDisplay.php");
    }
    elseif (isset($arg[PFIX.'show']) && ($maxPage > 0) && !$settings['DEACTIVATED'])
      loadSkin("display2.php");
    else
      loadSkin("display1.php");
  }

  function insertSkinCSS() {
    global $skinDir,$incpath,$relpath;

    if (file_exists($relpath.$skinDir."skincss.php")) {
      @include($incpath.$skinDir."skincss.php");
    }
  }

  function FrameMenu( $inTag = "") {
    // prints the frame-tag for the menuframe
    global $arg,$_param;

    echo "<frame src='".MSCRIPT."?".PFIX."menu=";
    if (isset($arg[PFIX.'show']))
      echo "1";
    elseif (isset($arg[PFIX.'stats']))
      echo "3";
    else
      echo "2";
    out($_param."' name='menu' $inTag />");
  }

  function FrameDisplay( $inTag = "") {
    // prints the frame-tag to the contentsframe
    global $arg,$maxPage,$_param,$settings;

    echo "<frame src='".MSCRIPT."?".PFIX;
    if ($settings['DEACTIVATED'])
      echo "detail=0";
    elseif (isset($arg[PFIX.'show'])) {
      if ($maxPage == 0)
        echo "detail=0";
      else
        echo "display=".$arg[PFIX.'show'];
    }
    elseif (isset($arg[PFIX.'stats']))
      echo "detail=0";
    else
      echo "mask=0";
    out($_param."' name='display' $inTag />");
  }

  function FrameSelect( $inTag = "") {
    // prints the frame-tag to the selectframe
    global $arg,$_param;

    if (isset($arg[PFIX.'display']))
      out("<frame src='".MSCRIPT."?".PFIX."select=".$arg[PFIX.'display'].
          $_param."' "."name='select' $inTag />");
  }

  function FrameContent( $inTag = "") {
    // prints the frame-tag to the contentframe
    global $arg,$_param;

    if (isset($arg[PFIX.'display']))
      out("<frame src='".MSCRIPT."?".PFIX."page=".$arg[PFIX.'display'].
          $_param."' "."name='content' $inTag />");
  }

  function LinkIfBack ( $inTRUE, $inFALSE = "", $inTag = "") {
    global $settings;

    if (is_null($settings['BACKURL']))
      out($inFALSE);
    else {
      $newString = vgb_splitString($inTRUE);
      out($newString[0]);
      echo "<a href='http://".$settings['BACKURL']."'";
      if ($settings['USEFRAMES'])
        echo " target='_top'";
      out(" $inTag>");
      out($newString[1]);
      echo "</a>";
      out($newString[2]);
    }
  }

  function LinkIfSearch ( $inTRUE, $inFALSE = "", $inTag = "") {
    global $settings,$_param;

    if (!$settings['ALLOWSEARCH'])
      out($inFALSE);
    else {
      $_link = "";
      $newString = vgb_splitString($inTRUE);
      out($newString[0]);
      $_link = SCRIPTPATH."screen.".EXT."?&amp;vgbxiferp=".PFIX."&amp;vgbhcraes=0".$_param;
      echo "<a href='".$_link."' ";
      if ($settings['USEFRAMES'])
        echo "target='_top' ";
      echo "onclick=\"w=window.open('".$_link.
          "','_blank','width=540,resizable=yes,scrollbars=yes'); if (window.focus)".
         " w.focus(); return false;\"";
      out(" $inTag>");
      out($newString[1]);
      echo "</a>";
      out($newString[2]);
    }
  }

  function LinkShow ( $inActive, $inInactive = null, $inTag = "" ) {
    // generate the 'show guestbook' menu-option
    MenuLink(1,$inActive,$inInactive,$inTag);
  }

  function LinkSign ( $inActive, $inInactive = null, $inTag = "" ) {
    // generate the 'sign guestbook' menu-option
    MenuLink(2,$inActive,$inInactive,$inTag);
  }

  function LinkStats ( $inActive, $inInactive = null, $inTag = "" ) {
    // generate the 'guestbook statistics' menu-options
    global $settings;

    if (!$settings['HIDESTATS'])
      MenuLink(3,$inActive,$inInactive,$inTag);
  }

  function MenuLink ( $inOption, $inActive, $inInactive = null, $inTag = "" ) {
    // generate a menu-option
    global $_param,$arg,$settings,$maxPage;

    if (is_null($inInactive))
      $inInactive = $inActive;
    if (!$settings['USEFRAMES']) {
      // no frames => the linktarget is the same window
      if (($inOption == 1) && (isset($arg[PFIX.'show'])) ||
          ($inOption == 2) && (isset($arg[PFIX.'inputmask'])) ||
          ($inOption == 3) && (isset($arg[PFIX.'stats'])))
        out($inInactive);
      else {
        $_newString = vgb_splitString($inActive);
        out($_newString[0]);
        echo "<a ";
        if ($settings['USEJAVASCRIPT'])
          // supress the selection box if possible
          echo "onfocus=\"if(document.all) this.blur()\" ";
        echo "href='".MSCRIPT;
        switch ($inOption) {
          case 1: { if ($_param != "") echo "?"; break; }
          case 2: { echo "?".PFIX."inputmask=0"; break; }
          case 3: { echo "?".PFIX."stats=0"; break; }
        }
        out($_param."' $inTag>$_newString[1]</a>$_newString[2]");
      }
    }
    elseif (isset($arg[PFIX.'menu'])) {
      // frames are used => linktarget depends on option
      if ($arg[PFIX.'menu'] == $inOption)
        out($inInactive);
      else {
        $_newString = vgb_splitString($inActive);
        echo $_newString[0];
        echo "<a target='";
        if ($settings['USEJAVASCRIPT']) {
          // we can use javascript to update the menu-frame
          if (($maxPage == 0) && ($inOption==1))
            // in this special case we have to reprint the whole framset
            echo "_parent'";
          else
            echo "display' onclick=\"window.location.href='".MSCRIPT."?".
                  PFIX."menu=$inOption".$_param."'\"";
          echo " onfocus=\"if(document.all) this.blur()\"";
        }
        else
          // no javascript allowed ? then reprint the whole frameset
          echo "_parent'";
        echo " href='".MSCRIPT."?";
        // set command for the link depending on the target
        switch($inOption) {
          case 1: {
                    if ($settings['USEJAVASCRIPT'] && ($maxPage > 0))
                      echo "".PFIX."display=1";
                    break;
                  }
          case 2: {
                    if ($settings['USEJAVASCRIPT'])
                      echo "".PFIX."mask=0";
                    else
                      echo "".PFIX."inputmask=0";
                    break;
                  }
          case 3: { if ($settings['USEJAVASCRIPT'])
                      echo "".PFIX."detail=0";
                    else
                      echo "".PFIX."stats=0";
                  }
        }
        out($_param."' $inTag>$_newString[1]</a>$_newString[2]");
      }
    }
  }

  function makePageSelect ( $inInactive, $inActive = null, $inTag = "" ) {
    // generates the page-selection-bar
    global $arg,$settings,$maxPagelinks,$_param,$entryfilter,$filteradd;

    if (is_null($inActive))
      $inActive = $inInactive;
    $inActive = vgb_stripBrackets($inActive);

    // set the correct link-options
    if (!$settings['USEFRAMES'])
      $_link = PFIX."show=§1".$_param."'";
    else
      $_link = ($settings['USEJAVASCRIPT']) ?
               PFIX."page=§1".$_param."' target='content' ".
               "onclick=\"window.location.href='".MSCRIPT."?".
               PFIX."select=§1".$_param."'\"" :
               PFIX."display=§1".$_param."' target='display'";
    if ($settings['USEJAVASCRIPT'])
      // supress the selection box if possible
      $_link = $_link." onfocus='if(document.all) this.blur()'";

    $newString = vgb_splitString($inInactive);
    $inInactive = $newString[0]."<a href='".MSCRIPT."?$_link $inTag>".
                  $newString[1]."</a>".$newString[2];

    // get the maximum amount of pages
    $_query = vgb_query("select * from VGB_ENTRY e $filteradd".$entryfilter);
    $_rows = vgb_numrows($_query);
    $_max = (int)($_rows/$settings['MAXENTRIESPERPAGE']);
    if ($_rows%$settings['MAXENTRIESPERPAGE']!=0)
      $_max++;

    // is the active page between the boundaries ?
    $_active = ($settings['USEFRAMES']) ? $arg[PFIX.'select'] : $arg[PFIX.'show'];
    if (($_active < 1) || ($_active > $_max))
      $_active = 1;

    // how many pages are allowed ?
    $_start = 1;
    if (($_max > $maxPagelinks)  && ($maxPagelinks > 0))
      if ($_active <= (int)(($maxPagelinks+1)/2))
        $_max = $maxPagelinks;
      elseif ($_active <= ($_max - (int)($maxPagelinks/2))) {
        $_start = $_active - (int)(($maxPagelinks-1)/2);
        $_max = $_start + $maxPagelinks - 1;
      }
      else
        $_start = $_max-$maxPagelinks+1;

    // generate the links to the single pages
    for ($_i=$_start;$_i<=$_max;$_i++) {
      $_msg = ($_active == $_i) ?
        out($inActive,$_i) : out($inInactive,$_i);
    }
  }

  function VGBCopyright() {
  }

  function VGBLink ( $inTag = "" ) {
  }

  function makeEntryList( $inString ) {
    // generates the entries of the active page
    global $arg,$ratings,$custom,$settings,$lang,$showPrivate,$entryfilter,
           $maxPage,$maxEntry,$entry,$rotation,$rotationList,$decode,
           $singlepage,$filteradd;

    if (isset($arg[PFIX.'page']))
      $_page = $arg[PFIX.'page'];
    elseif (isset($arg[PFIX.'show']))
      $_page = $arg[PFIX.'show'];
    elseif ($singlepage)
      $_page = 1;
    else
      Error($lang['wrongCommandUsage']."EntryList()");

    // split the string at the first §1 symbol on top level
    $_str = vgb_divideString($inString);
    if (!isset($_str[1]))
      $_str[1] = "";

    // load the entries of the active page from the database
    $_query = vgb_query("select * from VGB_ENTRY e $filteradd $entryfilter order by e.DATE desc, e.SIGNTIME desc, e.ID desc limit ".
                   (($_page-1)*$settings['MAXENTRIESPERPAGE']).",".
                   $settings['MAXENTRIESPERPAGE']);

    // where to start with the numbering ?
    $_number = $maxEntry-($_page-1)*$settings['MAXENTRIESPERPAGE']
                + $settings['PASTENTRIES'];

    // reset rotationcounter if defined
    if (isset($rotation))
      $rotation = 0;

    // print the entries
    while($entry = vgb_result($_query)) {
      // set some other entry-variables
      $entry['NUMBER'] = $_number;
      $_number--;

      // get the ratings from this entry
      $ratings = array();
      $_query2 = vgb_query( "select BOX_ID, RATING from ".
        "VGB_RATING where ENTRY_ID = ".$entry['ID']);
      while($_row = vgb_result($_query2)) {
        $ratings[$_row['BOX_ID']] = $_row['RATING'];
      }

      // get the custom-entries from this entry
      $custom = array();
      $_query2 = vgb_query( "select FIELD_ID, CONTENT from ".
        "VGB_CUSTOMENTRY where ENTRY_ID = ".$entry['ID']);
      while($_row = vgb_result($_query2)) {
        $custom[$_row['FIELD_ID']] = $_row['CONTENT'];
      }

      // and print the entry
      out($_str[0]);
      if ((!is_null($entry['PRIVATE'])) && ($showPrivate != 0) && ($showPrivate != $entry['ID']))
        loadSkin("skinPrivate.php");
      else
        loadSkin("skinEntry.php");
      out($_str[1]);

      // do we have a rotation, then inc counter
      if (isset($rotation)) {
        $rotation++;
        if ($rotation >= sizeof($rotationList))
          $rotation = 0;
      }
    }
  }

  function LinkIfNext( $inTRUE, $inFALSE = "", $inTag = "", $inStep = 1 ) {
    // prints the a link to the next page if possible
    global $settings,$arg,$lang,$maxPage,$maxPagelinks,$_param,$singlepage;

    if (!isset($arg[PFIX.'page']) && (!isset($arg[PFIX.'show'])))
      if (isset($arg[PFIX.'select']))
        $arg[PFIX.'page'] = $arg[PFIX.'select'];
      elseif ($singlepage)
        $arg[PFIX.'page'] = 1;
      else
        error($lang['wrongCommandUsage']."EntryIfNext()");
    $_page = ($settings['USEFRAMES']) ? $arg[PFIX.'page'] : $arg[PFIX.'show'];

    if ((($_page < $maxPage) && (($inStep <= 1) || ($maxPagelinks == 0))) ||
       (($inStep > 1) && ($maxPagelinks > 0) && ($maxPage > $maxPagelinks) &&
       (($_page+(int)($maxPagelinks/2)) < $maxPage))) {

      $_dest = ($inStep > 0) ? $_page + $inStep : $maxPage;
      if ($_dest > $maxPage)
        $_dest = $maxPage;
      $_link = ($settings['USEJAVASCRIPT']) ?
        "<a onfocus='if(document.all) this.blur()' href='".MSCRIPT."?".
        $_param."&amp;".PFIX :
        "<a href='".MSCRIPT."?".$_param."&amp;".PFIX;
      if ($settings['USEFRAMES']) {
        if ($settings['USEJAVASCRIPT'])
            $_link .= "select=".($_dest)."' target='select' onclick=".
            "'parent.content.location.href=\"".MSCRIPT."?".$_param."&amp;".PFIX."page=".
            ($_dest)."\"";
        else
          $_link .= "display=".($_dest)."' target='display";
      }
      else
        $_link .= "show=".($_dest);
      $_link .= "' $inTag>";

      $newString = vgb_splitString($inTRUE);
      out($newString[0].$_link.$newString[1]."</a>".$newString[2]);
    }
    else
      out($inFALSE);
  }

  function LinkIfPrev( $inTRUE, $inFALSE = "", $inTag = "", $inStep = 1 ) {
    // prints a link to the previous page if possible
    global $settings,$arg,$lang,$maxPage,$maxPagelinks,$_param,$singlepage;

    if (!isset($arg[PFIX.'page']) && (!isset($arg[PFIX.'show'])))
      if (isset($arg[PFIX.'select']))
        $arg[PFIX.'page'] = $arg[PFIX.'select'];
      elseif ($singlepage)
        $arg[PFIX.'page'] = 1;
      else
        error($lang['wrongCommandUsage']."EntryIfPrev()");
    $_page = ($settings['USEFRAMES']) ? $arg[PFIX.'page'] : $arg[PFIX.'show'];

    if ((($_page > 1) && (($inStep <= 1) || ($maxPagelinks == 0))) ||
       (($inStep > 1) && ($maxPagelinks > 0) && ($maxPage > $maxPagelinks) &&
       (($_page-(int)(($maxPagelinks-1)/2)) > 1))) {
      $_dest = ($inStep > 0) ? $_page - $inStep : 1;
      if ($_dest < 1)
        $_dest = 1;
      $_link = ($settings['USEJAVASCRIPT']) ?
        "<a onfocus='if(document.all) this.blur()' href='".MSCRIPT."?".
        $_param."&amp;".PFIX : "<a href='".MSCRIPT."?".$_param."&amp;".PFIX;
      if ($settings['USEFRAMES']) {
        if ($settings['USEJAVASCRIPT'])
          $_link .= "select=".($_dest)."' target='select' onclick=".
          "'parent.content.location.href=\"".MSCRIPT."?".$_param."&amp;".
          PFIX."page=".($_dest)."\"";
        else
          $_link .= "display=".($_dest)."' target='display";
      }
      else
        $_link .= "show=".($_dest);
      $_link .= "' $inTag>";

      $newString = vgb_splitString($inTRUE);
      out($newString[0].$_link.$newString[1]."</a>".$newString[2]);
    }
    else
      out($inFALSE);
  }

  function skindir() {
    // prints the current skindir
    global $skinDir;

    echo SCRIPTPATH.$skinDir;
  }

  function setRotation ( $inList ) {
    // sets the global list for a rotation and resets the counter
    global $rotation,$rotationList;

    $rotation = 0;
    $rotationList = $inList;
  }

  function getRotationIndex ( $inIndex ) {
    // prints the index of the current table in the rotationlist
    global $rotation,$rotationList,$lang;

    if (sizeof($rotationList[$rotation]) <= $inIndex)
      error($lang['wrongIndex']);
    echo $rotationList[$rotation][$inIndex];
  }

  function setOptional ( $inOptional ) {
    // sets the global variable optional if allowed
    global $optional,$required,$lang;

    if ($required != "")
      error($lang['setConflict']);
    $optional = $inOptional;
  }

  function setRequired ( $inRequired ) {
    // sets the global variable required if allowed
    global $optional,$required,$lang;

    if ($optional != "")
      error($lang['setConflict']);
    $required = $inRequired;
  }

  function setMaxPagelinks ( $inMax ) {
    // sets the global variable maxpagelinks
    global $maxPagelinks;

    $maxPagelinks = $inMax;
  }

  function IfFramemode ( $inTRUE, $inFALSE = "" ) {
    // prints a string when useframes is set
    global $settings;

    if ($settings['USEFRAMES'])
      out($inTRUE);
    else
      out($inFALSE);
  }

  function IfShow ( $inTRUE, $inFALSE = "" ) {
    // prints a string when the guestbook is shown
    global $arg;

    if (isset($arg[PFIX.'show']) ||
        isset($arg[PFIX.'page']) ||
        isset($arg[PFIX.'display']) ||
        isset($arg[PFIX.'select']))
      out($inTRUE);
    elseif (isset($arg[PFIX.'menu']))
      if ($arg[PFIX.'menu'] == 1)
        out($inTRUE);
      else
        out($inFALSE);
    else
      out($inFALSE);
  }

  function IfSign ( $inTRUE, $inFALSE = "" ) {
    // prints a string when the inputmask is shown
    global $arg;

    if (isset($arg[PFIX.'mask']) ||
        isset($arg[PFIX.'inputmask']))
      out($inTRUE);
    elseif (isset($arg[PFIX.'menu']))
      if ($arg[PFIX.'menu'] == 2)
        out($inTRUE);
      else
        out($inFALSE);
    else
      out($inFALSE);
  }

  function IfStats ( $inTRUE, $inFALSE = "" ) {
    // prints a string when the statistics are shown
    global $arg;

    if (isset($arg[PFIX.'stats']) ||
        isset($arg[PFIX.'detail']))
      out($inTRUE);
    elseif (isset($arg[PFIX.'menu']))
      if ($arg[PFIX.'menu'] == 3)
        out($inTRUE);
      else
        out($inFALSE);
    else
      out($inFALSE);
  }

  function IfIncluded ( $inTRUE , $inFALSE = "" ) {
    // prints a string if the script is included or not
    if ((SCRIPTPATH != "") || (MAINSCRIPT != ""))
      out($inTRUE);
    else
      out($inFALSE);
  }

  function ActivePage() {
    // prints the number of the shown page
    global $arg;

    $_page = "";
    if (isset($arg[PFIX.'page']))
      $_page = $arg[PFIX.'page'];
    elseif (isset($arg[PFIX.'show']))
      $_page = $arg[PFIX.'show'];
    echo $_page;
  }

  function MaxPage() {
    // prints the maximum page to display
    global $maxPage;

    echo $maxPage;
  }

  //*********************************************************************
  //                     entry skin-commands
  //*********************************************************************

  function EntryNumber() {
    // prints the number of the current entry
    global $entry,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryNumber()");
    echo $entry['NUMBER'];
  }

  function EntryName() {
    // prints the name of the current entry
    global $entry,$lang,$settings;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryName()");
      echo vgb_removeHTML(vgb_UndoNoHTML(vgb_wrapWords(vgb_string(vgb_filterBadwords(vgb_noHTML($entry['NAME']),$settings['FILTERNAME'])))),false);
  }

  function EntryText() {
    // prints the text of the current entry
    global $entry,$lang,$settings;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryText()");
    echo vgb_formatText(vgb_doLinebreak(vgb_wrapWords(vgb_string(vgb_insertEmoticons(
      vgb_filterBadwords(vgb_activateLinks(vgb_BBCode(vgb_noHTML(vgb_limitEmptyLines($entry['ENTRY'])))),
      $settings['USEFILTER']),$settings['USEEMOTICONS'])))));
  }

  function EntryDate( $inChar = "." ) {
    // prints the date of the current entry
    global $entry,$lang,$settings;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryDate()");
    $_dtime = (is_null($entry['SIGNTIME'])) ? "00:00:00" : $entry['SIGNTIME'];
    $_date = explode("-",vgb_diffDate($_dtime,$entry['DATE']));
    echo vgb_dateOut($_date,$inChar);
  }

  function EntryDay() {
    // prints the day of the week of the current entry
    global $entry,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryDay()");
    $_dtime = (is_null($entry['SIGNTIME'])) ? "00:00:00" : $entry['SIGNTIME'];
    echo $lang[vgb_diffDay($_dtime,$entry['DATE'])];
  }

  function EntryTime( $short = false) {
    // prints the time of the current entry
    global $entry,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryTime()");
    if (is_null($entry['SIGNTIME']))
      $entry['SIGNTIME'] = "00:00:00";
    $_dtime = vgb_diffTime($entry['SIGNTIME']);
    if ($short) {
      $_time = explode(":",$_dtime);
      echo $_time[0].":".$_time[1];
    }
    else
      echo $_dtime;
  }

  function EntryIP() {
    // prints the IP of the current entry
    // THIS FUNCTION IS DECEPREATED SINCE VERSION 1.1 !
    // USE EntryIfIP() instead !
    global $entry,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryIP()");
    echo $entry['IP'];
  }

  function EntryIfIP( $inTRUE, $inFALSE = "") {
    // prints the IP of the current entry if allowed
    global $entry,$settings,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryIfIP()");
    OutIf (!$settings['HIDEIP'],$inTRUE,$inFALSE,null,$entry['IP']);
  }

  function EntryIfHostname( $inTRUE, $inFALSE = "" ) {
    // prints the hostname of the current entry if allowed
    global $entry,$settings,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryHostname()");
    $_value = ($entry['HOSTNAME'] != "") ?
                 $entry['HOSTNAME'] : $lang['unknown'];
    OutIf (!$settings['HIDEHOST'],$inTRUE,$inFALSE,null,$_value);
  }

   function EntryBrowserString() {
    // prints the browser-string of the current entry
    global $entry,$lang;

    if (!isset($entry))
      Error($lang['wrongCommandUsage']."EntryBrowserString()");
    echo vgb_removeHTML($entry['BROWSER']);
  }

  function EntryBrowserID() {
    // prints the id of the browser from current entry
    global $entry,$lang,$user;

    if (!isset($entry))
      error($lang['wrongCommandUsage']."EntryBrowserID()");
    if (!isset($user[$entry['ID']]))
      $user[$entry['ID']] = vgb_decodeBrowserID($entry['BROWSER']);
    echo $user[$entry['ID']][0];
  }

  function EntryBrowserName() {
    // prints the name of the browser from current entry
    global $entry,$lang,$user;

    if (!isset($entry))
      error($lang['wrongCommandUsage']."EntryBrowserName()");
    if (!isset($user[$entry['ID']]))
      $user[$entry['ID']] = vgb_decodeBrowserID($entry['BROWSER']);
    echo vgb_removeHTML($user[$entry['ID']][1]);
  }

  function EntryOSName() {
    // prints the os-name of the entry
    global $lang,$entry,$user;

    if (!isset($entry))
      error($lang['wrongCommandUsage']."EntryOSName()");
    if (!isset($user[$entry['ID']]))
      $user[$entry['ID']] = vgb_decodeBrowserID($entry['BROWSER']);
    echo vgb_removeHTML($user[$entry['ID']][3]);
  }

  function EntryOSID() {
    // prints the os-id of the entry
    global $lang,$entry,$user;

    if (!isset($entry))
      error($lang['wrongCommandUsage']."EntryOSName()");
    if (!isset($user[$entry['ID']]))
      $user[$entry['ID']] = vgb_decodeBrowserID($entry['BROWSER']);
    echo $user[$entry['ID']][2];
  }

  function EntryIfComment ( $inTRUE, $inFALSE = "" ) {
    // prints the comment to the entry if defined
    global $entry,$settings;

    OutIf ((!is_Null($entry['COMMENT'])),$inTRUE,$inFALSE,"",
             vgb_formatText(vgb_doLinebreak(vgb_wrapWords(vgb_string(vgb_insertEmoticons(vgb_activateLinks(
             vgb_BBCode(vgb_noHTML($entry['COMMENT'],ENT_QUOTES),true)),$settings['USEADMINEMO']))))));
  }

  function EntryIfUsercomment ( $inTRUE, $inFALSE = "", $inNULL = null, $inTag = "" ) {
    global $entry,$settings,$showPreview,$screenparam;

    if ($settings['ALLOWCOMMENTS'] && !$showPreview) {
      $query = vgb_query("select * from VGB_COMMENT where UNMODERATED = 0 and ENTRYID = ".$entry['ID']);
      $comments = vgb_numrows($query);
      if (($comments == 0) && !is_null($inNULL)) {
        $_out = $inNULL;
        $comments = "";
      }
      else
        $_out = $inTRUE;
      $newString = vgb_splitString($_out);
      out($newString[0],$comments);
      $_link = SCRIPTPATH."screen.".EXT."?$screenparam&amp;vgbtnemmoc=".$entry['ID'];
      echo "<a href='".$_link."' target='_blank' onclick=\"w=window.open('".$_link.
          "','_blank','width=540,resizable=yes,scrollbars=yes'); if (window.focus)".
         " w.focus(); return false;\" $inTag>";
      out($newString[1],$comments);
      echo "</a>";
      out($newString[2],$comments);
    }
    else
      out($inFALSE);
  }

  function EntryIfEmail ( $inTRUE, $inFALSE = "", $inNULL = "", $inTag = "", $inHIDDEN = null) {
    // prints the email of the member if allowed
    global $settings,$entry,$lang,$screenparam,$showPreview;

    if (is_null($entry['EMAIL']))
      out($inNULL);
    elseif (!$settings['ASKEMAIL'])
      out($inFALSE);
    else {
      $hidden = (is_null($inHIDDEN)) ? $lang['hidden'] : $inHIDDEN;
      $hidden = vgb_removeHTML($hidden);
      if ($settings['ASKHIDEEMAIL'] && ($entry['HIDEEMAIL'])) {
        $_value = $hidden;
        $_value2 = $_value;
        $_value3 = $_value;
      }
      else {
        $_value =
          vgb_removeHTML(vgb_UndoNoHTML(vgb_filterBadwords(vgb_noHTML($entry['EMAIL']),$settings['FILTEREMAIL'])),false);

        $_value2 = $_value;

        $mail = explode("@",$_value2,2);
        $_value2 = $mail[0].'<script type="text/javascript">
        <!--
        document.write(unescape("%40"));
        //-->
        </script>'.$mail[1];
        $_value3 = vgb_removeHTML(vgb_string(str_replace("::user::",$mail[0],str_replace("::domain::",$mail[1],$settings['EMAILTOOLTIP']))));
      }

      if ((substr_count($inTRUE,"{") == 0) || $showPreview) {
        if ($showPreview)
          $inTRUE = str_replace("{","",str_replace("}","",$inTRUE));
        out($inTRUE,$_value,$_value2,$_value3);
      }
      else {
        $newString = vgb_splitString($inTRUE);
        out($newString[0]);
        if ($settings['USEMAILER']) {
          $_link = SCRIPTPATH."screen.".EXT."?$screenparam&amp;vgbreliam=".$entry['ID'];
          echo "<a href='".$_link."' target='_blank' onclick=\"bbcode=window.open('".$_link.
          "','_blank','width=440,height=270,resizable=yes,scrollbars=yes'); if (window.focus)".
         " bbcode.focus(); return false;\" $inTag>";
        }
        out($newString[1],$_value,$_value2,$_value3);
        if ($settings['USEMAILER'])
          echo "</a>";

        out($newString[2]);
      }
    }
  }

  function EntryIfHomepage ( $inTRUE, $inFALSE = "", $inNULL = "") {
    // prints the homepage of the member if allowed
    global $settings,$entry;

    $_value = (is_null($entry['HOMEPAGE'])) ?
      null :
      vgb_removeHTML(vgb_string(vgb_UndoNoHTML(vgb_filterBadwords(vgb_noHTML($entry['HOMEPAGE']),$settings['FILTERHOMEPAGE']))),false);
    OutIf ($settings['ASKHOMEPAGE'],$inTRUE,$inFALSE,$inNULL,$_value);
  }

  function EntryIfICQ ( $inTRUE, $inFALSE = "", $inNULL = "") {
    // prints the ICQ-number of the member if allowed
    global $settings,$entry;

    $_value = (is_null($entry['ICQ'])) ?
      null : $entry['ICQ'];
    OutIf ($settings['ASKICQ'],$inTRUE,$inFALSE,$inNULL,$_value);
  }

  function EntryIfAIM ( $inTRUE, $inFALSE = "", $inNULL = "") {
    // prints the AIM-number of the member if allowed
    global $settings,$entry;

    $_value = (is_null($entry['AIM'])) ?
      null :
      vgb_removeHTML(vgb_string(vgb_UndoNoHTML(vgb_filterBadwords(vgb_noHTML($entry['AIM']),$settings['FILTERAIM']))),false);
    OutIf ($settings['ASKAIM'],$inTRUE,$inFALSE,$inNULL,$_value);
  }

  function EntryIfMSN ( $inTRUE, $inFALSE = "", $inNULL = "") {
    // prints the MSN-identity of the member if allowed
    global $settings,$entry;

    $_value = (is_null($entry['MSN'])) ?
      null :
      vgb_removeHTML(vgb_string(vgb_UndoNoHTML(vgb_filterBadwords(vgb_noHTML($entry['MSN']),$settings['FILTERMSN']))),false);
    OutIf ($settings['ASKMSN'],$inTRUE,$inFALSE,$inNULL,$_value);
  }

  function EntryIfYAHOO ( $inTRUE, $inFALSE = "", $inNULL = "") {
    // prints the YAHOO-identity of the member if allowed
    global $settings,$entry;

    $_value = (is_null($entry['YAHOO'])) ?
      null :
      vgb_removeHTML(vgb_string(vgb_UndoNoHTML(vgb_filterBadwords(vgb_noHTML($entry['YAHOO']),$settings['FILTERYAHOO']))),false);
    OutIf ($settings['ASKYAHOO'],$inTRUE,$inFALSE,$inNULL,$_value);
  }

  function EntryIfPrivate ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the link to a private entry if entry is private
    global $settings,$entry,$_param,$arg;

    if (!is_null($entry) && ($settings['ASKPRIVATE'])) {
      $_page = "";
      if (isset($arg[PFIX.'page']))
        $_page = $arg[PFIX.'page'];
      elseif (isset($arg[PFIX.'show']))
        $_page = $arg[PFIX.'show'];
      $newString = vgb_splitString($inTRUE);
      out($newString[0]);
      $_link = SCRIPTPATH."screen.".EXT."?vgbnigol=".$entry['ID'].
               "&amp;vgbxiferp=".PFIX."&amp;vgbegap=".$_page.$_param;
      echo "<a href='".$_link."' target='_top' $inTag>";
      out($newString[1]);
      echo "</a>";
      out($newString[2]);
    }
    else
      out($inFALSE);
  }

  function EntryIfCountry ( $inTRUE, $inFALSE = "", $inNULL = "") {
    // prints the countryname and flag of the member if allowed
    global $settings,$entry,$langC,$lang;

    if (is_null($entry['COUNTRY'])) {
      $_value = null;
      $_value2 = null;
    }
    else {
      // get the country-datas from the database
      $_query = vgb_query("select * from VGB_COUNTRY where ID = ".
                $entry['COUNTRY']);
      if (vgb_numrows($_query) == 0)
        Error($lang['wrongQueryResult'].$_q);
      $_country = vgb_result($_query);
      $_value = $_country['NAME'];
      $_value2 = SCRIPTPATH."flags/".$_country['FLAGICON'];

      // do we have to translate the country-name ?
      if ($_country['TRANSLATE'])
        $_value = ($_country['ID'] == 1) ?
          $lang['notGiven'] : $langC[$_value];
    }
    if (!is_Null($_value))
      $_value = vgb_string(vgb_removeHTML($_value));
    OutIf ($settings['ASKCOUNTRY'],$inTRUE,$inFALSE,$inNULL,
             $_value,null,$_value2);
  }

  function EntryIfRating ( $inTRUE, $inFALSE = "", $inNULL = "" ) {
    // prints all of the ratings of the entry
    global $ratings;

    // are there any rating-boxes defined ?
    $_query = vgb_query("select * from VGB_RATINGBOX".
              " order by PRIORITY asc, ID asc");
    if (($_max = vgb_numrows($_query)) == 0)
      out($inFALSE);
    else {
      // print the defined rating-boxes
      $_string = vgb_splitString($inTRUE);
      out($_string[0]);
      while ($_box = vgb_result($_query)) {

        $_value = (isset($ratings[$_box['ID']])) ?
          $ratings[$_box['ID']] : null;

        OutIf (TRUE,$_string[1],"",$inNULL,
               $_value,vgb_removeHTML(vgb_string($_box['NAME'])));
      }
      out($_string[2]);
    }
  }

  function EntryIfRatingPos ( $inPos, $inTRUE, $inFALSE = "",
                              $inNULL = "" ) {
    // prints rating-box of the given position if it exists
    global $ratings;

    // get the list of all boxes
    $_query = vgb_query("select * from VGB_RATINGBOX".
              " order by PRIORITY asc, ID asc");
    if ((vgb_numrows($_query)) < $inPos)
      out($inFALSE);
    else {
      for ($_i=0;$_i<$inPos;$_i++) {
        $_box = vgb_result($_query);
      }
      $_value = (isset($ratings[$_box['ID']])) ?
        $ratings[$_box['ID']] : null;
      OutIf (TRUE,$inTRUE,"",$inNULL,
             $_value,vgb_removeHTML(vgb_string($_box['NAME'])));
    }
  }

  function EntryIfCustom ( $inTRUE, $inFALSE = "", $inNULL = "" ) {
    // prints the customfields of the entry if allowed
    global $custom;

    // are there any custom-fields defined ?
    $_query = vgb_query("select * from VGB_CUSTOMFIELD".
              " order by PRIORITY asc, ID asc");
    if (($_max = vgb_numrows($_query)) == 0)
      out($inFALSE);
    else {
      // print the defined custom-fields
      $_string = vgb_splitString($inTRUE);
      out($_string[0]);
      while ($_field = vgb_result($_query)) {

        // is there an input for this entry ?
        $st = true;
        if (!isset($custom[$_field['ID']]))
          $_value = null;
        else {
          $_content = $custom[$_field['ID']];
          // is the content an index of a selection-box ?
          if ($_field['TYPE'] == 2) {
            // get the name of the selected index
            $_value = "";
            $_length = strlen(($_find = $_content."="));
            foreach (explode("\n",$_field['RULES']) as $_rule) {
              // check if the current rule is the one we´re searching for
              if (substr($_rule,0,$_length) == $_find)
                $_value = substr($_rule,$_length);
            }
          }
          else {
            $_value = $_content;
            if ($_field['TYPE'] == 0) {
               $_limit = trim($_field['RULES']);
               $_value = vgb_UndoNoHTML(vgb_wrapWords(vgb_string(vgb_filterBadwords(vgb_noHTML($_value),$_field['FILTER']))));
               $st = false;
            }
          }
        }
        if (!is_null($_value)) {
          $_value = ($st) ? vgb_removeHTML(vgb_string($_value),false) : vgb_removeHTML($_value,false);
        }
        OutIf (TRUE,$_string[1],"",$inNULL,$_value,
                 vgb_removeHTML(vgb_string($_field['NAME'])));
      }
      out($_string[2]);
    }
  }

  function EntryIfCustomPos ( $inPos, $inTRUE, $inFALSE = "",
                              $inNULL = "" ) {
    // prints the custom-field of the position if it exists
    global $custom;

    $_query = vgb_query("select * from VGB_CUSTOMFIELD".
              " order by PRIORITY asc, ID asc");
    if (($_max = vgb_numrows($_query)) < $inPos)
      out($inFALSE);
    else {
      for($_i=0;$_i<$inPos;$_i++) {
        $_field = vgb_result($_query);
      }
      // is there an input for this entry ?
      $_value2 = null;
      $st = true;
      if (!isset($custom[$_field['ID']]))
        $_value = null;
      else {
        $_content = $custom[$_field['ID']];
        // is the content an index of a selection-box ?
        if ($_field['TYPE'] == 2) {
          // get the name of the selected index
          $_value = "";
          $_length = strlen(($_find = $_content."="));
          foreach (explode("\n",$_field['RULES']) as $_rule) {
            // check if the current rule is the one we´re searching for
            if (substr($_rule,0,$_length) == $_find)
              $_value = substr($_rule,$_length);
          }
          $_value2 = $_content;
        }
        else {
          $_value = $_content;
          if ($_field['TYPE'] == 0) {
             $_limit = trim($_field['RULES']);
             $_value = vgb_UndoNoHTML(vgb_wrapWords(vgb_string(vgb_filterBadwords(vgb_noHTML($_value),$_field['FILTER']))));
             $st = false;
          }
        }
      }
      if (!is_null($_value))
        $_value = ($st) ? vgb_removeHTML(vgb_string($_value),false) : vgb_removeHTML($_value,false);
      OutIf (TRUE,$inTRUE,"",$inNULL,$_value,
               vgb_removeHTML(vgb_string($_field['NAME'])),$_value2);
    }
  }

  function EntryIfPicture ($inTRUE, $inFALSE = "", $inNULL = "", $inTag = "") {
    // prints the uploaded picture of an entry if available
    global $settings,$entry,$showPreview,$screenparam,$relpath;

    $_text = (is_null($entry['PICTEXT']) || (!$settings['ASKPICTEXT'])) ?
              "" :
              vgb_removeHTML(vgb_string(vgb_UndoNoHTML(vgb_filterBadwords(vgb_noHTML($entry['PICTEXT']),$settings['FILTERPICTEXT']))),false);
    if (is_null($entry['PICTURE']))
      $_value = null;
    else {
      unset($_w);
      $_value = "<img alt='".$_text."' title='".$_text."' src='".SCRIPTPATH."upload/".$entry['PICTURE']."' $inTag ";
      if (($settings['THUMBNAILX'] > 0) || ($settings['THUMBNAILY'] > 0)) {
        $size = @getImageSize($relpath."upload/".$entry['PICTURE']);
        if (count($size) > 1) {
          $_x = ((($size[0]-$settings['THUMBNAILX']) <= 0) || ($settings['THUMBNAILX'] == 0)) ? 0 : 1;
          $_y = ((($size[1]-$settings['THUMBNAILY']) <= 0) || ($settings['THUMBNAILY'] == 0)) ? 0 : 1;

          if (($_x > 0) || ($_y > 0)) {
            $_w = true;
            if (($_x == 0) || (($_y > 0) && (($size[1]/$size[0]*$settings['THUMBNAILX']) > $settings['THUMBNAILY'])))
              $_w = false;
            $_value .= ($_w) ? "width='".$settings['THUMBNAILX']."' " : "height='".$settings['THUMBNAILY']."' ";
            if ($showPreview)
              $_value = $_value." />";
            else {
              $url = SCRIPTPATH."screen.".EXT."?$screenparam&amp;vgberutcip=".$entry['ID'];
              $_value = "<a href='".$url."' target='_blank' onclick=\"pic=window.open('".$url.
                "','_blank','width=".$size[0].",height=".$size[1].",resizable=no,scrollbars=no'); if (window.focus)".
                " pic.focus(); return false;\">".$_value." /></a>";
            }
          }
        }
      }
      if (!isset($_w))
        $_value = $_value." />";
    }
    OutIf ($settings['ASKPICTURE'],$inTRUE,$inFALSE,$inNULL,$_value);
  }

  //*********************************************************************
  //                          form skin-commands
  //*********************************************************************

  function FormStart ( $inTag = "" ) {
    // prints the begin of the form
    global $settings,$lang,$_param,$_form,$showPreview,
           $singlepage,$entry_backup,$ratings,$custom,$ratings_backup,
           $custom_backup,$entry,$_entry;

    if (($singlepage) && (isset($entry_backup))) {
      $entry = $entry_backup;
      $ratings = $ratings_backup;
      $custom = $custom_backup;
    }
    if ($settings['USEJAVASCRIPT'] && !(($_form == 0) && $showPreview)) {
      // insert javascript check-routines for the selected input
      echo "<script type='text/javascript'>\n".
           "<!--\n".
           "function isEmpty(inString) {\n".
           "  var Empty = true;\n".
           "  for (var i=0;i<inString.length;i++) {\n".
           "    if ((inString.charAt(i) != ' ') &&\n".
           "        (inString.charAt(i) != '\\t') &&\n".
           "        (inString.charAt(i) != '\\r') &&\n".
           "        (inString.charAt(i) != '\\n')) {\n".
           "      Empty = false;\n".
           "    }\n".
           "  }\n".
           "  return Empty;\n".
           "}\n".
           "\n";

      if ($settings['USEEMOTICONS']) {
        echo "function icon(zeichen) {\n".
             "  document.form.".PFIX."ENTRY.value += zeichen;\n".
             "  document.form.".PFIX."ENTRY.focus();\n".
             "}\n".
             "\n";
      }

      echo "function check() {\n".
           "  if(isEmpty(document.form.".PFIX."NAME.value))  {\n".
           "    alert('".vgb_JSout($lang['noName'])."');\n".
           "    document.form.".PFIX."NAME.focus();\n".
           "    return false;\n".
           "  }\n".
           "  if(isEmpty(document.form.".PFIX."ENTRY.value)) {\n".
           "    alert('".vgb_JSout($lang['noEntry'])."');\n".
           "    document.form.".PFIX."ENTRY.focus();\n".
           "    return false;\n".
           "  }\n".
           "  var pfx = '".addSlashes($settings['PASSPREFIX'])."';\n ".
           " if (document.form.".PFIX."NAME.value.substring(0,pfx.length).toLowerCase() != pfx) {\n";
      if ($settings['FORCECOUNTRY'] && $settings['ASKCOUNTRY']) {
        echo "  if(document.form.".PFIX."COUNTRY.value == '') {\n".
             "    alert('".vgb_JSout($lang['noCountry'])."');\n".
             "    document.form.".PFIX."COUNTRY.focus();\n".
             "    return false;\n".
             "  }\n";
      }

      if ($settings['FORCEEMAIL'] && $settings['ASKEMAIL']) {
        echo "  if(document.form.".PFIX."EMAIL.value == '') {\n".
             "    alert('".vgb_JSout($lang['noEmail'])."');\n".
             "    document.form.".PFIX."EMAIL.focus();\n".
             "    return false;\n".
             "  }\n";
      }

      $_query = vgb_query("select ID, NAME, FRCE from VGB_RATINGBOX");
      while ($_box = vgb_result($_query)) {
        if ($_box['FRCE']) {
           echo "  if(document.form.".PFIX."RATING".$_box['ID'].
                ".value == '') {\n".
                "    alert('".vgb_JSout($lang['noRating']).
                              vgb_JSout(addSlashes(vgb_string($_box['NAME']))).
                "');\n".
                "    document.form.".PFIX."RATING".$_box['ID'].
                 ".focus();\n".
                "    return false;\n".
                " }\n";
        }
      }

      $_query = vgb_query("select ID, NAME, FRCE from VGB_CUSTOMFIELD");
      while ($_field = vgb_result($_query)) {
        if ($_field['FRCE']) {
           echo "  if(isEmpty(document.form.".PFIX."CUSTOM".$_field['ID'].
                ".value)) {\n".
                "    alert('".vgb_JSout($lang['noFieldValue']).
                              vgb_JSout(addSlashes(vgb_string($_field['NAME']))).
                "');\n".
                "    document.form.".PFIX."CUSTOM".$_field['ID'].
                ".focus();\n".
                "    return false;\n".
                " }\n";
        }
      }

      echo "  }\n".
           "  return true;\n".
           "}\n".
           "//-->\n".
           "</script>\n";
    }

    echo "<form ";
    if (!(($_form==0) && $showPreview)) {
      echo "name='form' ";
    }
    echo "action='".MSCRIPT;
    if ($_param != "")
      echo "?".$_param;
    echo "' method='post' ";
    if ($settings['ASKPICTURE'] && !(($_form==0) && $showPreview))
      echo "enctype='multipart/form-data' ";

    out($inTag);
    if ($settings['USEJAVASCRIPT'] && !(($_form==0) && $showPreview))
      echo " onsubmit='return check()'";
    echo ">";
    $_form++;
  }

  function FormEnd () {
    // prints the end of the form

    echo "</form>";
  }

  function FormIfMSG ( $inStatus, $inError, $inFALSE = "" ) {
    // prints a status- or error-message if available
    global $statusMSG,$errorMSG,$oldFilename,$lang;

    if (isset($statusMSG))
      out($inStatus,$statusMSG);
    elseif ((isset($errorMSG)) && ($errorMSG != "")) {
      if (isset($oldFilename) && ($oldFilename != ""))
        $errorMSG .= "<br /><br />".$lang['reselect2'];
      out($inError,$errorMSG);
    }
    else
      out($inFALSE);
  }

  function FormName ( $inTag = "" ) {
    // prints the textfield for the name
    global $settings,$_entry;

    echo "<input type='text' name='".PFIX."NAME' value='";
    if (isset($_entry['NAME']))
      echo vgb_formdata($_entry['NAME']);
    out("' maxlength='".$settings['MAXLENNAME']."' ".$inTag." />");
  }

  function FormText ( $inTag = "" ) {
    // prints the textarea for the entry
    global $_entry;

    out("<textarea name='".PFIX."ENTRY' $inTag>");
    if (isset($_entry['ENTRY']))
      echo vgb_formdata($_entry['ENTRY']);
    echo "</textarea>";
  }

  function FormIfBBCode ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the link to the BBCode info page if activated
    global $settings,$screenparam;

    if ($settings['USEBBCODE']) {
      $_newString = vgb_splitString($inTRUE);
      out($_newString[0]);
      $_link = SCRIPTPATH."screen.".EXT."?$screenparam&amp;vgbedocbb=0";
      echo "<a href='".$_link.
         "' target='_blank' onclick=\"bbcode=window.open('".$_link.
         "','_blank','width=540,scrollbars=yes,resizable=yes'); if (window.focus)".
         " bbcode.focus(); return false;\" $inTag>";
      out($_newString[1]);
      echo "</a>";
      out($_newString[2]);
    }
    else
      Out($inFALSE);
  }

  function FormIfEmail ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for email if allowed
    global $_entry,$settings,$optional,$required;

    $_value = "<input type='text' name='".PFIX."EMAIL' maxlength='".
              $settings['MAXLENEMAIL']."' value='";
    if (isset($_entry['EMAIL']))
      $_value .= vgb_formdata($_entry['EMAIL']);
    $_value .= "' $inTag />";
    if ($required == "")
      $_value2 = ($settings['FORCEEMAIL']) ? "" : $optional;
    else
      $_value2 = ($settings['FORCEEMAIL']) ? $required : "";
    OutIf($settings['ASKEMAIL'],$inTRUE,$inFALSE,"",
          $_value,null,null,$_value2);
  }

  function FormIfHomepage ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for homepage if allowed
    global $_entry,$settings,$optional;

    $_value = "<input type='text' name='".PFIX."HOMEPAGE' maxlength='".
              $settings['MAXLENHOMEPAGE']."' value='http://";
    if (isset($_entry['HOMEPAGE']))
      $_value .= vgb_formdata($_entry['HOMEPAGE']);
    $_value .= "' $inTag />";
    OutIf($settings['ASKHOMEPAGE'],$inTRUE,$inFALSE,"",
            $_value,null,null,$optional);
  }

  function FormIfPictureText ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for homepage if allowed
    global $_entry,$settings,$optional;

    $_value = "<input type='text' name='".PFIX."PICTEXT' maxlength='".vgb_maxlen().
              "' value='";
    if (isset($_entry['PICTEXT']))
      $_value .= vgb_formdata($_entry['PICTEXT']);
    $_value .= "' $inTag />";
    OutIf(($settings['ASKPICTEXT'] && $settings['ASKPICTURE']),$inTRUE,$inFALSE,"",
            $_value,null,null,$optional);
  }

  function FormIfICQ ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for the ICQ-number if allowed
    global $_entry,$settings,$optional;

    $_value = "<input type='text' name='".PFIX."ICQ' maxlength='10'".
              " value='";
    if (isset($_entry['ICQ']))
      $_value .= vgb_formdata($_entry['ICQ']);
    $_value .= "' $inTag />";
    OutIf($settings['ASKICQ'],$inTRUE,$inFALSE,"",
          $_value,null,null,$optional);
  }

  function FormIfAIM ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for the AIM-identity if allowed
    global $_entry,$settings,$optional;

    $_value = "<input type='text' name='".PFIX."AIM' maxlength='".
              $settings['MAXLENAIM']."' value='";
    if (isset($_entry['AIM']))
      $_value .= vgb_formdata($_entry['AIM']);
    $_value .= "' $inTag />";
    OutIf($settings['ASKAIM'],$inTRUE,$inFALSE,"",
            $_value,null,null,$optional);
  }

  function FormIfMSN ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for the MSN-identity if allowed
    global $_entry,$settings,$optional;

    $_value = "<input type='text' name='".PFIX."MSN' maxlength='".
              $settings['MAXLENMSN']."' value='";
    if (isset($_entry['MSN']))
      $_value .= vgb_formdata($_entry['MSN']);
    $_value .= "' $inTag />";
    OutIf($settings['ASKMSN'],$inTRUE,$inFALSE,"",
            $_value,null,null,$optional);
  }

  function FormIfYAHOO ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the textfield for the YAHOO-identity if allowed
    global $_entry,$settings,$optional;

    $_value = "<input type='text' name='".PFIX."YAHOO' maxlength='".
              $settings['MAXLENYAHOO']."' value='";
    if (isset($_entry['YAHOO']))
      $_value .= vgb_formdata($_entry['YAHOO']);
    $_value .= "' $inTag />";
    OutIf($settings['ASKYAHOO'],$inTRUE,$inFALSE,"",
            $_value,null,null,$optional);
  }

  function FormIfPrivate ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the checkbox for a private entry if allowed
    global $settings,$entry,$optional;

    $_value = "<input type='text' name='".PFIX."PRIVATE' maxlength='20' value='";
    if (isset($entry['PRIVATE']) && (!is_null($entry['PRIVATE'])))
      $_value .= vgb_formdata($entry['PRIVATE']);
    $_value .= "' $inTag />";
    OutIf($settings['ASKPRIVATE'],$inTRUE,$inFALSE,"",$_value,
          null,null,$optional);
  }

  function FormIfHideEmail ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the checkbox for hide email entry if allowed
    global $settings,$_entry;

    $_value = "<input type='checkbox' name='".PFIX."HIDEEMAIL' value='1' ";
    if (isset($settings['ASKHIDEEMAIL']) && ($_entry['HIDEEMAIL'] == 1))
      $_value .= "checked='checked'";
    $_value .= " $inTag />";
    OutIf($settings['ASKHIDEEMAIL'],$inTRUE,$inFALSE,"",$_value);
  }

  function FormIfCountry ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the selection for the country if allowed
    global $_entry,$settings,$lang,$langC,$optional,$required,$showPreview;

    $_value = "<select name='".PFIX."COUNTRY' $inTag><option value=''> &nbsp; </option>";
    $_query = vgb_query("select * from VGB_COUNTRY where ID > 1");

    // get the list of countries and sort the list by names
    $_countries = array();
    while ($_country = vgb_result($_query)) {
      if ($_country['NAME'] != "0") {
        $_name = ($_country['TRANSLATE']) ? $langC[$_country['NAME']] :
          $_country['NAME'];
        $_countries[$_country['ID']] = $_name;
       }
    }
    uasort($_countries,"vgb_stringsort");
    $_countries[1] = $langC['0'];

    if (is_null($_entry['COUNTRY']))
      $_selected = (is_null($settings['PRECOUNTRY']) || $showPreview) ?
        0 : $settings['PRECOUNTRY'];
    else
      $_selected = $_entry['COUNTRY'];

    // generate country-selection
    foreach ($_countries as $_id => $_name) {
      $_value .= "<option value='".$_id."'";
      if ($_id == $_selected)
        $_value .= " selected='selected'";
      $_value .= ">";
      $_value .= vgb_removeHTML(vgb_string($_name))."</option>";
    }
    $_value .= "</select>";
    if ($required == "")
      $_value2 = ($settings['FORCECOUNTRY']) ? "" : $optional;
    else
      $_value2 = ($settings['FORCECOUNTRY']) ? $required : "";

    OutIf($settings['ASKCOUNTRY'],$inTRUE,$inFALSE,"",
          $_value,null,null,$_value2);
  }

  function FormIfRating ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints all of the rating-boxes if defined
    global $settings,$_ratings,$lang,$optional,$required;

    $_query = vgb_query("select * from VGB_RATINGBOX order by PRIORITY asc");
    if (vgb_numrows($_query) == 0)
      out($inFALSE);
    else {
      $_string = vgb_splitString($inTRUE);
      out($_string[0]);
      while ($_box = vgb_result($_query)) {
        $_selected = (isset($_ratings[$_box['ID']])) ?
          $_ratings[$_box['ID']] : 0;
        $_value = "<select name='".PFIX."RATING".$_box['ID']."' $inTag>";
        $_value .= "<option value='' ";
        if ($_selected == 0) $_value .= "selected='selected'";
        $_value .= "> &nbsp;</option><option value='5'";
        if ($_selected == 5) $_value .= "selected='selected'";
        $_value .= "> 5 ".$lang['good']."</option><option value='4'";
        if ($_selected == 4) $_value .= "selected='selected'";
        $_value .= "> 4 </option><option value='3'";
        if ($_selected == 3) $_value .= "selected='selected'";
        $_value .= "> 3 </option><option value='2'";
        if ($_selected == 2) $_value .= "selected='selected'";
        $_value .= "> 2 </option><option value='1'";
        if ($_selected == 1) $_value .= "selected='selected'";
        $_value .= "> 1 ".$lang['poor'];
        $_value .= "</option></select>";
        if ($required == "")
          $_optional = ($_box['FRCE']) ? "" : $optional;
        else
          $_optional = ($_box['FRCE']) ? $required : "";
        $_name = ($_box['FORMTEXT'] == '') ? $_box['NAME'] : $_box['FORMTEXT'];
        out($_string[1],$_value,
            vgb_removeHTML(vgb_string($_name)),null,$_optional);
      }
      out($_string[2]);
    }
  }

  function FormIfCustom ( $inTRUE, $inFALSE = "",
                          $inTagText = "",
                          $inTagNumber = "", $inTagSelect = "") {
    // prints the different custom-fields if defined
    global $settings,$lang,$_custom,$optional,$required,$showPreview;

    $_query = vgb_query("select * from VGB_CUSTOMFIELD order by PRIORITY asc");
    if (vgb_numrows($_query) == 0)
      out($inFALSE);
    else {
      $_string = vgb_splitString($inTRUE);
      out($_string[0]);
      while ($_field = vgb_result($_query)) {
        if ($_field['TYPE'] == 2) {
          // the custom-field is a selection
          $_value = "<select name='".PFIX."CUSTOM".$_field['ID']."'".
                    " $inTagSelect>".
                    "<option value=''> &nbsp;";
          $_options = explode("\n",$_field['RULES']);
          foreach ($_options as $option) {
            if (($_pos = substr_count($option,"=")) > 0) {
              $_rule = explode("=",$option,2);
              $_value .= "</option><option value='".vgb_formdata($_rule[0])."'";
              if (isset($_custom[$_field['ID']])) {
                if ($_custom[$_field['ID']] == $_rule[0]) {
                  $_value .= "selected='selected'";
                }
              }
              elseif (!$showPreview && ($_field['PREALLOCATE'] == $_rule[0]))
                $_value .= "selected='selected'";
              $_value .="> ".
                 vgb_removeHTML(vgb_string($_rule[1]))." ";
            }
          }
          $_value .= "</option></select>";
        }
        else {
          // the custom-field is text-input
          $_value = "<input type='text' name='".PFIX."CUSTOM".$_field['ID'].
                    "' value='";
          if (!isset($_custom[$_field['ID']])) {
            if (!is_null($_field['PREALLOCATE']) && !$showPreview)
              $_value .= vgb_formdata($_field['PREALLOCATE']);
          }
          else
            $_value .= vgb_formdata($_custom[$_field['ID']]);
          $_value .= "' maxlength='";
          if ($_field['TYPE'] == 1) {
            // the input is a number
            $_rules = explode("\n",$_field['RULES'],2);
            // is there a valid rule in the first line ?
            if ($_rules[0] != "") {
              $_rule = explode("-",$_rules[0]);
              if ($_rule[1] != "")
                // set the maximum from the rule
                $_value .= strlen($_rule[1]);
              else
                // set the maximum from the integer-boundary
                $_value .= strlen("999999999");
            }
            else
               // no rule => set integer-boundary as maximum
               $_value .= strlen("999999999");
            $_value .= "' $inTagNumber />";
          }
          else {
            // the input is text
            $_rules = explode("\n",$_field['RULES'],2);
            if ($_rules[0] != "")
              // set the given length as maximum
              $_value .= $_rules[0];
            else
              // no rule => set string-maximum
              $_value .= vgb_maxlen();
            $_value .= "' $inTagText />";
          }
        }
        if ($required == "")
          $_optional = ($_field['FRCE']) ? "" : $optional;
        else
          $_optional = ($_field['FRCE']) ? $required : "";
        $_name = ($_field['FORMTEXT'] == '') ? $_field['NAME'] :
                  $_field['FORMTEXT'];
        out($_string[1],$_value,
          vgb_removeHTML(vgb_string($_name)),
          null,$_optional);
      }
      out($_string[2]);
    }
  }

  function FormIfEmoticons ( $inTRUE, $inFALSE = "", $inTag = "",
                             $inIFRAME = "", $inIFrameTag = "" ) {
    // prints the selection for the emoticons if allowed
    global $settings,$skinDir,$emoticons;

    if ($settings['USEEMOTICONS']) {

      if ((!$settings['USEIFRAME']) || ($inIFRAME == "")) {
      $_string = vgb_splitString($inTRUE);
      out($_string[0]);
      $_emoticon = 0;
      while ($_emoticon < sizeof($emoticons)) {

        $_newString = "";
        $_depth = 0;
        $_pos = 0;
        while ($_pos < strlen($_string[1])) {
          if (($_string[1][$_pos] == '<') &&
             ($_string[1][$_pos+1] == '?')) {
            $_pos++;
            $_depth++;
            $_newString .= "<?";
          }
          elseif (($_string[1][$_pos] == '?') &&
                  ($_string[1][$_pos+1] == '>')) {
            $_pos++;
            $_depth++;
            $_newString .= "?>";
          }
          elseif (($_depth == 0) && ($_string[1][$_pos] == '§') &&
                  ($_string[1][$_pos+1] == '1')) {
            $_pos++;
            if ($_emoticon < sizeof($emoticons)) {
              if ($settings['USEJAVASCRIPT']) {
                $_newString .= "<a href=\"javascript:icon('".
                   $emoticons[$_emoticon][0].
                   "')\"><img alt='' border='0' src='".SCRIPTPATH.$skinDir."emoticons/".
                $emoticons[$_emoticon][1]."' $inTag /></a>";
              }
              else {
                $_newString .= "<img border='0' src='".SCRIPTPATH.$skinDir.
                  "emoticons/".$emoticons[$_emoticon][1]."' alt=' ".
                  vgb_formdata($emoticons[$_emoticon][0])." ' title=' ".
                  vgb_formdata($emoticons[$_emoticon][0])." ' $inTag />";
              }
              $_emoticon++;
            }
          }
          else
            $_newString .= $_string[1][$_pos];
          $_pos++;
        }
        out($_newString);

      }
      out($_string[2]);
      }
      else {
        // use iFrame
        $_string = explode("§1",$inIFRAME,2);
        if (count($_string) == 1)
          $_string[1] == "";
        out($_string[0]);
        echo "<iframe src='".SCRIPTPATH."screen.".EXT."?vgbnocitome=0' $inIFrameTag></iframe>";
        out($_string[1]);
      }
    }
    else
      out($inFALSE);
  }

  function FormIfPicture ( $inTRUE, $inFALSE = "", $inTag = "") {
    // prints the uploadfield for a picture if allowed
    global $settings,$optional;

    $_query = vgb_query("select MINX, MAXX, MINY, MAXY from VGB_SETTINGS");
    $_size = vgb_result($_query);
    $_value2 = $_size[0];
    if ($_size[0] < $_size[1])
      $_value2 .= "-".$_size[1];
    $_value3 = $_size[2];
    if ($_size[2] < $_size[3])
      $_value3 .= "-".$_size[3];
    $_value = "<input type='file' name='".PFIX."UPLOAD' $inTag />";
    OutIf($settings['ASKPICTURE'],$inTRUE,$inFALSE,"",
            $_value,$_value2,$_value3,$optional);
  }

  function FormSendButton ( $inName, $inGraphic = FALSE, $inTag = "" ) {
    // prints the send-button either as text-button or graphic
    global $settings,$skinDir;

    echo "<input type=";
    if ($inGraphic)
      echo "'image' src='".SCRIPTPATH."$skinDir";
    else
      echo "'submit' value='";
    out("$inName' name='".PFIX."send' $inTag />");
  }

  function FormPreviewButton ( $inName, $inGraphic = FALSE, $inTag = "") {
    // prints the preview-button either as text-button or graphic
    global $settings,$skinDir;

    echo "<input type=";
    if ($inGraphic)
      echo "'image' src='".SCRIPTPATH."$skinDir";
    else
      echo "'submit' value='";
    out("$inName' name='".PFIX."preview' $inTag />");
  }

  function FormIfPreview ( $inTRUE, $inFALSE = "", $inWARN = null,
                           $inFORMEND = true ) {
    // prints the preview of the entry if allowed
    global $showPreview,$oldFilename,$lang,$_entry,$entry,$parameters;

    $inWARN = null;
    if (is_null($inWARN))
      $inWARN = $inTRUE;
    if (isset($showPreview)) {
      if (isset($oldFilename) && ($oldFilename != "")) {
        $_string = vgb_divideString($inWARN);
        $_str = $lang['reselect'];
      }
      else {
        $_string = vgb_divideString($inTRUE);
        $_str = null;
      }
      Out($_string[0],"",$_str);
      if (isset($_string[1])) {
        loadSkin("skinEntry.php");
        Out($_string[1],"",$_str);
      }
      // create hidden fields for the preview
      $_l = strlen(PFIX);
      foreach($parameters as $_param) {
        $_val = $_entry[substr($_param,$_l)];
        echo "<input type='hidden' name='".$_param."' value='".vgb_formdata($_val)."' />";
      }
      echo "<input type='hidden' name='".PFIX."HIDEEMAIL' value='".$_entry['HIDEEMAIL']."' />";
      if (isset($entry['PICTURE']) && (substr($entry['PICTURE'],0,7) == "preview"))
        echo "<input type='hidden' name='".PFIX."PICTURE' value='".$entry['PICTURE']."' />";
      if ($inFORMEND)
        Out("</form><?php FormStart()?>");
    }
    else
      out($inFALSE);
  }

  //*********************************************************************
  //                          stats skin-commands
  //*********************************************************************

  function StatsTotalEntries() {
    // prints the total number of guestbook-entries
    global $maxEntry,$settings;

    echo $maxEntry+$settings['PASTENTRIES'];
  }

  function StatsIfPastEntries( $inTRUE, $inFALSE = "" ) {
    // prints the number of entries that are no longer in database
    global $settings;

    if ($settings['PASTENTRIES'] > 0)
      out($inTRUE,$settings['PASTENTRIES']);
    else
      out($inFALSE);
  }

  function StatsVisitors () {
    global $settings;

    echo $settings['VISITORS'];
  }

  function StatsUsersBrowsing() {
    $query = vgb_query("select * from VGB_VISITOR");
    echo vgb_numrows($query);
  }

  function StatsOnlineDate ( $inSeperator = "." ) {
    // prints the date when the guestbook was installed
    global $settings,$lang;

    $_date = explode("-",$settings['ONLINEDATE']);
    echo vgb_dateOut($_date,$inSeperator);
  }

  function StatsNewEntryAt () {
    // prints the average number of entries per day
    global $settings,$maxEntry,$lang;

    // how many days are past ?
    $_date = explode("-",$settings['ONLINEDATE']);
    $_today = getdate(time());
    $_days = (mktime(0,0,0,$_today['mon'],$_today['mday'],$_today['year'])
             -mktime(0,0,0,$_date[1],$_date[2],$_date[0]))/86400+1;
    if ($_days == 0)
      $_days = 1;
    if (round((float)($_days/($maxEntry+$settings['PASTENTRIES'])))> 1)
      echo $lang['all']." ".
      (round((float)($_days/($maxEntry+$settings['PASTENTRIES'])))).
      " ".$lang['days'];
    else
      echo (round((float)(($maxEntry+$settings['PASTENTRIES'])/$_days))).
      " ".$lang['perDay'];
  }

  function StatsVisitorAt () {
    // prints the average number of visitors
    global $settings,$lang;

    // how many days are past ?
    $_date = explode("-",$settings['VISITORSSINCE']);
    $_today = getdate(time());
    $_days = (mktime(0,0,0,$_today['mon'],$_today['mday'],$_today['year'])
             -mktime(0,0,0,$_date[1],$_date[2],$_date[0]))/86400+1;
    if (round((float)($_days/($settings['VISITORS'])))> 1)
      echo $lang['all']." ".
      (round((float)($_days/($settings['VISITORS'])))).
      " ".$lang['days'];
    else
      echo (round((float)(($settings['VISITORS'])/$_days))).
      " ".$lang['perDay'];
  }

  function StatsBrowser( $inString ) {
    // generates the list of browser-statistics
    global $lang,$browsers,$maxEntry,$user,$settings,$entryfilter,$filteradd;

    // get the browsers of the entries
    $_other = 0;
    $_total = 0;
    $_browsers = array();
    $_query = vgb_query("select e.ID, e.BROWSER from VGB_ENTRY e $filteradd".$entryfilter);
    while ($_entry = vgb_result($_query)) {
      $_total++;
      if (!isset($user[$_entry['ID']]))
        $user[$_entry['ID']] = vgb_decodeBrowserID($_entry['BROWSER']);
      $_name = $user[$_entry['ID']][1];
      if (($_name == "Netscape Navigator ".$lang['orOther']) ||
          ($_name == $lang['unknownBrowser'])) {
        $_other++;
        $_othername = $_name;
      }
      else
        if (isset($_browsers[$_name]))
          $_browsers[$_name]++;
        else
          $_browsers[$_name] = 1;
    }
    arsort($_browsers,SORT_NUMERIC);
    if ($_other > 0)
      $_browsers[$_othername] = $_other;

    $_i = 0;
    $_other = 0;
    foreach ($_browsers as $_name => $_count) {
      $_id = "";
      foreach ($browsers as $browser) {
        if (substr($_name,0,strlen($browser[2])) == $browser[2]) {
          $_id = $browser[0];
          break;
        }
      }
      $_i++;
      if (($settings['LIMITBROWSER'] > 0) && ($settings['LIMITBROWSER'] < $_i))
        $_other += $_count;
      else
        out($inString,$_count,vgb_removeHTML($_name),
            vgb_short(round((FLOAT)((100*$_count/$maxEntry)),2)),
            $_id);
    }
    if ($_other > 0) {
      out($inString,$_other,$lang['otherBrowser'],
          vgb_short(round((FLOAT)((100*$_other/$maxEntry)),2)),
            "x");
    }
  }

  function StatsOS( $inString ) {
    // generates the list of browser-statistics
    global $lang,$systems,$maxEntry,$user,$settings,$entryfilter,$filteradd;

    // get the browsers of the entries
    $_other = 0;
    $_total = 0;
    $_systems = array();
    $_query = vgb_query("select e.ID, e.BROWSER from VGB_ENTRY e $filteradd".$entryfilter);
    while ($_entry = vgb_result($_query)) {
      $_total++;
      if (!isset($user[$_entry['ID']]))
        $user[$_entry['ID']] = vgb_decodeBrowserID($_entry['BROWSER']);
      $_name = $user[$_entry['ID']][3];
      if ($_name == $lang['unknownOS']) {
        $_other++;
        $_othername = $_name;
      }
      else
        if (isset($_systems[$_name]))
          $_systems[$_name]++;
        else
          $_systems[$_name] = 1;
    }
    arsort($_systems,SORT_NUMERIC);
    if ($_other > 0)
      $_systems[$_othername] = $_other;

    $_other = 0;
    $_i = 0;
    foreach ($_systems as $_name => $_count) {
      $_id = "";
      foreach ($systems as $system) {
        if (substr($_name,0,strlen($system[2])) == $system[2]) {
          $_id = $system[0];
          break;
        }
      }
      $_i++;
      if (($settings['LIMITOS'] > 0) && ($settings['LIMITOS'] < $_i))
        $_other += $_count;
      else
        out($inString,$_count,vgb_removeHTML($_name),
            vgb_short(round((FLOAT)((100*$_count/$maxEntry)),2)),
            $_id);
    }
    if ($_other > 0) {
      out($inString,$_other,$lang['otherOS'],
          vgb_short(round((FLOAT)((100*$_other/$maxEntry)),2)),
            "x");
    }
  }

  function StatsIfCountry( $inTRUE, $inFALSE = "") {
    // generates a list of countries
    global $settings,$skinDir,$maxEntry,$lang,$langC,$entryfilter,$filteradd;

    if ($settings['ASKCOUNTRY']) {
      // get the list of countries from the database
      if (substr($entryfilter,0,6) == " where")
        $_entryfilter = " and ".substr($entryfilter,6);
      else
        $_entryfilter = $entryfilter;
      $_query = vgb_query("select e.COUNTRY, c.NAME, FLAGICON,".
       " TRANSLATE, count(e.COUNTRY) as NUMBER from VGB_ENTRY e, VGB_COUNTRY c".
       " $filteradd where e.COUNTRY = c.ID $_entryfilter group by e.COUNTRY order by NUMBER desc");

      $_total = 0;
      $_i = 0;
      $_other = 0;
      $_newString = vgb_splitString($inTRUE);
      out($_newString[0]);
      // print each country with statistics
      while ($_row = vgb_result($_query)) {
        $_c[3] = SCRIPTPATH."flags/".$_row['FLAGICON'];
        $_c[1] = ($_row['TRANSLATE']) ? $langC[$_row['NAME']]
                 : $_row['NAME'];
        $_c[0] = $_row['NUMBER'];
        $_total += $_c[0];
        $_c[2] = vgb_short(round((FLOAT)(100*$_c[0]/$maxEntry),2));
        $_i++;
        if (($_row['COUNTRY'] == 1) || (($settings['LIMITCOUNTRY'] > 0) &&
            ($settings['LIMITCOUNTRY'] < $_i)))
          $_other += $_c[0];
        else
          out($_newString[1],$_c[0],vgb_removeHTML(vgb_string($_c[1])),$_c[2],$_c[3]);
      }
      // do we have people from countries that are not listed ?
      if (($_other)>0) {
        out($_newString[1],$_other,$langC['0'],
            vgb_short(round((FLOAT)(100*$_other/$maxEntry),2)),SCRIPTPATH.
            "flags/empty.gif");
      }
      // were that all entries ?
      if (($_remnant = $maxEntry-$_total) > 0)
        out($_newString[1],$_remnant,$lang['noInput'],
           vgb_short(round((FLOAT)(100*$_remnant/$maxEntry),2)),SCRIPTPATH.
           "flags/empty.gif");
      out($_newString[2]);
    }
    else
      out($inFALSE);
  }

  function StatsIfRating( $inTRUE, $inFALSE = "", $inNULL = "") {
    // generate the statistics for the allowed rating-boxes
    global $lang,$entryfilter,$filteradd;

    $_query = vgb_query("select * from VGB_RATINGBOX order by".
      " PRIORITY asc");

    if (substr($entryfilter,0,6) == " where")
      $_entryfilter = " and ".substr($entryfilter,6);
    else
      $_entryfilter = $entryfilter;
    // are there any rating_boxes defined ?
    $_number = 0;
    $_max = vgb_numrows($_query);
    for ($_i=0;$_i<$_max;$_i++) {
      $_box = vgb_result($_query);
      if ($_box['STATS']) {
        // generate statistics for this box
        if ($_number == 0) {
          // we have to print the first box => initialize newString
          $_newString = vgb_splitString($inTRUE);
          out($_newString[0]);
        }
        $_number++;
        // get the average of the entries for each rating-box
        $_query2 = vgb_query("select round(avg(r.RATING),2)".
          " from VGB_RATING r, VGB_ENTRY e $filteradd where r.ENTRY_ID = e.ID and r.BOX_ID = ".$_box['ID'].$_entryfilter);
        // print the statistics for this rating-box
        $_row = vgb_fetchrow($_query2);
        $_string = (is_null($_row[0])) ? $inNULL : $_newString[1];
        $_result = (is_null($_row[0])) ? "" : vgb_short($_row[0]);
        $_round  = (is_null($_row[0])) ? "" : (round($_row[0]));
        out($_string,$_result,
            vgb_removeHTML(vgb_string($_box['NAME'])),$_round);
      }
    }
    if ($_number == 0)
      // we have no rating-boxes for the stats
      out($inFALSE);
    else
      out($_newString[2]);
  }

  function StatsIfCustomNumber( $inTRUE, $inFALSE = "", $inNULL = "") {
    // generate the statistics for the allowed number-custom-fields
    global $lang,$entryfilter,$filteradd;

    $_query = vgb_query("select * from VGB_CUSTOMFIELD where ".
      "TYPE = 1 order by PRIORITY asc");

    if (substr($entryfilter,0,6) == " where")
      $_entryfilter = " and ".substr($entryfilter,6);
    else
      $_entryfilter = $entryfilter;
    // are there any number-custom-fields defined ?
    $_number = 0;
    $_max = vgb_numrows($_query);
    for ($_i=0;$_i<$_max;$_i++) {
      $_field = vgb_result($_query);
      if ($_field['STATS']) {
        // generate statistics for this field
        if ($_number == 0) {
          // we have to print the first field => initialize newString
          $_newString = vgb_splitString($inTRUE);
          out($_newString[0]);
        }
        $_number++;
        // calculate the average of the values
        $_query2 = vgb_query("select round(avg(c.CONTENT),2)".
          " as RESULT from VGB_CUSTOMENTRY c, VGB_ENTRY e $filteradd where c.ENTRY_ID = e.ID and c.FIELD_ID = ".
          $_field['ID'].$_entryfilter);
        $_row = vgb_fetchrow($_query2);
        $_string = (is_null($_row[0])) ? $inNULL : $_newString[1];
        $_result = (is_null($_row[0])) ? "" : vgb_short($_row[0]);
        $_round  = (is_null($_row[0])) ? "" : round($_row[0]);
        out($_string,$_result,vgb_removeHTML(vgb_string($_field['NAME'])),$_round);
      }
    }
    if ($_number == 0)
      // we have no number-custom-fields for the statistics
      out($inFALSE);
    else
      out($_newString[2]);
  }

  function StatsIfCustomSelect ($inTRUE, $inFALSE = "", $inNULL = "") {
    // generate the statistics for the allowed custom-selections
    global $lang,$maxEntry,$entryfilter,$filteradd;

    // devide the input-string if possible
    $_newString = vgb_splitString($inTRUE);

    if (substr($entryfilter,0,6) == " where")
      $_entryfilter = " and ".substr($entryfilter,6);
    else
      $_entryfilter = $entryfilter;
    // check every defined custom-selection
    $_query = vgb_query("select * from VGB_CUSTOMFIELD where ".
      "TYPE = 2 order by PRIORITY asc");
    $_max = vgb_numrows($_query);
    $_noField = TRUE;

    for ($_j=0;$_j<$_max;$_j++) {
      $_number = 0;
      $_field = vgb_result($_query);
      // do we have to generate the statistics for this selection ?
      if ($_field['STATS']) {
        $_noField = FALSE;

        // get the names for the indeces of this selection
        $_set = array();
        $_rules = explode("\n",$_field['RULES']);
        foreach ($_rules as $_rule) {
          if (substr_count($_rule,"=") > 0) {
            $_entry = explode("=",$_rule,2);
            $_set[$_entry[0]] = $_entry[1];
          }
        }

        // is this the first index of the selection ?
        if ($_number == 0)
          out($_newString[0],null,vgb_removeHTML(vgb_string($_field['NAME'])));
        $_number++;
        // get the statistics for this selection from the database
        $_query2 = vgb_query("select c.CONTENT, count(c.ENTRY_ID)".
          "as COUNT from VGB_CUSTOMENTRY c, VGB_ENTRY e $filteradd where c.ENTRY_ID = e.ID and c.FIELD_ID = ".
          $_field['ID']."$_entryfilter group by c.CONTENT order by COUNT desc");

        if (vgb_numrows($_query2) == 0)
          // no guestbook-entries for this selection
          out($inNULL);
        else {
          // print the statistics for every single index
          $_sum = 0;
          $_i = 0;
          $_other = 0;
          while ($_row = vgb_result($_query2)) {
            $_count = $_row['COUNT'];
            $_sum += $_count;
            $_percent = round($_count*100/$maxEntry,2);
            $_name  = $_set[$_row['CONTENT']];
            $_i++;
            if (($_field['LIMITSTATS'] > 0) && ($_field['LIMITSTATS'] < $_i))
              $_other += $_count;
            else
              out($_newString[1],$_count,null,vgb_short($_percent),vgb_removeHTML(vgb_string($_name)));
          }
          if ($_other > 0) {
            out($_newString[1],$_other,null,
                vgb_short(round($_count*100/$maxEntry,2)),$lang['otherOption']);
          }
          // any entries with no input for this selection ?
          if (($_remnant = ($maxEntry-$_sum)) > 0) {
            $_percent = round($_remnant*100/$maxEntry,2);
            out($_newString[1],$_remnant,null,vgb_short($_percent),
            $lang['noInput']);
          }
        }
        out($_newString[2]);
      }
    }
    if ($_noField)
      // we haven't printed any statistics
      out($inFALSE);
  }
?>
Return current item: YW-GuestBook