<?php

@( (bool)FALSE === strpos( $_SERVER['REQUEST_URI'], basename( __FILE__ ) ) ) OR exit( '!! ACCESS DENIED !!' );

/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | myPHPNuke Version 188_8 RC2                                          |
// +----------------------------------------------------------------------+
// | License: GNU/GPL - http://www.gnu.org/copyleft/gpl.html              |
// +----------------------------------------------------------------------+
// | Support: http://myphpnuke.com/                                       |
// +----------------------------------------------------------------------+
// | Author: myPHPNuke Dev Team                                           |
// +----------------------------------------------------------------------+
// | Copyright: © 2001-2004 myPHPNuke Dev Team                            |
// +----------------------------------------------------------------------+
// $Id: mainfile.php,v 1.130.2.57 2004/09/15 03:12:49 kirilt Exp $

/* ===========================                                          */
/*                                                                      */
/* Copyright (c) 2001 by Francisco Burzi (fburzi@ncc.org.ve)            */
/* http://phpnuke.org                                                   */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/

//2001-09-27 trini0: Added ChatboxII to blocks.

ob_start();
define( '_E_VALUE', 0 );
error_reporting( _E_VALUE );
set_magic_quotes_runtime( 0 );

$mainfile = 1; // Relic
define( '_MAINFILE_', (bool)TRUE );
define( '_SERVER_WIN32_', ( (bool)FALSE !== stristr( PHP_OS, 'WIN' ) ) );

// WIN32 && IIS Adjustments

if ( _SERVER_WIN32_ )
{
    $tmp = array( 'APPL_PHYSICAL_PATH', 'PATH_TRANSLATED', 'DOCUMENT_ROOT' );

    foreach( $tmp AS $key )
    {
        $srch = ( isset( $_SERVER[ $key ] )
                  && (bool)FALSE !== strpos( $_SERVER[ $key ], '\\\\' ) )
              ? ( '\\\\' )
              : ( '\\' );

        if ( isset( $_SERVER[ $key ] ) ) { $_SERVER[ $key ] = str_replace( $srch, '/', $_SERVER[ $key ] ); }

        if ( isset( $GLOBALS[ $key ] ) ) { $GLOBALS[ $key ] = str_replace( $srch, '/', $GLOBALS[ $key ] ); }
    }

    if ( (bool)FALSE !== strpos( $_SERVER['SERVER_SOFTWARE'], 'IIS' ) )
    {
        $_SERVER['DOCUMENT_ROOT'] =& $_SERVER['APPL_PHYSICAL_PATH'];
        $_SERVER['QUERY_STRING'] =& getenv( 'QUERY_STRING' );
    }
}

if ( $_SERVER['SCRIPT_NAME'] != $_SERVER['PHP_SELF'] )
{
    $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
    $_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['PHP_SELF'];
}

require_once './extention.inc';

require_once './classes/core_Snoopy.class.php';

require_once './classes/phpSniff.class.php';

    $_SERVER['ua_sniff'] = new phpSniff( '' );

require_once './core_SupportFunc.php';

require './classes/core_LIB_Functions.class.php';

    $_SERVER['F_LIB'] = new FunctionLibrary();

$_SERVER['ua_sniff'] -> bot = in_array( $_SERVER['ua_sniff'] -> _browser_info['ua'], $_SERVER['F_LIB'] -> getFileContent( _DP_CLASS_PAR . 'core_BotAgents.csv', 2 ) );

require_once './phpsyndication.lib.php';
require_once './blocksconst.inc.php';

/**
 * SECURITY -> USER INPUT VERIFICATION AND SANITIZING
 *
 * Check And Sanitize All Incoming Request Variables
 */

require './config.php';

require './core_SecureMPN.php';

// Start The Load Timer

include './phptimer.php';
ss_timing_start();

// 2003-09-17 Kiril: Extract super globals into global namspace if registered globals is OFF.

$register_globals = @ini_get( 'register_globals' );

if ( empty( $register_globals ) || ! strcasecmp( $register_globals, 'off' ) || ! strcasecmp( $register_globals, 'false' ) )
{
    if ( ! empty( $_REQUEST ) ) { extract( $_REQUEST ); }
    if ( ! empty( $_SERVER )  ) { extract( $_SERVER );  }
}

$forumconfig = $GLOBALS['forumconfig'] = loadForumConfig();

// Login User If Coming From A Global Login Form

if ( isset( $_POST['global_login'] ) && $_POST['global_login'] == 1 )
{
    userLogin();
}

if ( isset( $_POST ) )
{
    require './classes/subs/sanitizer/core_BBCodeConvert.subclass.php';

    // Load The BBCode Encoder

    $allow_html = ( $forumconfig['allow_html'] == 0 || isset( $_POST['html'] ) ) ? ( (bool)FALSE ) : ( (bool)TRUE );

    $allow_bbcode = ( $forumconfig['allow_bbcode'] == 0 || isset( $_POST['bbcode'] ) ) ? ( (bool)FALSE ) : ( (bool)TRUE );

    $addsig = ( _MPN_USER && isset( $_POST['sig'] ) ) ? ( (bool)TRUE ) : ( (bool)FALSE );

    $GLOBALS['bbencoder'] = new BBCodeConvert( $allow_html, $allow_bbcode, $addsig );
}

/**
 * Delete Users Cookie If Pre 188_8
 */

if (    isset( $_COOKIE['LastVisit'] )
     && strtotime( $_COOKIE['LastVisit'] ) < '1064238014' )
{
   $LVTime = strtotime( $_COOKIE['LastVisit'] ) + 3600 * 24 * 7 * 52;

    bakeCookie( 'user' , '', '15552000', TRUE );
    bakeCookie( 'admin', '', '2592000' , TRUE );
    @setcookie( 'user', '', time() - 15552000, '', $_SERVER['HTTP_HOST'], '' );
    @setcookie( 'admin', '', time() - 2592000, '/', '', 0 );
    bakeCookie( 'LastVisit', '', $LVTime , TRUE );
}

// Stuff Online Table

on_line(); // <-- Should always run

if ( _MPN_USER ) { last_seen(); }


// ##### FUNCTIONS #####

/**
 * Compress HTML Output.
 *
 *
 */

function compressOutput( $output )
{
    $_output = gzencode( $output );

    if ( strlen( $_output ) < 1000 )
    {
        //error_log( 'Compression Off, String Length = ' . strlen( $_output ) );
        return $output;
    }

    //error_log( 'Compression On, String Length = ' . strlen( $_output ) );
    header( "Content-Encoding: gzip" );
    return $_output;

} // End Function compressOutput

/**
 * Decode Cookies
 *
 * @return mixed ( array on success, null on fail )
 */

function cookiedecode( $user = NULL )
{
    global $mpnTables;

    $cookietmp = NULL;

    if ( empty( $_COOKIE['user'] ) || is_array( $_COOKIE['user'] ) || isset( $_POST['user'] ) || isset( $_GET['user'] ) )
    {
        return NULL;
    }

    $cookietmp = base64_decode( $_COOKIE['user'] );
    $cookietmp = explode( ':' , $cookietmp );

    $sql = "SELECT COUNT(uid) FROM " . $mpnTables['users'] . " WHERE uid = '$cookietmp[0]' && pass = '$cookietmp[2]'";

    if ( empty( $cookietmp ) || @mysql_result( @mysql_query( $sql ), 0 ) == 0 )
    {
        // User Not Verified

        unset( $_COOKIE['user'], $GLOBALS['user'], $_REQUEST['user'] );

        // Attempt To Destroy User Cookie

        bakeCookie( 'user', '', '15552000', TRUE );

        return NULL;
    }
    else
    {
        return $cookietmp;
    }

} // End Function cookiedecode

/**
 * Verify Admin Status
 *
 * @return bool
 */

function is_admin( $admin = NULL, $checksuper = FALSE, $allow = NULL )
{
    global $mpnTables;

    $admintmp = NULL;

    if ( ( defined( '_ADMIN_TRUSTED' ) && (bool)TRUE === _ADMIN_TRUSTED ) || ( defined( '_MPN_ADMIN' ) && (bool)TRUE === _MPN_ADMIN ) )
    {
       return (bool)TRUE;
    }

    if ( ! empty( $_COOKIE['admin'] ) && ! is_array( $_COOKIE['admin'] ) && ! isset( $_POST['admin'] ) && ! isset( $_GET['admin'] ) )
    {
        $admintmp = base64_decode( $_COOKIE['admin'] );
        $admintmp = explode( ':' , $admintmp );

        if ( (bool)TRUE === $checksuper )
        {
            $cond = "pwd = '$admintmp[1]' && pwd != '' && radminsuper = '1'";

            if ( ! empty( $allow ) )
            {
                foreach ( $allow AS $v )
                {
                    $cond .= " || $v = '1'";
                }
            }

            $sql = "SELECT *
                    FROM " . $mpnTables['authors'] . "
                    WHERE $cond && aid = '$admintmp[0]'
                    LIMIT 1";
        }
        else
        {
            $sql = "SELECT *
                    FROM " . $mpnTables['authors'] . "
                    WHERE pwd = '$admintmp[1]' && pwd != '' && aid = '$admintmp[0]'
                    LIMIT 1";
        }

        if ( ! empty( $admintmp ) && @( $result = mysql_query( $sql ) ) && @mysql_data_seek( $result, 0 ) )
        {
            $tmp = mysql_fetch_assoc( $result );
            mysql_free_result( $result );

            $GLOBALS['ainf'] = array( 'uname' => $tmp['aid'], 'realname' => $tmp['name'], 'url' => $tmp['url'], 'email' => $tmp['email'], 'artcount' => $tmp['counter'] );

            foreach( $tmp AS $key => $v )
            {
                if ( (bool)FALSE !== strpos( $key, 'radmin' ) )
                {
                    $GLOBALS['ainf'][ substr( $key, 6 ) ] = ( $v == 1 ) ? ( TRUE ) : ( FALSE );
                }
            }

            if ( $tmp['uid'] > 0 )
            {
                $sql = 'SELECT uid, theme, theme_layout, theme_format
                        FROM ' . $mpnTables['users'] . '
                        WHERE uid = ' . $tmp['uid'] . '
                        LIMIT 1';

                if ( @( $result = mysql_query( $sql ) ) && @mysql_data_seek( $result, 0 ) )
                {
                    @$tmp2 = mysql_fetch_assoc( $result );
                    @mysql_free_result( $result );

                    foreach( $tmp2 AS $key => $v )
                    {
                        $GLOBALS['ainf'][ $key ] = $v;
                    }
                }
            }
            else
            {
                $GLOBALS['ainf']['uid'] = - 1;
                $GLOBALS['ainf']['theme_layout'] = 0;
                $GLOBALS['ainf']['theme_format'] = 0;
            }


            if ( ! defined( '_ADMIN_TRUSTED' ) )
            {
                if ( $GLOBALS['ainf']['super'] )
                {
                    define( '_ADMIN_TRUSTED', (bool)TRUE );
                }
                else
                {
                    define( '_ADMIN_TRUSTED', (bool)FALSE );
                }
            }

            if ( ! defined( '_MPN_ADMIN' ) )
            {
                define( '_MPN_ADMIN', (bool)TRUE );
            }

            return (bool)TRUE;
        }
    }

    if ( (bool)TRUE !== $checksuper )
    {
        bakeCookie( 'admin', '', '2592000', TRUE );
        @define( '_MPN_ADMIN', (bool)FALSE );
    }

    @define( '_ADMIN_TRUSTED', (bool)FALSE );

    return (bool)FALSE;

}  // End Function

/**
 * Verify User Status
 *
 * @return bool
 */

function is_user( $user = NULL )
{
    global $mpnTables;

    if ( defined( '_MPN_USER' ) && (bool)TRUE === _MPN_USER )
    {
        return (bool)TRUE;
    }

    $usertmp = getusrinfo( NULL, TRUE );

    if ( (bool)FALSE !== $usertmp )
    {
        if ( ! defined( '_MPN_USER' ) )
        {
            define( '_MPN_USER', (bool)TRUE );
        }

        return (bool)TRUE;
    }

    if ( ! defined( '_MPN_USER' ) )
    {
        define( '_MPN_USER', (bool)FALSE );
        bakeCookie( 'user', '', '15552000', TRUE );
    }

    return (bool)FALSE;

}  // End Function

/**
 * Get User Info From DB
 *
 * @return array
 */

function getusrinfo( $user = NULL, $chkonly = FALSE )
{
    global $userinfo, $mpnTables, $anonymous, $Default_Theme, $storyhome;

    $tmp = cookiedecode();
    $userinfo = NULL;

    // Default

    if ( empty( $tmp ) )
    {
        $usename = ( _MPN_ADMIN ) ? ( translate( 'Administrator' ) ) : ( $anonymous );

        if ( _MPN_ADMIN )
        {
            $useid = ( _MPN_ADMIN && $GLOBALS['ainf']['uid'] > 1 ) ? ( $GLOBALS['ainf']['uid'] ) : ( - 1 );
        }
        else
        {
            $useid = 1;
        }

        $theme = ( _MPN_ADMIN && isset( $GLOBALS['ainf']['theme'] ) ) ? ( $GLOBALS['ainf']['theme'] ) : ( $Default_Theme );
        $theme_layout = ( _MPN_ADMIN ) ? ( $GLOBALS['ainf']['theme_layout'] ) : ( 0 );
        $theme_format = ( _MPN_ADMIN ) ? ( $GLOBALS['ainf']['theme_format'] ) : ( 0 );
        $mod = ( _MPN_ADMIN ) ? ( TRUE ) : ( FALSE );
        $supermod = ( _ADMIN_TRUSTED ) ? ( TRUE ) : ( FALSE );
        $level = ( $supermod ) ? ( 3 ) : ( 0 );
        $rankdisp = ( _MPN_ADMIN ) ? ( translate( 'Moderator' ) ) : ( '' );

        $GLOBALS['uinf'] = array( 0 => $useid, 'uid' => $useid, 1 => $usename, 'uname' => $usename, '2' => NULL, 'pass' => NULL, 3 => $storyhome, 'thread', 0, 0, 1, 0, $Default_Theme, 4096, 'mod' => $mod, 'supermod' => $supermod, 'lastvisit' => _MPN_TIMESTAMP - ( 60 * 30 ), 'attachsig' => FALSE, 'level' => $level, 'posts' => 0, 'rank' => 0, 'rank_display' => $rankdisp, 'user_sig' => NULL, 'email' => NULL, 'user_from' => NULL, 'user_icq' => NULL, 'url' => NULL, 'online' => FALSE, 'theme' => $theme, 'theme_layout' => $theme_layout, 'theme_format' => $theme_format );

        if ( _MPN_ADMIN ) { updateLastVisitCookie(); }

        if ( $chkonly ) { return (bool)FALSE; }
    }
    else
    {
        if ( $tmp[2] == '' ) { goBack( translate( 'Invalid Password' ) ); }

        $sql = 'SELECT t1.uid, t1.uname, t1.pass, t1.storynum, t1.umode, t1.uorder, t1.thold, t1.noscore, t1.ublockon, t1.theme, t1.commentmax, t1.name, t1.email, t1.femail, t1.url, t1.user_avatar, t1.user_icq, t1.user_occ, t1.user_from, t1.user_from_flag, t1.user_intrest, t1.user_sig, t1.user_viewemail, t1.user_theme, t1.theme_layout, t1.theme_format, t1.user_aim, t1.user_yim, t1.user_msnm, t1.user_regdate, t1.bio, t1.ublock, t2.posts, t2.attachsig, t2.rank, t2.level, t3.username AS online
                FROM  ' . $mpnTables['users'] . ' AS t1
                    , ' . $mpnTables['users_status'] . ' AS t2
                LEFT JOIN ' . $mpnTables['session'] . ' AS t3
                    ON t1.uname = t3.username
                WHERE t1.uid = "' . $tmp[0] . '"
                    && t1.pass = "' . $tmp[2] . '"
                    && t1.pass != ""
                    && t1.uid > 1
                    && t1.uid = t2.uid
                LIMIT 0, 1';

        $result = @mysql_query( $sql );

        if ( ! @mysql_data_seek( $result, 0 ) )
        {
            if ( $chkonly ) { return (bool)FALSE; }
            goBack( translate( 'Unable To Verify Your Identity' ) );
            exit;
        }

        if ( ! ( $userinfo = mysql_fetch_array( $result ) ) )
        {
            if ( $chkonly ) { return (bool)FALSE; }
            goBack( translate( 'Unable To Retrieve Data' ) );
            exit;
        }
    }

   if ( ! empty( $userinfo ) )
   {
        $GLOBALS['uinf'] = $userinfo;

        Sanitizer :: slashIT( $GLOBALS['uinf'] );

        $GLOBALS['uinf']['supermod'] = ( $GLOBALS['uinf']['level'] == 3 || $GLOBALS['uinf']['level'] == 5 || _MPN_ADMIN )
                                    ? ( (bool)TRUE )
                                     : ( (bool)FALSE );

        $GLOBALS['uinf']['mod'] = ( $GLOBALS['uinf']['supermod'] )
                                ? ( (bool)TRUE )
                               : ( (bool)FALSE );

        $GLOBALS['uinf']['pass'] = $GLOBALS['uinf'][2] = NULL;

        if ( $GLOBALS['uinf']['user_sig'] != '' )
        {
            Sanitizer :: adjustFormat( $GLOBALS['uinf']['user_sig'], 3, 10 );
        }

        updateLastVisitCookie();
    }

    $userinfo = $GLOBALS['uinf'];

    if ( $chkonly ) { return (bool)TRUE; }

    return $userinfo;
}

/**
 * Get User Cookie Information And Make The Cookie
 *
 * @return void
 */

function makeUserCookie( $uid, $upass )
{
    global $mpnTables;

    if ( $upass == '' ) { goBack( translate( 'Invalid Password' ) ); }

    $sql = "SELECT uid, uname, pass, storynum, umode, uorder, thold, noscore, ublockon, theme, commentmax
            FROM " . $mpnTables['users'] . "
            WHERE uid = '$uid'
                && uid > 1
                && pass = '$upass'
                && pass != ''";

    $result = mysql_query( $sql );

    if ( mysql_num_rows( $result ) === 1 )
    {
        $userinfo = mysql_fetch_array($result);

        Sanitizer :: slashIT( $userinfo );

        $info = $userinfo['uid'] . ':' . $userinfo['uname'] . ':' . $userinfo['pass'] . ':' . $userinfo['storynum'] . ':' . $userinfo['umode'] . ':' . $userinfo['uorder'] . ':' . $userinfo['thold'] . ':' . $userinfo['noscore'] . ':' . $userinfo['ublockon'] . ':' . $userinfo['theme'] . ':' . $userinfo['commentmax'];

        bakeCookie( 'user', base64_encode( $info ) );
    }
    else
    {
        goBack( translate( 'Unable To Verify Your Identity' ) );
        exit;
    }

    return;

} // End Function makeUserCookie

/**
 * Process A User Login Request
 *
 * @return void
 */

function userlogin( $uname = NULL, $pass = NULL, $redirect = NULL )
{
    global $mpn_anonymous_id, $mpnTables;

    if ( ! isset( $_POST['uname'] ) || ! isset( $_POST['pass'] ) ) { goBack( translate( 'Invalid Login Operation' ) ); }

    $uname = ( empty( $uname ) ) ? ( $_POST['uname'] ) : ( $uname );
    $pass = ( empty( $pass ) ) ? ( $_POST['pass'] ) : ( $pass );

    if ( $pass == '' || $uname == '' ) { goBack( translate( 'Invalid Password Or Username' ) ); }

    $sql = 'SELECT t1.uid, t1.pass
            FROM ' . $mpnTables['users'] . ' AS t1
                , ' . $mpnTables['users_status'] . ' AS t2
            WHERE t1.uid > 1
                && t1.uid = t2.uid
                && t1.uname = "' . $uname . '"
                && t1.pass != ""
                && t1.pass = "' . MD5( $pass ) . '"';

    $result = @mysql_query( $sql );

    if ( ! @mysql_data_seek( $result, 0 ) )
    {
        goBack( translate( 'Unable To Process User Login' ) );
        exit;
    }

    $tmp = mysql_fetch_row( $result );
    makeUserCookie( $tmp[0], $tmp[1] );
    unset( $tmp );

    if ( (bool)FALSE !== $redirect )
    {
        if ( is_null( $redirect ) ) { $redirect = $_SERVER['REQUEST_URI']; }

        $_SERVER['F_LIB'] -> redirectRequest( $redirect, TRUE );
    }

    return;

} // End Function userLogin

/**
 * Set / Delete User Cookie
 *
 * return void
 */

function bakeCookie( $who, $info = '', $time = '15552000', $eat = FALSE )
{
    $err = (bool)FALSE;

    if ( ! $eat )
    {
       @setcookie( $who, '', time() - $time, '/', _MPN_COOKIE_HOST, 0 );
        sleep(1);

        if ( ! @setcookie( $who, $info, time() + $time, '/', _MPN_COOKIE_HOST, 0 ) )
        {
            $err = (bool)TRUE;
            $msg = translate( 'Failed To Create Cookie' );
        }
    }
    else
    {
        unset( $_COOKIE[ $who ] );

        if ( ! @setcookie( $who, '', time() - $time, '/', _MPN_COOKIE_HOST, 0 ) )
        {
            $err = (bool)TRUE;
            $msg = translate( 'Failed To Delete Cookie' );
        }
    }

    if ( (bool)TRUE === $err )
    {
        if ( ! $eat ) { goBack( $msg ); }

        return $msg;
    }

    return;

} // End Function bakeCookie

/**
 * Update Last Visit Cookie.
 *
 * Additionally Add Last Visit Time To User Array and/or DB
 *
 * @return void
 */

function updateLastVisitCookie()
{
    global $userdata, $mpnTables, $serv_offset;

    $time = ( time() + 3600 * 24 * 7 * 52 ); // one year 'til expiry
    $value = strftime( '%Y-%m-%d %H:%M:%S', _MPN_TIMESTAMP );
    $update_interval = 60 * 30;  // 30 minutes
    $update = (bool)FALSE;

    //$sql = 'UPDATE ' . $mpnTables['users_status'] .' SET lastvisit = ' . _MPN_TIMESTAMP . ' WHERE uid = "' . $GLOBALS['uinf']['uid'] . '"';

    // If Cookie Is Already Set, Determine Update Check

    if ( isset( $_COOKIE['LastVisit'] ) )
    {
        $unixtime = ( ! is_integer( $_COOKIE['LastVisit'] ) )
                  ? ( strtotime( $_COOKIE['LastVisit'] ) )
                  : ( $_COOKIE['LastVisit'] );

        $GLOBALS['uinf']['lastvisit'] = $unixtime;
        $update = ( _MPN_TIMESTAMP > ( $unixtime + $update_interval ) );
    }

    if ( $update || ! isset( $_COOKIE['LastVisit'] ) || ! isset( $GLOBALS['uinf']['lastvisit'] ) || $GLOBALS['uinf']['lastvisit'] == 0  )
    {
        //if ( _MPN_USER ) { @mysql_query( $sql ); }
        $userdata['lastvisit'] = $GLOBALS['uinf']['lastvisit'] = $value;
        bakeCookie( 'LastVisit', $value, $time );
    }

    return;

} // End Function

/**
 * Update Backend/RSS Feed
 *
 *
 */

function ultramode()
{
    global $mpnTables;

    $fname = 'ultramode.txt';

    $sql = 'SELECT sid, aid, title, time, comments, topic FROM ' . $mpnTables['stories'] . ' ORDER BY time DESC LIMIT 0,10';

    $res = mysql_query( $sql );

    $content[] = 'General purpose self-explanatory file with news headlines' . "\n";

    while( list( $sid, $aid, $title, $time, $comments, $topic ) = mysql_fetch_row( $res ) )
    {
        $sql = 'SELECT topictext, topicimage from ' . $mpnTables['topics'] . ' WHERE topicid = ' . $topic;

       $res1 = mysql_query( $sql );

        list( $topictext, $topicimage ) = mysql_fetch_row( $res1 );

        $content[] =   "%%\n"
                     . $title
                     . "\n"
                     . _MPN_ROOT_URI
                     . 'article.php?sid='
                     . $sid
                     . "\n"
                     . $time
                     . "\n"
                     . $aid
                     . "\n"
                     . $topictext
                     . "\n"
                     . $comments
                     . "\n"
                     . $topicimage
                     . "\n";
    }

    if (is_file($fname) && ! $_SERVER['F_LIB'] -> writeFile( $fname, 'w+b', $content ) )
    {
        goBack( translate( 'File Write Error.  Check Permissions On ' ) . $fname );
        exit;
    }

    mysql_free_result( $res );
    mysql_free_result( $res1 );

    return;
}

function searchblock()
{
        global $phpEx;

        OpenTable();

        echo "<form action=\"searchbb.$phpEx\" method=\"post\">";
        echo '<input type="hidden" name="bbsearch" value="1">' . "\n";
        echo "<input type=\"hidden\" name=\"addterm\" value=\"any\">";
        echo "<input type=\"hidden\" name=\"sortby\" value=\"p.post_time\">";
        echo "&nbsp;&nbsp;<b>" . translate("Search") . "</b>&nbsp;<input class=\"textbox\" type=\"text\" name=\"term\" size=\"15\">";
        echo "<input type=\"hidden\" name=\"submit\" value=\"submit\"></form>";
        echo "<div align=\"left\"><font size=\"2\">&nbsp;&nbsp;[ <a href=\"searchbb.$phpEx?addterm=any&amp;adv=1\">" .translate("Advanced Search")."</a> ]</font></div>";
        CloseTable();
}


function getDisplayTime( $time, $strfmt = 'datestring4', $adj = TRUE )
{
    if ( ! isset( $time ) ) { return NULL; }

    $time = ( ! is_integer( $time ) && strtotime( $time ) != -1 )
              ? ( strtotime( $time ) )
              : ( (int)$time );

    if ( $adj )
    {
        global $serv_offset;
        $time = $time + ( 3600 * $serv_offset );
    }

    return strftime( translate( $strfmt ), $time );
}

/*********************************************************/
/* formatting stories                                    */
/*********************************************************/


function formatTimestamp($time) {
    global $mpn_use_timezone_formattimestamp;
/*
        global $datetime, $locale;
        setlocale (LC_TIME, "$locale");
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("datestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        return($datetime);
*/

        global $datetime, $locale, $language, $serv_offset;
        if ($language != 'english') {
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $hari = date("l", mktime($datetime[4]+$serv_offset,$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $bulan = date("F", mktime($datetime[4]+$serv_offset,$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $daerah = strftime("%Z", mktime($datetime[4]+$serv_offset,$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $hari = "" . translate($hari) . "";
        $bulan  = "" . translate($bulan) . "";
    $time_hour = $datetime[4] + $serv_offset;
        if ($mpn_use_timezone_formattimestamp == 1) {
          $datetime = "$hari, $datetime[3] $bulan $datetime[1] @ $time_hour:$datetime[5]:$datetime[6] $daerah";
        } else {
          $datetime = "$hari, $datetime[3] $bulan $datetime[1] @ $time_hour:$datetime[5]:$datetime[6]";
        }
        return($datetime);
        } else {
        setlocale (LC_TIME, "$locale");
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("datestring")."", mktime($datetime[4]+$serv_offset,$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        return($datetime);
        }

}

function oldNewsNew($storynum,$boxstuff) {
    global $locale, $oldnum, $storyhome, $cookie, $categories, $cat, $mpnTables,$phpEx;
    $storynum = $storyhome;
    $options = '';
    if ($categories == 1) {
        $sel = "where catid='$cat'";
    } else {
        $sel = "";
    }
    $result = mysql_query("select sid, title, time, comments from ".$mpnTables['stories']." $sel order by time desc limit $storynum, $oldnum");
    $vari = 0;
    if (isset($cookie[4])) {
        $options .= "&amp;mode=$cookie[4]";
    } else {
        $options .= "&amp;mode=thread";
    }
    if (isset($cookie[5])) {
        $options .= "&amp;order=$cookie[5]";
    } else {
        $options .= "&amp;order=0";
    }
    if (isset($cookie[6])) {
        $options .= "&amp;thold=$cookie[6]";
    } else {
        $options .= "&amp;thold=0";
    }
    while(list($sid, $title, $time, $comments) = mysql_fetch_row($result))
    {
        setlocale (LC_TIME, "$locale");
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime2);
        $datetime2 = strftime("".translate("datestring2")."", mktime($datetime2[4],$datetime2[5],$datetime2[6],$datetime2[2],$datetime2[3],$datetime2[1]));
        $datetime2 = ucfirst($datetime2);
        if(isset($time2) && $time2 == $datetime2) {
            $boxstuff .= "<ul><li><a href=\"article.$phpEx?sid=$sid$options\">$title</a></li></ul>\n";
        } else {
            if(!isset($a) || $a == "") {
                $boxstuff .= "<b>$datetime2</b><br /><br /><ul><li><a href=\"article.$phpEx?sid=$sid$options\">$title</a></li></ul>\n";
                $time2 = $datetime2;
                $a = 1;
            } else {
                $boxstuff .= "<br /><b class='t-left'>$datetime2</b><br /><br /><ul><li><a href=\"article.$phpEx?sid=$sid$options\">$title</a></li></ul>\n";
                $time2 = $datetime2;
            }
        }
        $vari++;
        if ($vari==$oldnum)
        {
            if (isset($cookie[3])) {
                $storynum = $cookie[3];
            } else {
                $storynum = $storyhome;
            }
            $min = $oldnum + $storynum;

            $boxstuff .= "<br /><p class=t-right><a href=\"search.$phpEx?min=$min&amp;type=stories&amp;category=$cat\"><b>".translate("Older Articles")."</b></a></p>\n";
        }
    }

    return($boxstuff);
}

/*********************************************************/
/* poll functions                                        */
/*********************************************************/

// Kiril: Moved to pollFunctions.php

function getTopics($s_sid)
{
    global $topicname, $topicimage, $topictext, $mpnTables;

    $sid = $s_sid;
    $result=mysql_query("SELECT topic FROM ".$mpnTables['stories']." where sid=$sid");
    list($topic) = mysql_fetch_row($result);
    $result=mysql_query("SELECT topicid, topicname, topicimage, topictext FROM ".$mpnTables['topics']." where topicid=$topic");
    list($topicid, $topicname, $topicimage, $topictext) = mysql_fetch_row($result);
}

function applet_oldnews($storynum,$boxstuff)
{
    global $bgcolor1, $bgcolor4, $textcolor1, $textcolor2, $textcolor3, $textcolor4, $site_font, $phpEx;

    include_once './newsapplet.php';

    $bgcolor = ( !empty( $bgcolor4 ) ) ? ( $bgcolor4 ) : ( $bgcolor1 );

    $textcolor = ( !empty( $textcolor3 ) ) ? ( $textcolor3 ) : ( $textcolor1 );
    $textcolor4 = ( !empty( $textcolor4 ) ) ? ( $textcolor4 ) : ( $textcolor2 );

    if ( oldAppletNews( $storynum ) )
    {
        $boxstuff .= "<APPLET CODE='yavs.class' CODEBASE=\"". _MPN_ROOT_URI ."\" WIDTH='130' HEIGHT='400'>\n";
        $boxstuff .= "<PARAM NAME='MSGTEXT'       VALUE='" . _MPN_ROOT_URI . "cache/oldnewsapplet.txt'>\n";
        $boxstuff .= "<PARAM NAME='FGCOLOR'       VALUE='$textcolor'>\n";
        $boxstuff .= "<PARAM NAME='BGCOLOR'       VALUE='$bgcolor'>\n";
        $boxstuff .= "<PARAM NAME='HREFCOLOR'     VALUE='$textcolor4'>\n";
        $boxstuff .= "<PARAM NAME='LINKCOLOR'     VALUE='#ff0000'>\n";
        $boxstuff .= "<PARAM NAME='SPEED'         VALUE='50'>\n";
        $boxstuff .= "<PARAM NAME='PAUSE'         VALUE='5000'>\n";
        $boxstuff .= "<PARAM NAME='MOUSEOVERHOLD' VALUE='YES'>\n";
        $boxstuff .= "<PARAM NAME='WAITTEXT'      VALUE='YES'>\n";
        $boxstuff .= "<PARAM NAME='WAITTEXT1'     VALUE='" .translate("Streaming news content.. ")."'>\n";
        $boxstuff .= "<PARAM NAME='WAITTEXT2'     VALUE=''>\n";
        //$boxstuff .= "<PARAM NAME='FONTNAME'      VALUE='$site_font'>\n";
        //$boxstuff .= "<PARAM NAME='FONTSIZE'      VALUE='10'>\n";
        $boxstuff .= "<PARAM NAME='HPAD'          VALUE='3'>\n";
        $boxstuff .= "<PARAM NAME='VPAD'          VALUE='5'>\n";
        $boxstuff .= "</APPLET>\n";

        $boxstuff .= "<p align=right><a href=\"archive.php\"><b>".translate("Older Articles")."</b></a></font>\n";

        return $boxstuff;
    }
    else
    {
        return NULL;
    }
}


function applet_headlines($boxstuff)
{
    global $bgcolor1, $bgcolor4, $textcolor1, $textcolor3, $textcolor2, $textcolor4, $site_font, $mpnTables;

    include_once './newsapplet.php';

    $bgcolor = ( ! empty( $bgcolor4 ) ) ? ( $bgcolor4 ) : ( $bgcolor1 );

    $textcolor = ( ! empty( $textcolor3 ) ) ? ( $textcolor3 ) : ( $textcolor1 );
    $textcolor4 = ( ! empty( $textcolor4 ) ) ? ( $textcolor4 ) : ( $textcolor2 );

    $cache_file = "newsapplet.txt";

    $result = mysql_query("select COUNT(hid) FROM ".$mpnTables['headlines']." where status='1'");
    $sum = mysql_result($result, 0);

    if ( $sum > 0 && get_applet_headlines( $cache_file ) )
    {
        $boxstuff .= "<APPLET CODE=\"yavs.class\" CODEBASE=\"". _MPN_ROOT_URI ."\" WIDTH=\"130\" HEIGHT=\"200\">";
        $boxstuff .= "<PARAM NAME=\"MSGTEXT\"       VALUE=\"" . _MPN_ROOT_URI . "cache/newsapplet.txt\">";
        $boxstuff .= "<PARAM NAME=\"FGCOLOR\"       VALUE=\"$textcolor\">";
        $boxstuff .= "<PARAM NAME=\"BGCOLOR\"       VALUE=\"$bgcolor\">";
        $boxstuff .= "<PARAM NAME=\"HREFCOLOR\"     VALUE=\"$textcolor4\">";
        $boxstuff .= "<PARAM NAME=\"LINKCOLOR\"     VALUE=\"#ff0000\">";
        $boxstuff .= "<PARAM NAME=\"SPEED\"         VALUE=\"50\">";
        $boxstuff .= "<PARAM NAME=\"PAUSE\"         VALUE=\"5000\">";
        $boxstuff .= "<PARAM NAME=\"MOUSEOVERHOLD\" VALUE=\"YES\">";
        $boxstuff .= "<PARAM NAME=\"WAITTEXT\"      VALUE=\"YES\">";
        $boxstuff .= "<PARAM NAME=\"WAITTEXT1\"     VALUE=\"" .translate("Streaming news content.. ")."\">";
        $boxstuff .= "<PARAM NAME=\"WAITTEXT2\"     VALUE=\"" .translate("Please Wait")."\">";
       //$boxstuff .= "<PARAM NAME=\"FONTNAME\"      VALUE=\"$site_font\">";
        //$boxstuff .= "<PARAM NAME=\"FONTSIZE\"      VALUE=\"10\">";
        $boxstuff .= "<PARAM NAME=\"HPAD\"          VALUE=\"3\">";
        $boxstuff .= "<PARAM NAME=\"VPAD\"          VALUE=\"5\">";
        $boxstuff .= "</APPLET> ";
    }
    else
    {
       return null;
    }

    return $boxstuff;

}

function myphpnuke_headlines($content,$title,$position) {
    global $mpnTables;

    $separ        =        "<li>";
    $cache_time        =        3600;
    $max_items        =        15;
    $max_length = 100;
    $target        =        "new";
    $items        =        0;
    $boxstuff = '';

    $result = mysql_query("select hid, sitename, url, headlinesurl from ".$mpnTables['headlines']." where status=1");

    $count = mysql_num_rows( $result );

    while ( list( $hid, $sitename, $url, $headlinesurl ) = mysql_fetch_row( $result ) )
    {
        $cache_file = 'newsheadline-' . $hid . '.cache';

        $synd = new RSStoHTML($headlinesurl,$cache_file,$cache_time,$max_items, $max_length);

        if ( $count > 1 )
        {
            $boxtitle = "" . translate( "HeadLines" ) . "";
        }
        else
        {
            $boxtitle = $sitename . "&nbsp;" . translate( "Headlines" ) . "";
        }

        if ( !is_null ( $synd ) )
        {
            $boxstuff .= "<div class='headlineblk'>\n";

                if ( $count > 1 ) { $boxstuff .= "<br /><center><b>$sitename</b></center><br />"; }

                $boxstuff .= $synd->getHtml();
                $boxstuff .= "<br /><br />";

            $boxstuff .= "</div>\n";
        }
    }

    $boxstuff = build_content($position,$content,$boxstuff);

    if ( $boxstuff != '' ) { themesidebox($boxtitle, $boxstuff); }
}


function on_line()
{
    global $mpnTables;

    $cookie = cookiedecode();
    $ip = $_SERVER['REMOTE_ADDR'];
    $username = $cookie[1];
    if (!isset($username)) {
        $username = "$ip";
        $guest = 1;
    }
    else
    {
        $guest = 0;
    }

    $past = time()-900;
    mysql_query("DELETE FROM ".$mpnTables['session']." WHERE time < $past");
    $result = mysql_query("SELECT time FROM ".$mpnTables['session']." WHERE username='$username'");
    $ctime = time();

    if ($row = mysql_fetch_array($result))
    {
        mysql_query("UPDATE ".$mpnTables['session']." SET username='$username', time='$ctime', host_addr='$ip', guest='$guest' WHERE username='$username'");
    }
    else
    {
        mysql_query("INSERT INTO ".$mpnTables['session']." (username, time, host_addr, guest, forum_pass) VALUES ('$username', '$ctime', '$ip', '$guest','')");
    }
}

function myphpnuke_online($content)
{
        global $mpnTables;
        global $sitename,$phpEx;
        global $bgcolor1, $bgcolor2, $guest_online_num;
        global $mpn_whosonline_white_table_bg, $use_custom_whosonline;
        global $mpn_whosonline_author_access_level, $mpn_whosonline_author_show_level;

        if (!isset($mpn_whosonline_white_table_bg)) { $mpn_whosonline_white_table_bg = 0; }
        if (!isset($mpn_whosonline_author_access_level)) { $mpn_whosonline_author_access_level = 3; }
        if (!isset($mpn_whosonline_author_show_level)) { $mpn_whosonline_author_show_level = 1; }

        $username = $GLOBALS['uinf']['uname'];
        if ( _MPN_USER || _MPN_ADMIN ) { $use_custom_whosonline = 1; }

        $result = mysql_query("SELECT COUNT(username) FROM ".$mpnTables['session']." where guest=1");
        $guest_online_num = mysql_result($result, 0);
        $result = mysql_query("SELECT COUNT(username) FROM ".$mpnTables['session']." where guest=0");
        $member_online_num = mysql_result($result, 0);

        // Code for Messages
        $total_messages = mysql_result(mysql_query("SELECT COUNT(msg_id) FROM ".$mpnTables['priv_msgs']." WHERE to_userid = '" . $GLOBALS['uinf']['uid'] . "'"), 0);
        $new_messages = mysql_result(mysql_query("SELECT COUNT(msg_id) FROM ".$mpnTables['priv_msgs']." WHERE to_userid = '" . $GLOBALS['uinf']['uid'] . "' AND read_msg='0'"), 0);
        // Code for Messages

        $who_online_num = $guest_online_num + $member_online_num;
        $who_online = "<center>".translate("There are currently,")." $guest_online_num ".translate("guest(s) and")." $member_online_num ".translate("member(s) that are online.")."</center><br /><br />";

        $content .= "$who_online";

        if ($use_custom_whosonline == 0)
        {
            if ($member_online_num > 2) {
                    $result = mysql_query("SELECT username FROM ".$mpnTables['session']." WHERE guest='0' LIMIT 2");
                    while(list($memusername) = mysql_fetch_row($result)) {
                            $content .="<a href=\"user.$phpEx?op=userinfo&amp;uname=$memusername\">$memusername</a>, ";
                    }
                    $content .="<a href=\"memberslist.php\" target=\"_blank\">more...</a><br />";
            } elseif ($member_online_num != 0) {
                    $first = 0;
                    $result = mysql_query("SELECT username FROM ".$mpnTables['session']." WHERE guest='0'");
                    while(list($memusername) = mysql_fetch_row($result)) {
                            if ($first!=0) { $content .=", "; }

                            $content .="<a href=\"user.$phpEx?op=userinfo&amp;uname=$memusername\">$memusername</a>";
                             $first= 1;
                    }
                    $content .="<br />";
            }

            $content .= "<br />";
        }

        if ( _MPN_USER ) {
                $content .= "".translate("You are logged as")." <b>$username</b>.";
                $content .= "<br /><br />";
        } else {
                $content .= "".translate("You are Anonymous user. You can register for free by clicking <a href='user.php?op=register'>here</a>.")."";
                $content .= "<br /><br />";
        }


        if ($use_custom_whosonline == 1) {

                $result = mysql_query("SELECT COUNT(uid) FROM ".$mpnTables['users']." where (uid > 1) order by uid");
                $numrows = mysql_result($result, 0);

                if ( _MPN_USER || _MPN_ADMIN )
                {
                    $result2 = mysql_query("SELECT username, guest FROM ".$mpnTables['session']." where guest=0");
                    $member_online_num = mysql_num_rows($result2);
                    $who_online = "<center><FONT SIZE=\"1\"><b>".translate("Current Online Registered Users:")."</b><br /><br />";
                    $i = 1;

                    while ($session = mysql_fetch_array($result2))
                    {
                        if ($session['guest'] == 0)
                        {
                            $who_online .= "<a href=\"user.$phpEx?op=userinfo&amp;uname=" . $session['username'] . "\">" . $session['username'] . "</a>";

                            if ($i != $member_online_num) {
                                    $who_online .= ($i != $member_online_num ? " - " : "");
                                if ($i == 5)
                                {
                                        $who_online .= "<a href=\"memberslist.$phpEx\">more...</a>";
                                        break;
                                }
                            }
                            $i++;
                        }
                    }

                    $who_online .= "</font></center>";

                    if ($mpn_whosonline_white_table_bg == 1) {
                            $content .= "<table class='onlinetbl1' width='90%' border='0' cellpadding='0' cellspacing='1' bgcolor='000000'><tr><td>\n";
                            $content .= "<table class='onlinetbl2' width=\"100%\" border='0' cellpadding='5' cellspacing='1' bgcolor='FFFFFF'><tr><td>\n";
                            $content .= $who_online;
                            //$content .= "</td></tr></table></td></tr></table><br />\n";
                    } else {
                            $content .= "<table width=\"90%\" border='0' cellspacing='1' cellpadding='0' bgcolor=\"$bgcolor2\"><tr><td>\n";
                            $content .= "<table width=\"100%\" border='0' cellspacing='1' cellpadding='8' bgcolor=\"$bgcolor1\"><tr><td>\n";
                            $content .= $who_online;
                    }

                    $content .= "</td></tr></table></td></tr></table><br />\n";
                }
        }

        if ( _MPN_USER ) {
        // Code for Messages
         if ($total_messages > 0) {
                        // $content .= "<br /><br />";
                        if ($new_messages > 0) $content.= "<a href='viewpmsg.$phpEx'>$new_messages ".translate("New Messages")."</a><br /> ";
                        else $content .= "".translate("No New Messages")." <br /> ";
                        $content .= "<a href='viewpmsg.$phpEx'>$total_messages ".translate("Total Messages.")."</a></font>";
                } else {
                        // $content .= "<br /><br />"'
                        $content .= "<a href='viewpmsg.$phpEx'>".translate("You don't have any Messages.")."</a></font>";
                }

        // Code for Messages
        }

        if ( _BLKS_SHOW_AUTHORS_ )
        {
            $result = mysql_query("SELECT u.uname, u.email, u.user_icq, a.access_title, s.level FROM ".$mpnTables['users']." u, ".$mpnTables['access']." a, ".$mpnTables['users_status']." s WHERE s.uid > 1 && s.level >= $mpn_whosonline_author_access_level AND s.uid=u.uid AND a.access_id = s.level ORDER by a.access_id DESC");

            if ( mysql_num_rows($result) > 0 )
            {
                $prev_caption = "";

                $content .= "<br /><br />";

                if ($mpn_whosonline_white_table_bg == 1) {
                        $content .= "<table width='90%' border='0' cellpadding='0' cellspacing='1' bgcolor='000000'><tr><td>\n";
                        $content .= "<table width=\"100%\" border='0' cellpadding='5' cellspacing='1' bgcolor='FFFFFF'><tr><td>\n";
                } else {
                        $content .= "<table width=\"90%\" border='0' cellspacing='1' cellpadding='0' bgcolor=\"$bgcolor2\"><tr><td>\n";
                        $content .= "<table width=\"100%\" border='0' cellspacing='1' cellpadding='8' bgcolor=\"$bgcolor1\"><tr><td>\n";
                }

                while  ($userinfo = mysql_fetch_array($result))
                {
                    if (($prev_caption != $userinfo['access_title']) && ($mpn_whosonline_author_show_level == 1)) {
                            $prev_caption = $userinfo['access_title'];
                            $content .= "<tr><td colspan=\"2\">";
                            $content .= "<font size=\"1\">";
                            $content .= "<b>$prev_caption</b>";
                            $content .= "</font>";
                            $content .= "</td></tr>";
                    }

                    $content .= "<tr><td width='80%'>";
                    $content .= "<font size=\"1\">";
                    if ($userinfo['email'] != "") {
                            $content .= '<a href=mailto:' . $userinfo['email'] . '>' . $userinfo['uname'] . '</a>';
                    } else {
                            $content .= $userinfo['uname'];
                    }
                    $content .= "</font>";
                    //$content .= "</td><td width=20% align=right>";

                    if ( $userinfo['user_icq'] != '' )
                    {
                        $content .= '&nbsp;&nbsp;<a href="http://wwp.icq.com/' . $userinfo['user_icq'] . '#pager" target="_blank">';

                        if ( _USR_ICQ_STATUS_ )
                        {
                            $content .= '<img src="http://online.mirabilis.com/scripts/online.dll?icq=' . $userinfo['user_icq'] . '&amp;img=5" alt="' . translate( 'Send ICQ Meesage To' ) . ' ' . $userinfo['uname'] . '" ' . _T_NN4_BORDER . ' />';
                        }
                        else
                        {
                            $content .= '<img src="' . _MPN_ROOT_URI . 'images/forum/icons/icq_on.gif" alt="' . translate( 'Send ICQ Meesage To' ) . ' ' . $userinfo['uname'] . '" ' . _T_NN4_BORDER . ' />';
                        }

                        $content .= '</a>' . "\n";
                    }
                    else
                    {
                        $content .= "&nbsp;";
                    }

                    $content .= "</td></tr>";

                }

                $content .= "</table></td></tr></table>";
            }
        }
    $content .= "<br />";
    return($content);
}

function automatednews() {
    global $mpnTables;
    $today = getdate();
    $day = $today['mday'];
    if ($day < 10) {
        $day = "0$day";
    }
    $month = $today['mon'];
    if ($month < 10) {
        $month = "0$month";
    }
    $year = $today['year'];
    $hour = $today['hours'];
    $min = $today['minutes'];
    $sec = "00";
    $result = mysql_query("select anid, time from ".$mpnTables['autonews']);
    while(list($anid, $time) = mysql_fetch_row($result)) {
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $date);
        if (($date[1] <= $year) AND ($date[2] <= $month) AND ($date[3] <= $day)) {
            if (($date[4] < $hour) AND ($date[5] >= $min) OR ($date[4] <= $hour) AND ($date[5] <= $min)) {
                $result2 = mysql_query("select catid, aid, title, hometext, bodytext, topic, informant, notes, ihome from ".$mpnTables['autonews']." where anid='$anid'");
                while(list($catid, $aid, $title, $hometext, $bodytext, $topic, $author, $notes, $ihome) = mysql_fetch_row($result2))
                {
                    $title = addslashes($title);
                    $hometext = addslashes($hometext);
                    $bodytext = addslashes($bodytext);
                    $notes = addslashes($notes);

                    mysql_query("insert into ".$mpnTables['stories']." values (NULL, '$catid', '$aid', '$title', now(), '$hometext', '$bodytext', '0', '0', '$topic', '$author', '$notes', '$ihome')");
                    mysql_query("delete from ".$mpnTables['autonews']." where anid='$anid'");
                }
            }
        }
    }
}

function forumerror($e_code) {
    global $sitename, $header, $footer,$phpEx;
    if ($e_code == "0001") {
        $error_msg = translate( "Could not connect to the forums database." );
    }
    if ($e_code == "0002") {
        $error_msg = translate( "The forum you selected does not exist. Please go back and try again." );
    }
    if ($e_code == "0003") {
        $error_msg = translate( "Password Incorrect." );
    }
    if ($e_code == "0004") {
        $error_msg = translate( "Could not query the topics database." );
    }
    if ($e_code == "0005") {
        $error_msg = translate( "Error getting messages from the database." );
    }
    if ($e_code == "0006") {
        $error_msg = translate( "Please enter the Nickname and the Password." );
    }
    if ($e_code == "0007") {
        $error_msg = translate( "You are not the Moderator of this forum therefore you can't perform this function." );
    }
    if ($e_code == "0008") {
        $error_msg = translate( "You did not enter the correct password, please go back and try again." );
    }
    if ($e_code == "0009") {
        $error_msg = translate( "Could not remove posts from the database." );
    }
    if ($e_code == "0010") {
        $error_msg = translate( "Could not move selected topic to selected forum. Please go back and try again." );
    }
    if ($e_code == "0011") {
        $error_msg = translate( "Could not lock the selected topic. Please go back and try again." );
    }
    if ($e_code == "0012") {
        $error_msg = translate( "Could not unlock the selected topic. Please go back and try again." );
    }
    if ($e_code == "0013") {
        $error_msg = translate( "Could not query the database. <br />Error: mysql_error()" );
    }
    if ($e_code == "0014") {
        $error_msg = translate( "No such user or post in the database." );
    }
    if ($e_code == "0015") {
        $error_msg = translate( "Search Engine was unable to query the forums database." );
    }
    if ($e_code == "0016") {
        $error_msg = translate( "That user does not exist. Please go back and search again." );
    }
    if ($e_code == "0017") {
        $error_msg = translate( "You must type a subject to post. You can't post an empty subject. Go back and enter the subject" );
    }
    if ($e_code == "0018") {
        $error_msg = translate( "You must choose message icon to post. Go back and choose message icon." );
    }
    if ($e_code == "0019") {
        $error_msg = translate( "You must type a message to post. You can't post an empty message. Go back and enter a message." );
    }
    if ($e_code == "0020") {
        $error_msg = translate( "Could not enter data into the database. Please go back and try again." );
    }
    if ($e_code == "0021") {
        $error_msg = translate( "Can't delete the selected message." );
    }
    if ($e_code == "0022") {
        $error_msg = translate( "An error ocurred while querying the database." );
    }
    if ($e_code == "0023") {
        $error_msg = translate( "Selected message was not found in the forum database." );
    }
    if ($e_code == "0024") {
        $error_msg = translate( "You can't reply to that message. It wasn't sent to you." );
    }
    if ($e_code == "0025") {
        $error_msg = translate( "You can't post a reply to this topic, it has been locked. Contact the administrator if you have any question." );
    }
    if ($e_code == "0026") {
        $error_msg = translate( "The forum or topic you are attempting to post to does not exist. Please try again." );
    }
    if ($e_code == "0027") {
        $error_msg = translate( "You must enter your username and password. Go back and do so." );
    }
    if ($e_code == "0028") {
        $error_msg = translate( "You have entered an incorrect password. Go back and try again." );
    }
    if ($e_code == "0029") {
        $error_msg = translate( "Couldn't update post count." );
    }
    if ($e_code == "0030") {
        $error_msg = translate( "The forum you are attempting to post to does not exist. Please try again." );
    }
    if ($e_code == "0031") {
        return(0);
    }
    if ($e_code == "0032") {
        $error_msg = translate( "Error doing DB query in check_user_pw()" );
    }
    if ($e_code == "0033") {
        $error_msg = translate( "Error doing DB query in get_pmsg_count" );
    }
    if ($e_code == "0034") {
        $error_msg = translate( "Error doing DB query in check_username()" );
    }
    if ($e_code == "0035") {
        $error_msg = translate( "You can't edit a post that's not yours." );
    }
    if ($e_code == "0036") {
        $error_msg = translate( "You do not have permission to edit this post." );
    }
    if ($e_code == "0037") {
        $error_msg = translate( "You did not supply the correct password or do not have permission to edit this post. Please go back and try again." );
    }
    if ($e_code == "0038") {
        $error_msg = translate( "Only Registered Users May Post New Topics.<br /><br />Please <a href='user.php'>LOGIN</a><br />" );
    }
    if ($e_code == "0039") {
        $error_msg = translate( "The selected user doesn't exist in the database.<br />Please check the name and try again.<br />" );
    }
    if ($e_code == "0040") {
        $error_msg = translate( "Both Old and New Password Fields Need To Be Filled In<br />Please Try Again.<br />" );
    }
    if ($e_code == "0041") {
        $error_msg = translate( "Invalid User ID<br />Please Try Again.<br />" );
    }

    if ($e_code == "0042") {
        $error_msg = translate( "You MUST provide a Poll Title and at least 2 Options<br />Please Try Again." );
    }

    include_once './header.php';

    CloseTable();

    OpenTable2();
    echo "<center><font size=\"2\"><b>$sitename " . translate("Forum Error") . "</b></font><br /><br />";
    echo translate("Error Code:") . " $e_code<br /><br /><br />";
    echo "<b>" . translate("ERROR:") . "</b> $error_msg<br /><br /><br />";
    echo "[ <a href=\"javascript:history.go(-1)\">" . translate("Go Back") . "</a> ]</center><br /><br />";

    CloseTable();

    include_once './footer.php';

    exit;
}

function getHelpFile($wichhelpfile,$wichdir='') {
global $language;

    if ($wichdir =='') {
        $hlpdir = "manual";
    } else {
        $hlpdir = "manual/$wichdir";
    }
    $hlp = "$hlpdir/$language/$wichhelpfile";
    if (!file_exists($hlp)) {
       $hlp = "$hlpdir/$wichhelpfile";
    }
    return($hlp);
}

function OpenWaitBox() {
    global $bgcolor2,$textcolor1,$textcolor2;
echo "<DIV ID=\"waitDiv\" style=\"position:absolute;left:40%;top:50%;visibility:hidden\"><center>
<table cellpadding='6' border='2' bgcolor=\"$bgcolor2\" bordercolor=\"$textcolor2\"><tr><td align=\"center\">
<font color=\"$textcolor1\" face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"4\"><b>" .translate("Fetching Request...")."</b></font><br /> <img src=\"images/await.gif\" border=\"0\"><br />
<font color=\"$textcolor1\" face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"2\">" .translate("Please Wait")."</font></td></tr></table></center></DIV> <SCRIPT> <!--
     var DHTML = (document.getElementById || document.all || document.layers);
function ap_getObj(name) { if (document.getElementById) { return document.getElementById(name).style; } else if (document.all) { return document.all[name].style;
} else if (document.layers) { return document.layers[name]; } } function ap_showWaitMessage(div,flag)  { if (!DHTML) return; var x = ap_getObj(div); x.visibility = (flag) ? 'visible':'hidden'
if(! document.getElementById) if(document.layers) x.left=280/2; return true; } ap_showWaitMessage('waitDiv', 1);
 //--> </SCRIPT>";

}

function CloseWaitBox()  {

echo "<SCRIPT language=\"javascript\"> <!--
  ap_showWaitMessage('waitDiv', 0);
 //-->
</SCRIPT><br />";

}

function substrcount($string,$search) {
    $temp = str_replace($search,$search."a",$string);
    return strlen($temp)-strlen($string);
}

function recenttopics()
{
    global $mpnTables, $phpEx, $mpn_recenttopics_num, $forumconfig;
    $boxstuff = "";
    $boxTitle = translate("Recent discussions in the <a href='forum.php'>Forums</a>");

    $sql = "SELECT t.topic_id, t.topic_title, t.topic_time, t.topic_views, t.forum_id, f.forum_name
              FROM ".$mpnTables['forumtopics']." AS t USE INDEX(forum_id)
                 , ".$mpnTables['forums']." AS f
              WHERE f.forum_id = t.forum_id
                  && f.forum_type <> '1'
              ORDER BY t.topic_time DESC
              LIMIT 0, $mpn_recenttopics_num";

    $boxstuff .= "<div class='recenttopicsblk'>\n";

    if ( ! ( @$result = mysql_query( $sql ) ) && ! @mysql_data_seek( $result, 0 ) )
    {
        $boxstuff .= translate( 'Database Error' );
        $boxstuff .= "</div>";
        themecenterposts($boxTitle, $boxstuff);
        return;
    }

    $boxstuff .= "<table width=\"100%\" cellpadding=\"1\" cellspacing=\"0\">";
    $boxstuff .="<tr><td><b>" .translate("Forum")."</b></td><td><b>" .translate("Topic")."</b></td><td align=\"center\"><b>" .translate("Replies")."</b></td><td align=\"center\"><b>" .translate("Views")."</b></td><td align=\"right\"><b>" .translate("Last Post")."</b></td></tr>";

    while ($array = mysql_fetch_array($result))
    {
        $cond = ( _UM_SHOW_DELETED_USERS_CONTENT_ ) ? ( '' ) : ( '&& poster_id >= - 1' );

        $sql = 'SELECT MAX(post_id) AS last_post, COUNT(*) AS total
                FROM ' . $mpnTables['posts'] . ' USE INDEX(idxtopics)
                WHERE topic_id = ' . $array['topic_id'] . $cond;

        if ( ! ( @$res = mysql_query( $sql ) ) && ! @mysql_data_seek( $res, 0 ) )
        {
            $boxstuff .= '<tr><td>';
            $boxstuff .= translate( 'Database Error' );
            $boxstuff .= '</td></tr>';
            continue;
        }

        $tmp = mysql_fetch_assoc( $res );
        @mysql_free_result( $res );

        if ( $tmp['total'] == 0 || is_null( $tmp['last_post'] ) )
        {
            $boxstuff .= '<tr><td>';
            $boxstuff .= translate( 'Database Tables Not Synchronized' );
            $boxstuff .= '</td></tr>';
            continue;
        }

        $tmp['total']--;
        $ploc = NULL;

        if ( $tmp['total'] > floor( $forumconfig['posts_per_page'] / 2 ) )
        {
            $pstrt = ( floor( $tmp['total'] / $forumconfig['posts_per_page'] ) ) * $forumconfig['posts_per_page'];

            $ploc = '&amp;start=' . $pstrt . '&#035;f' . $tmp['last_post'];
        }

        if (strlen($array["forum_name"]) > 30)
        {
            $array["forum_name"] = substr($array["forum_name"], 0, 30);
            $array["forum_name"] .= "...";
        }

        $boxstuff .= "<tr><td><a href=\"viewforum.$phpEx?forum=" . $array["forum_id"] . "\">";

        $boxstuff .= stripslashes($array["forum_name"]);
        $boxstuff .= "</a></td><td><a href=\"viewtopic.php?forum=" . $array["forum_id"] . "&amp;topic=" . $array["topic_id"] . $ploc . "\">";

        if (strlen($array["topic_title"]) > 30)
        {
            $array["topic_title"] = substr($array["topic_title"], 0, 30);
            $array["topic_title"] .= "...";
        }
        $boxstuff .= stripslashes($array["topic_title"]);
        $boxstuff .= "</a></td>";
        //$replies = get_total_posts($array["topic_id"], "topic");

        $boxstuff .= "<td align=\"center\"><font color='brick'>" . ( $tmp['total'] ) . "</font></td>";
        $boxstuff .= "<td align=\"center\">".$array["topic_views"]."</td><td align=\"right\">";
        $boxstuff .= getDisplayTime( $array["topic_time"], 'forumdatestring2' ). "</td></tr>";
    }

    $boxstuff .= "</table>";
    $boxstuff .= "</div>";

    themecenterposts($boxTitle, $boxstuff);
}

function recentnews() {
    global $mpn_whatsnew_entries, $mpnTables;
    global $anonymous, $mpn_anonymous_id,$phpEx;
    global $bgcolor1, $bgcolor2, $bgcolor3;

    $boxstuff = "";
    $boxTitle = translate("What's new");
    $boxstuff .= "<div class='recentnewsblk'>\n";
    $boxstuff .= "<table width=\"100%\" border='0' cellspacing='1' cellpadding='0'>";
//  $boxstuff .= "<table width=\"100%\" border=0 cellspacing=1 cellpadding=0 bgcolor=\"$bgcolor2\"><tr><td>\n";
//  $boxstuff .= "<table width=\"100%\" border=0 cellspacing=1 cellpadding=8 bgcolor=\"ffffff\">\n";

    $query="SELECT topic_id, topic_title, topic_time, topic_views, t.forum_id FROM ".$mpnTables['forumtopics']." t, ".$mpnTables['forums']." f where (f.forum_id=t.forum_id) and (forum_type <> '1') ORDER BY topic_time desc LIMIT " . $mpn_whatsnew_entries;
    $result=mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        $boxstuff .= "<tr><td><a href=\"forum.$phpEx\">" .translate("Forum Topics")."</a></td><td>" . mysql_num_rows($result) . " " .translate("posts").".</td><td align=\"right\"><a href=\"index.$phpEx?op=whatsnew\">" .translate("Detail")."</a></td></tr>";

    }

    $query="SELECT sid, title, time FROM ".$mpnTables['stories']." ORDER BY time desc LIMIT " . $mpn_whatsnew_entries;
    $result=mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        $boxstuff .= "<tr><td><a href=\"index.$phpEx\">" .translate("Articles")."</a></td><td>" . mysql_num_rows($result) . " " .translate("posts").".</td><td align=\"right\"><a href=\"index.$phpEx?op=whatsnew\">" .translate("Detail")."</a></td></tr>";

    }

    $query="SELECT g.guest_id, g.guest_title, g.guest_poster, g.guest_time, g.guest_views, u.uname FROM ".$mpnTables['guestbook']." g, ".$mpnTables['users']." u WHERE u.uid > 1 && u.uid = g.guest_poster ORDER BY g.guest_time desc LIMIT " . $mpn_whatsnew_entries;
    $result=mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        $boxstuff .= "<tr><td><a href=\"guestbook.$phpEx\">" .translate("Guestbook")."</a></td><td>" . mysql_num_rows($result) . " " .translate("posts").".</td><td align=\"right\"><a href=\"index.$phpEx?op=whatsnew\">" .translate("Detail")."</a></td></tr>";

    }



    $boxstuff .= "</table>";
    $boxstuff .= "</div>";

    themecenterposts($boxTitle, $boxstuff);
}

function last_seen()
{
    global $mpnTables, $mpn_lastseen_daysintable;

    $sql = "DELETE
            FROM " . $mpnTables['lastseen'] . "
            WHERE ( date < ( " . _MPN_TIMESTAMP . " - ( 86400 * $mpn_lastseen_daysintable ) ) )
              || username = ''";

    @( $result = mysql_query( $sql ) );

    $ip = ( isset( $_SERVER['REMOTE_ADDR'] ) )
        ? ( $_SERVER['REMOTE_ADDR'] )
        : ( 'unknown' );

//    $sql = "SELECT ( username == '" . $GLOBALS['uinf']['uname'] . "' )
//            FROM " . $mpnTables['lastseen'];

    $sql = "SELECT id FROM " . $mpnTables['lastseen']  . " WHERE username = '" . $GLOBALS['uinf']['uname'] . "'";

    $_ACTION = ( @mysql_num_rows( mysql_query( $sql ) ) )
             ? ( 'UPDATE' )
             : ( 'INSERT INTO' );

    $sql = $_ACTION . ' ' . $mpnTables['lastseen'];

    if ( $_ACTION == 'UPDATE' )
    {
        $sql .= " SET date = " . _MPN_TIMESTAMP . "
                  WHERE username = '" . $GLOBALS['uinf']['uname'] . "'";
    }
    else
    {
        $sql .= " SET id = " . FunctionLibrary :: uniqueID() . "
                    , username = '" . addslashes( $GLOBALS['uinf']['uname'] ) . "'
                    , date = " . _MPN_TIMESTAMP . "
                    , ip = '$ip'";
    }

    @mysql_query( $sql );

} // End Function

function makeLastSeen($body)
{
    global $show_user, $mpnTables, $phpEx;

    $body = '';

    $sql = "SELECT username, date
            FROM " . $mpnTables['lastseen'] . "
            WHERE username != ''
                && username != '" . $GLOBALS['uinf']['uname'] . "'
            ORDER BY date DESC
            LIMIT " . $show_user;

    if ( ! @( $result = mysql_query( $sql ) ) )
    {
        return $body;
    }

    $mins = $days = $hours = null;

    while ( list( $uname, $date ) = mysql_fetch_row( $result ) )
    {
        $realtime = _MPN_TIMESTAMP - $date;
        $dont = false;

        // how many days ago?
        if ($realtime >= (86400*2))
        { // if it's been more than 2 days
            $days = floor($realtime / (86400));
            $dont = true;
        }
        else if ($realtime >= (86400))
        { // if it's been less than 2 days
            $days = 1;
            $realtime -= (86400);
        }

        if (!$dont)
        {
            // how many hours ago?
            if ($realtime >= (3600))
            {
                //$body .= " ($realtime) ";
                $hours = floor($realtime / (3600));
                $realtime -= (3600*$hours);
            }

            // how many minutes ago?
            if ($realtime >= 60)
            {
                $mins = floor($realtime / 60);
                $realtime -= (60*$mins);
            }

            // just a little precation, although I don't *think* mins will ever be 60...
            if ($mins == 60)
            {
                $mins = 0;
                $hours += 1;
            }
        }

        $body .= "<font size='0' face='tahoma'><a href=\"./user.php?op=userinfo&amp;uname=".$uname."\">".$uname."</a>:  ";

        if ($dont)
        {
            $body .= " ".$days." ".translate("days");
        }
        else
        {
            if ($days > 0)
            {
               $body .= " ".$days." ".translate("day").(($hours == 0 && $mins == 0)?(""):(","));
            }

            if ($hours > 0)
            {
                $body .= " ".$hours." ".(($hours > 1)?(translate("hours")):translate(("hour"))).(($mins == 0)?(""):(","));
            }

            if ($mins > 0)
            {
                $body .= " ".$mins." ".(($mins > 1)?(translate("minutes")):(translate("minute")))."";
            }
            else
            { // less than a minute :)
                $body .= " ".$realtime." ".translate("seconds");
            }
        }

        $body .= " ".translate("ago")."</font><br />";

        $days = 0;
        $hours = 0;
        $mins = 0;
        $dont = false;
    }

    return $body;
}


/******************************************************************************
 *
 * Function: build_title
 * Purpose : Builds the title for the blocks
 * Input   : $newtitle = New title for the block
 *         : $originaltitle = The original title for the block
 * Output  : When $newtitle is empty $originaltitle
 * Author  : Heinz Hombergs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-03-28  o Initial Version
 *
 ******************************************************************************/

function build_title($newtitle, $originaltitle) {
    if ($newtitle != "") {
        $what= $newtitle;
    } else {
        $what = $originaltitle;
    }
    return($what);
}

/******************************************************************************
 *
 * Function: build_content
 * Purpose : Add's a additional content to the original content of the block
 * Input   : $position = Flag that the additional is above or after the original
 *                       content.
 *           $content1 = The additional content for the block
 *           $content  = The original content of the block
 * Output  :
 * Author  : Heinz Hombergs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-03-28  o Initial Version
 *
 ******************************************************************************/

function build_content($position,$content1,$content2="") {
    if (($position == 0) and ($content2 !="")) {
        $what = $content2;
    } elseif ($position == 0) {
        if ($content1 != "") {
            $what = $content1;
        } elseif ($content2 == "") {
            $what = "";
        } else {
            $what = $content2;
        }
    } elseif (($position == 1) and ($content2 == "")) {
        $what = "";
    } elseif ($position == 1) {
        if ($content1 != "") {
            $what = $content2.$content1;
        } else {
            $what = $content2;
        }
    } else {
        $what = translate("Wrong Position");
    }
    return($what);
}
/******************************************************************************
 *
 * Function: build_box
 * Purpose : Builds the need block
 * Input   : $special  = The block type
 *           $position = Position of the additional content.
 *                       0 = Above the original content.
 *                       1 = After the original content.
 *                       Works not for costum blocks, adminblocks, mainblocks,
 *                       onlineblock, headlineblock, oldnewsblock, last seen block
 *                       and pollblock
 *           $title1   = The blocktitle
 *           $content1 = Content of the block
 *           $storynum = Storynumber for the oldNews function
 * Output  :
 * Author  : Heinz Hombergs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-04-06  o Added constant stuff
 * 2001-03-28  o Initial Version
 *
 ******************************************************************************/

function build_box($special, $position, $title1, $content1, $storynum) {
    global $mpn_display_lastseen,$mpn_display_quote, $HTTP_COOKIE_VARS, $cookie, $userinfo, $Ephemerids, $user;
    global $mpn_custom_headlines, $mpn_use_headline_applet, $mpn_custom_online, $mpn_display_chatboxII;
    global $cat, $language, $mpn_use_oldnews_applet, $head_sitename, $mpnTables, $phpEx, $theme_options, $Default_Theme, $guest_online_num;

    $userinfo = $GLOBALS['uinf'];

    if ($special == BLOCK_TYPE_CUSTOM)
    {
        // Custom block

        $content = "<div class='customblk'>\n";

            $_SERVER['SAN'] -> adjustFormat( $content1, 3, 10 );
            $content .= $content1;

        $content .= "</div>\n";

        if ( $content1 != '' ) { themesidebox($title1, $content); }

    } elseif ( $special == INCLUDE_FILE ) {

        $contents = '';
        $allowed_files = array( '.php', '.htm', '.html', '.js', '.txt' );
        $ext = strrchr( $content1, '.' );

        if ( is_file( $content1 ) && in_array( $ext, $allowed_files ) )
        {
            $contents = "<div class='includesblk'>\n";

                if ( $ext == '.php' )
                {
                    $contents .= include $content1;
                }
                else
                {
                    $contents .= $_SERVER['F_LIB'] -> getFileContent( $content1, 1 );
                }

            $contents .= "</div>\n";
        }

        if ( $contents != '' ) { themesidebox( $title1, $contents ); }

    }
    else if ( $special == BLOCK_THEME_OPTIONS && ( ( _MPN_USER || _MPN_ADMIN ) && $GLOBALS['uinf']['uid'] > 1 ) )
    {
        $title = build_title( $title1, translate( 'Theme Options' ) );
        $content = '';

        if ( ( $tmp = getThemeOptions() ) != '' )
        {
            $content = '<div class="themeoptblk">' . "\n";

                $content .= $tmp;

            $content .= "\n" . '</div>' . "\n";
        }

        if ( $content != '' ) { themesidebox( $title, $content ); }

    } elseif ($special == BLOCK_TYPE_QUOTE) {

        // random quote block
        if ($mpn_display_quote==1)
        {
            $title = build_title($title1, translate("Random Quote"));

            $content = build_content($position,$content1);

            $content .= "<div class='quoteblk'>\n";

                $result = mysql_query("SELECT quote, author FROM ".$mpnTables['quotes']);
                $quote_count = mysql_num_rows($result);

                // only proceed if we have quotes in the database
                if ($quote_count > 0) {
                    $data = array();
                    while($row = mysql_fetch_row($result))
                    {
                        $data[] = $row;
                    }

                    srand ((float) microtime() * 10000000);
                    $rand_key = array_rand($data);

                    // this is the start of the content for the qotd block
                    $content .= '<font size="1"><center><i>';
                    // add the quote text and remove whitespaces at begin or end
                    $content .= trim($data[$rand_key][0]);
                    $content .= '</i><br />';
                    // add the author and then close everything
                    $content .= '-- '.stripslashes($data[$rand_key][1]).'<br /></center></font>';
                } else {
                    // this is what we say when the quotes database is empty
                    $content .= translate("Sorry, there are no quotes in the database!");
                }

            $content .= "</div>\n";

            // now we build the box somewhere on the side

            $content = build_content($position,$content1,$content);

            if ( $result ) { themesidebox($title, $content); }
        }

    } elseif ($special == BLOCK_TYPE_ONLINE) {

        $title = build_title($title1,translate("Who's Online"));

        $content2 = build_content($position,$content1);

        $content1a = myphpnuke_online( $content2 );

        $content = "<div class='whoonlineblk'>\n";

            $content .= $content1a;

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $content1a != '' ) { themesidebox($title, $content); }

    }
    elseif ( $special == BLOCK_TYPE_USER && ( ! empty( $GLOBALS['uinf']['ublock'] ) && $GLOBALS['uinf']['ublockon'] ) )
    {
        $tmp = $GLOBALS['uinf']['ublock'];
        $_SERVER['SAN'] -> adjustFormat( $tmp, 3, 10 );

        if ( empty( $position ) ) { $position = 1; }

        $title = translate( 'Menu for' ) . ' ' . $GLOBALS['uinf']['uname'];

        $content = build_content( $position,$content1 );

        $content .= "<div class='userblk'>\n";

            $content .= $tmp;

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        unset( $tmp );

        if ( $GLOBALS['uinf']['ublock'] != '' ) { themesidebox($title, $content); }

    }
    elseif ($special == BLOCK_TYPE_CATEGORY)
    {
        // categoryblock
        // trini0 [09-18-2003]: Went back to original, as the new code wasn't working
        $result = mysql_query("select catid, title from ".$mpnTables['stories_cat']." order by title");
        $numrows = mysql_num_rows($result);
        if ($numrows == 0) {
        } else {
            $boxstuff = build_content($position,$content1);
            while(list($catid, $title) = mysql_fetch_row($result)) {
                $result2 = mysql_query("SELECT COUNT(*) FROM ".$mpnTables['stories']." where catid='$catid'");
                $numrows = mysql_result($result2, 0);
                if ($numrows > 0) {
                    $res = mysql_query("select time from ".$mpnTables['stories']." where catid='$catid' order by sid DESC limit 0,1");
                    list($time) = mysql_fetch_row($res);
                    ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $dat);
                    if ($cat == $catid) {
                        $boxstuff .= "<li><b>$title</b>";
                    } else {
                        $boxstuff .= "<li><a href=\"categories.$phpEx?op=newindex&amp;catid=$catid\">$title</a> <font size='1'>($dat[2]/$dat[3])</font>";
                    }
                }
            }
            $title = build_title($title1,translate("Categories"));
            $boxstuff = build_content($position,$content1,$boxstuff);
            themesidebox($title, $boxstuff);
        }
    } elseif ($special == BLOCK_TYPE_BIGSTORY) {

        // bigstoryblock
        $today = getdate();
        $day = $today["mday"];
        if ($day < 10) {
            $day = "0$day";
        }
        $month = $today["mon"];
        if ($month < 10) {
            $month = "0$month";
        }
        $year = $today["year"];
        $tdate = "$year-$month-$day";

        $content = build_content($position,$content1);

        $options = null;

        $content .= "<div class='bigstoryblk'>\n";

            $result = mysql_query("select sid, title from ".$mpnTables['stories']." where (time LIKE '%$tdate%') order by counter DESC limit 0,1");
            list($fsid, $ftitle) = mysql_fetch_row($result);

            if ((!$fsid) AND (!$ftitle)) {
                $content .= "<center>".translate("There isn't a Biggest Story for Today, yet.")."</center>";
            } else {

                $content .= "<center>".translate("Today's most read Story is:")."<br /><br />";
                if (isset($cookie[4])) {
                    $options .= "&mode=$cookie[4]";
                } else {
                    $options .= "&mode=thread";
                }
                if (isset($cookie[5])) {
                    $options .= "&order=$cookie[5]";
                } else {
                    $options .= "&order=0";
                }
                if (isset($cookie[6])) {
                    $options .= "&thold=$cookie[6]";
                } else {
                    $options .= "&thold=0";
                }
                $content .= "<a href='article.$phpEx?sid=$fsid$options'>$ftitle</a></center>";
            }

            $boxtitle = build_title($title1,translate("Today's Big Story"));

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $result ) { themesidebox($boxtitle, $content); }

    } elseif ($special == BLOCK_TYPE_SEARCH) {

        // searchblock

        $title = build_title($title1,translate("Search Articles"));

        $content = build_content($position,$content1);

        $content .= "<div class='searchblk'>\n";

            $content .= "<form action=\"search.$phpEx\" method='post'>";

            $content .= "<p class='center'>\n";

            $content .= "<input type='text' name='query' size='14' /><br /><br />";
            $content .= "<input class='button' type='submit' value=" . translate( "Search" ) . " />";
            $content .= "</p></form>";

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $content != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_POLL) {
        // pollblock

        if ( include_once './pollFunctions.php' )
        {
            $pollID = pollLatest();
            $title = build_title($title1,translate("Survey"));

            $content2 = build_content($position,$content1);

            $content1a = pollMain($pollID, $content2);

            $content = "<div class='pollblk'>\n";

                $content .= $content1a;

            $content .= "</div>\n";

            $content = build_content($position,$content1,$content);

            if ( $content1a != '' ) { themesidebox( $title, $content ); }
        }

    } elseif ($special == BLOCK_TYPE_LOGIN) {
        // loginblock
        if ( ! _MPN_USER ) {

            $title = build_title($title1,translate("Login"));

            $boxstuff = build_content($position,$content1);

            $boxstuff .= "<div class='loginblk'>\n";

                $boxstuff .= "<center><form action='user.$phpEx' method='post'>";
                $boxstuff .= "<font size='1'>".translate("Nickname")."</font><br />";
                $boxstuff .= "<input type='text' name='uname' size='12' maxlength='25'><br /><br />";
                $boxstuff .= "<font size='1'>".translate("Password")."</font><br />";
                $boxstuff .= "<input type='password' name='pass' size='12' maxlength='20'><br /><br />";
                $boxstuff .= "<input type='hidden' name='op' value='login'>";
                $boxstuff .= "<input class='button' type='submit' value='".translate("Login")."'></form>";

                $boxstuff .= "<br />&gt;&gt;&nbsp;<a href='user.$phpEx?op=register'>".translate("New Members")."</a>&nbsp;&lt;&lt;<br /><br />";

                $boxstuff .= "</center>";

            $boxstuff .= "</div>\n";

            $boxstuff = build_content($position,$content1,$boxstuff);

            if ( $boxstuff != '' ) { themesidebox($title, $boxstuff); }
        }

    } elseif ($special == BLOCK_TYPE_EPHEM) {

        // ephemeridsblock
        if ($Ephemerids == 1)
        {
            $today = getdate();
            $eday = $today['mday'];
            $emonth = $today['mon'];
            $cnt = 0;

            $result = mysql_query("select yid, content from ".$mpnTables['ephem']." where did='$eday' AND mid='$emonth'");

            $title = build_title($title1,translate("Ephemerids"));

            $boxstuff = build_content($position,$content1);

            $boxstuff .= "<div class='ephemblk'>\n";

                $boxstuff .= "<center><b>".translate("One Day like Today...")."</b></center><br />";

                while(list($yid, $content) = mysql_fetch_array($result))
                {
                    if ($cnt==1) {
                        $boxstuff .= "<br /><br />";
                    }
                    $boxstuff .= "<b>$yid</b><br />";
                    $boxstuff .= "$content";
                    $cnt = 1;
                }

            $boxstuff .= "</div>\n";

            $boxstuff = build_content($position,$content1,$boxstuff);

            if ( $boxstuff != '' ) { themesidebox($title, $boxstuff); }
        }

    } elseif ($special == BLOCK_TYPE_HEADLINE) {
        // headline block

        $result2 = mysql_query("select COUNT(*) as help from ".$mpnTables['headlines']." where status='1'");

        list($sum) = mysql_fetch_row($result2);

        if ($sum > 0)
        {
            if ( $mpn_use_headline_applet == 1 )
            {
                if ( ! is_null( ( $content_check = applet_headlines( $content1 ) ) ) )
                {
                    $content = "<div class='headlineapltblk'>\n";

                        $content .=  $content_check;

                    $content .= "</div>\n";

                    $content = build_content($position,$content);

                    $title = build_title($title1,translate("Headlines"));

                    if ( $content != '' ) { themesidebox($title, $content); }
                }
            }
            else
            {
                $title = build_title($title1,translate("Headlines"));

                $content = null;

                myphpnuke_headlines($content,$title,$position);
            }
        }

    } elseif ($special == BLOCK_TYPE_OLDNEWS) {

        // oldnewsblock
        $title = build_title($title1,translate("Past Articles"));

        $content2 = build_content($position,$content1);

        if ($mpn_use_oldnews_applet==1)
        {
            $content1a = applet_oldnews($storynum,$content2);

            $content = "<div class='oldapltnewsblk'>\n";

                $content .= $content1a;

            $content .= "</div>\n";
        }
        else
        {
            $content1a = oldNewsNew($storynum, $content2);

            $content = "<div class='oldnewsblk'>\n";

                $content .= $content1a;

            $content .= "</div>\n";
        }

        $content = build_content($position,$content1,$content);

        if ( $content1a != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_WAITINGCONTENT) {

        // waiting content block
        $title = build_title($title1,translate("Waiting Content"));

        $content = build_content($position,$content1);

        $content .= "<div class='adminblk'>\n";

            $result = mysql_query("SELECT COUNT(*) from ".$mpnTables['queue']);
            $num = mysql_result($result, 0);
            $content .= "<li><a href=\"admin.$phpEx?op=submissions\">".translate("Submissions")."</a>: $num";
            $result = mysql_query("SELECT COUNT(*) from ".$mpnTables['reviews_add']);
            $num = mysql_result($result, 0);
            $content .= "<li><a href=\"admin.$phpEx?op=reviews\">".translate("Waiting Reviews")."</a>: $num";
            $result = mysql_query("SELECT COUNT(*) from ".$mpnTables['links_newlink']);
            $num = mysql_result($result, 0);
            $content .= "<li><a href=\"admin.$phpEx?op=links\">".translate("Waiting Links")."</a>: $num";
            $result = mysql_query("SELECT COUNT(*) from ".$mpnTables['links_modrequest']." where brokenlink=1");
            $totalbrokenlinks = mysql_result($result, 0);
            $content .= "<li><a href=\"admin.$phpEx?op=LinksListBrokenLinks\">".translate("Broken Link")."</a>: $totalbrokenlinks";
            $result2 = mysql_query("SELECT COUNT(*) from ".$mpnTables['links_modrequest']." where brokenlink=0");
            $totalmodrequests = mysql_result($result2, 0);
            $content .= "<li><a href=\"admin.$phpEx?op=LinksListModRequests\">".translate("Modified Links")."</a>: $totalmodrequests";

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $content != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_LASTSEEN) {

        // last seen block
        if ($mpn_display_lastseen == 1)
        {
            $title = build_title($title1,translate("Last Seen"));

            $content2 = build_content($position,$content1);

            $content1a = makeLastSeen( $content2 );

            $content = "<div class='lastseenblk'>\n";

                $content .= $content1a;

            $content .= "</div>\n";

            $content = build_content($position,$content1,$content);

            if ( $content1a != '' ) { themesidebox($title, $content); }
        }

    } elseif ($special == BLOCK_TYPE_RECENTREVIEWS) {

        //Change limit to what you want
        $limit = 10;

        // recent reviews block
        $title = build_title($title1,translate("Recent Reviews"));

        $content2 = build_content($position,$content1);

        $content1a = reviewsBlockNew("date", $content2, $limit);

        $content = "<div class='newreviewsblk'>";

            $content .= $content1a;

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $content1a != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_POPULARREVIEWS) {

        // popular reviews block
        //Change limit to what you want
        $limit = 10;
        $title = build_title($title1,sprintf(translate("Top %s Reviews"),$limit));

        $content2 = build_content($position,$content1);

        $content1a = reviewsBlockNew("hits", $content2, $limit);

        $content = "<div class='popreviewsblk'>";

            $content .= $content1a;

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $content1a != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_RECENTLINKS) {

        // recent links block
        //Change limit to what you want
        $limit = 5;
        $title = build_title($title1,translate("Recent Links"));

        $content2 = build_content($position,$content1);
        $content1a = linksBlockNew("date", $content2, $limit);

        $content = "<div class='newlinksblk'>";

            $content .= $content1a;

        $content .= "</div>\n";

        $content = build_content($position,$content1,$content);

        if ( $content1a != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_POPULARLINKS) {

        // popular links block
        //Change limit to what you want
        $limit = 5;
        $title = build_title($title1,sprintf(translate("Top %s Links"),$limit));

            $content2 = build_content($position,$content1);
            $content1a = linksBlockNew("hits", $content2, $limit);

            $content = "<div class='poplinksblk'>";

                $content .= $content1a;

            $content .= "</div>\n";

            $content = build_content($position,$content1,$content);

        if ( $content1a != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_PARTNER) {

        $title = build_title($title1,translate("Partnersites"));

        $content = build_content($position,$content1);

        $content .= "<div class='partnerblk'>\n";

            $result = mysql_query("select * from ".$mpnTables['click']);
            $c = 0;
            while (list($num, $hits, $url, $image, $text) = mysql_fetch_row($result))
            {
                if (isset($image) && $c > 0) $content .= "<img src = \"images/pix.gif\" height = \"5\">";

                $content .= "<a href='partner.php?action=click&ampid=$num' target='_blank'>";
                $content .= "<img src=\"{$image}\" border='0' alt='$text'>";
                $content .= "</a>";
                $c++;
            }
            unset($c);

            $content .= "</div>\n";

            $content = build_content($position,$content1,$content);

            if ( $result ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_RANDOM_GALLERY) {

            global $HTTP_COOKIE_VARS, $mpnTables, $phpEx;
        $title = build_title($title1,translate("Random Gallery"));
            include 'admin/gallery/config.php';
            mt_srand((double)microtime()*1000000);
        if ( _MPN_USER ) {
                $total = mysql_fetch_array(mysql_query("SELECT COUNT(p.pid) AS total FROM ".$mpnTables['gallery_pictures']." AS p LEFT JOIN ".$mpnTables['gallery_categories']." AS c ON c.gallid=p.gid WHERE (extension='jpg' OR extension='gif' OR extension='png') AND c.visible>=1"));
            } else {
                $total = mysql_fetch_array(mysql_query("SELECT COUNT(p.pid) AS total FROM ".$mpnTables['gallery_pictures']." AS p LEFT JOIN ".$mpnTables['gallery_categories']." AS c ON c.gallid=p.gid WHERE (extension='jpg' OR extension='gif' OR extension='png') AND c.visible>=2"));
        }
        $p = mt_rand(0,($total['total'] - 1));

        if ( _MPN_USER ) {
                $pic = mysql_fetch_array(mysql_query("SELECT p.pid, p.img, p.name, p.description, c.galloc FROM ".$mpnTables['gallery_pictures']." AS p LEFT JOIN ".$mpnTables['gallery_categories']." AS c ON c.gallid=p.gid WHERE (extension='jpg' OR extension='gif' OR extension='png') AND c.visible>=1 LIMIT $p,1"));
        } else {
                $pic = mysql_fetch_array(mysql_query("SELECT p.pid, p.img, p.name, p.description, c.galloc, c.visible FROM ".$mpnTables['gallery_pictures']." AS p LEFT JOIN ".$mpnTables['gallery_categories']." AS c ON c.gallid=p.gid WHERE c.visible>=2 AND (extension='jpg' OR extension='gif' OR extension='png') LIMIT $p,1"));
        }

        $content = "<div class='galleryblk'>\n";

        if ( file_exists("$gallerypath/" . $pic['galloc'] . "/thumb/" . $pic['img']) ) {
                $content .= "<center><a href=\"$baseurl&amp;do=showpic&amp;pid=" . $pic['pid'] . "\"><img src=\"$gallerypath/" . $pic['galloc'] . "/thumb/" . $pic['img'] . "\" border=\"0\" alt=\"" . $pic['description'] . "\"></a></center>";
            } else {
                $content .= "<center><a href=\"$baseurl&amp;do=showpic&amp;pid=" . $pic['pid'] . "\"><img src=\"$gallerypath/" . $pic['galloc'] . "/" . $pic['img'] . "\" width=\"110\" border=\"0\" alt=\"" . $pic['description'] . "\"></a></center>";
            }
        if (!_MPN_USER && ($pic['visible'] < "2")) {
            $content .= "<div align=\"center\"><a href = \"user.$phpEx?op=register\">".translate("Members Only")."</a></div>";
        }

        $content .= "</div>\n";

        if ( $pic ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_STATS) {

    global $mpnTables, $member_online_num;
    $title = build_title($title1,translate("Stats"));
        $who_online_num = $guest_online_num + $member_online_num;
        $result5 = mysql_query("select uname from ".$mpnTables['users']." WHERE uid > 1 order by uid DESC limit 0,1");
        list($lastuser) = mysql_fetch_row($result5);

        $result8 = mysql_query("select sid from ".$mpnTables['stories']." order by sid DESC limit 0,1");
        list($totala) = mysql_fetch_row($result8);

        $result7 = mysql_query("select count(uid) from ".$mpnTables['users']." WHERE uid > 1 order by uid");
    $numrows = mysql_result($result7, 0);

        $result6 = mysql_query("SELECT count FROM ".$mpnTables['counter']." order by count DESC limit 0,1");
        list($totalc) = mysql_fetch_row($result6);

        $result9 = mysql_query("select count(artid) from ".$mpnTables['seccont']."");
        $secanum = mysql_result($result9, 0);

        //affiche les informations

        $content = "<div class='statsblk'>\n";

            $content .= "" .translate("Page Views: ")."$totalc<br />
            " .translate("Articles:")." $secanum <br />
            " .translate("News:")." $totala<br />
            " .translate("Members:")." $numrows <br />" .translate("Last Member: ")."<b><a href=user.php?op=userinfo&uname=$lastuser>$lastuser</a></b><br />";

        $content .= "</div>\n";

        if ( $content != '' ) { themesidebox($title, $content); }

    } elseif ($special == BLOCK_TYPE_RANDOM_BANNER) {

        global $randbanner;
        $title = build_title($title1,translate("Random Banner"));
        global $mpnTables, $maxbanner;
        $image= array();
        $url = array();
        $result = mysql_query("select url,image from ".$mpnTables['rand_banners']."");
        while($banners = mysql_fetch_object($result))
        {
            array_push($image, $banners->image);
            array_push($url, $banners->url);
        }
        mt_srand((double)microtime() * 1000000);
        $img_count = count($image);

        $max = 0;

        if ($img_count >= 1) {
            $rand_num = mt_rand (0, $img_count - 1);
            $max = $maxbanner;
            if($img_count < $max){
                $max = $img_count;
            }
        }
        $counter = 0;

        $boxstuff = "<div class='bannerblk'>";

        $boxstuff .= "<center>";
        while($counter < $max){
            if ($counter > 0) $boxstuff .= "<img src = \"images/pix.gif\" height = \"5\">";
            $boxstuff .= "<div align=\"center\"><a href=\"$url[$rand_num]\" target=\"_blank\">";
            $boxstuff .= "<img src = \"".dirname($image[$rand_num])."/".basename($image[$rand_num])."\" border='0'>";
            $boxstuff .= "</a></div>\n";
            $counter++;
            $rand_num++;
            if($rand_num==$img_count){
                $rand_num = 0;
            }
        }
        $boxstuff .= "</center>";

        $boxstuff .= "</div>\n";

        if ( !empty( $image ) ) { themesidebox($title,$boxstuff); }

    }
    else if ($special == BLOCK_TYPE_CHATBOXII)
    {
        if ($mpn_display_chatboxII == 2)
        {
            include_once './chatboxII.php';
            makeChatBoxII();
        }

    }

    if ( isset( $result ) ) { mysql_free_result( $result ); }

}

/******************************************************************************
 *
 * Function: make_sidebar
 * Purpose : Builds the blocks on both sides
 * Input   : $side = On wich side should the block are displayed?
 *             0, l, left : On the left side
 *             1, r, right: On the right side
 *             2, o, one:   Only on one side (
 *                          Call from themes header.php makes all blocks on the left side
 *                          and from themes footer.php for the right site)
 *           $storynum = Storynumber for the oldNews function
 * Output  :
 * Author  : Heinz Hombergs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-04-06  o Added constant stuff
 * 2001-03-28  o Initial Version
 *
 ******************************************************************************/

function make_sidebar($side, $storynum)
{
    global $mpnTables;

    if ( defined( '_T_PAGE_LAYOUT' ) && _T_PAGE_LAYOUT == 4 ) { return; }

    $addcond = ( defined( '_T_BLOCK_FORMAT' ) && _T_BLOCK_FORMAT == 4 )
             ? ( '&& ( special = 0 || special = 8 || special > 22 )' )
             : ( NULL );

    if (($side == "l") or ($side == 'left') or ($side == "0")) {
        $side = BLOCK_SIDE_LEFT;
    } elseif (($side == "r") or ($side == 'right') or ($side == "1")) {
        $side = BLOCK_SIDE_RIGHT;
    } elseif (($side == "2") or ($side == 'o') or ($side == "one")) {
        $side = BLOCK_SIDE_ONE;
    } elseif (($side != BLOCK_SIDE_LEFT) and ($side != BLOCK_SIDE_RIGHT)) {
        $side = BLOCK_SIDE_LEFT;
    }

    if ($side == BLOCK_SIDE_ONE)
    {
        if ( _MPN_ADMIN )
        {
            $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where visible='1' && category<'5' $addcond order by weight,bid";
        }
        elseif ( _MPN_USER )
        {
            $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where (admin='0' or admin ='1') and visible='1' and category<'5' $addcond order by weight,bid";
        }
        else
        {
            $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where admin='0' and visible='1' and category<'5' $addcond order by weight,bid";
        }
    }
    else
    {
        if ( _MPN_ADMIN )
        {
            $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where side='$side' and visible='1' and category<'5' $addcond order by weight,bid";
        }
        elseif ( _MPN_USER )
        {
            $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where (admin='0' or admin='1') and side='$side' and visible='1' and category<'5' $addcond order by weight,bid";
        }
        else
        {
            $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where admin='0' and side='$side' and visible='1' and category<'5' $addcond order by weight,bid";
        }
    }

    if ( ! ( $result = mysql_query( $sql ) ) && ! @mysql_data_seek( $result, 0 ) ) { return; }

    while ( list($special, $position, $title, $content) = mysql_fetch_row($result))
    {
        build_box($special, $position, $title, $content, $storynum);
    }
}


/******************************************************************************
 *
 * Function: reviewsBlockNew
 * Purpose : Display the most recent or most popular reviews
 * Input   : $order = date for the most recent reviews
 *                    hits for the most popular reviews
 *           $content = The optional above content
 *           $limit   = How many reviews are displayes
 * Output  : The content for the desired most recent or most popular links block
 * Author  : Jeff Lambert
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-03-30  o Initial Version
 *
 ******************************************************************************/
function reviewsBlockNew($order, $content, $limit) {
    global $mpnTables,$phpEx;
    //$order = date for most recent reviews
    //$order = hits for most popular reviews

    $result = mysql_query("select id, title, date from ".$mpnTables['reviews']." order by $order DESC limit $limit");

    if ( $result )
    {
        $content .= "<font size='1'>";

        for ($x = 0; $x < $limit; $x++) {
            $myrow=mysql_fetch_array($result);
            $id = $myrow["id"];
            $review = $myrow["title"];
            if (strlen($review) >= 19) {
                $review = substr($review,0,18)."...";
            }
            $content .= "<li><a href='reviews.$phpEx?op=showcontent&amp;id=$id'>$review</a><br />";
        }
        $content .= "<center>&gt;&gt; <a href='reviews.$phpEx?op=write_review'>" .translate("Write A Review!")."</a> &lt;&lt;</center>";

        $content .= "</font>";

        return($content);

        mysql_free_result($result);
    }
}

/******************************************************************************
 *
 * Function: linksBlock
 * Purpose : Display the most recent or most popular links
 * Input   : $order = date for the most recent links
 *                    hits for the most popular links
 *           $content = The optional above content
 *           $limit   = How many reviews are displayes
 * Output  : The content for the desired most recent or most popular links block
 * Author  : Jeff Lambert
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-03-30  o Initial Version
 *
 ******************************************************************************/

function linksBlockNew($order, $content,$limit) {
    global $mpnTables,$phpEx;
    //$order = date for most recent reviews
    //$order = hits for most popular reviews

    $result = mysql_query("select lid, title, date, hits from ".$mpnTables['links_links']." order by $order DESC limit $limit");

    if ( $result )
    {
        $content .= "<font size='1'>";

        for ($x = 0; $x < $limit; $x++) {
            $myrow=mysql_fetch_array($result);
            $lid = $myrow["lid"];
            $link = $myrow["title"];
            if (strlen($link) >= 19) {
                $link = substr($link,0,18)."...";
            }
            $content .= "<li><a href='links.$phpEx?op=visit&amp;lid=$lid' target='new'>$link</a><br />";
        }
        $content .= "<center>&gt;&gt; <a href='links.$phpEx?op=AddLink'>" .translate("Add Your Link!")."</a> &lt;&lt;</center>";

        $content .= "</font>";

        return($content);

        mysql_free_result($result);
    }
}

/******************************************************************************
 *
 * Function: oops_br2nl
 * Purpose : Converts <br/>-Tags to newline chars
 * Input   : $string = String to convert.
 * Output  : The converted string
 * Author  : goghs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-04-08  o Initial Version
 *
 ******************************************************************************/
function oops_br2nl($string) {
    $string = eregi_replace('<br[[:space:]]*/?[[:space:]]*>', "\n", $string);
    return $string;
}

/******************************************************************************
 *
 * Function: oops_nl2br
 * Purpose : Convert newline chars to <br/>-Tags
 * Input   : $string = String to convert.
 * Output  : The converted string
 * Author  : goghs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-04-08  o Initial Version
 *
 ******************************************************************************/
function oops_nl2br($string) {
    $string = preg_replace("/(\015\012)|(\015)|(\012)/","<br />",$string);
    return $string;
}



/******************************************************************************
 *
 * Function: loadForumConfig
 * Purpose : Loads the config for the forum
 * Input   :
 * Output  :
 * Author  : goghs
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-04-08  o Initial Version
 *
 ******************************************************************************/
function loadForumConfig() {
    global $mpnTables;
    // This function retrieve forum-wide setting from config table
    // @return: an array including all forum settings
    // $forumconfig['allow_html'], $forumconfig['allow_bbcode'],
    // $forumconfig['allow_sig'], $forumconfig['posts_per_page'],
    // $forumconfig['hot_threshold'], $forumconfig['topics_per_page']
    // This implementation also gives possibility to expand forum settings
    // For example, if you setup another config option, $allow_forbar,
    // you just alter the config table to add field 'allow_foobar'
    // You need not edit this function, you just use:
    // $forumconfig = loadForumConfig();
    // if $forumconfig['allow_foobar'] {
    // some code;
    $sql = "SELECT * FROM ".$mpnTables['forumconfig'];

    if($result = mysql_query($sql)) {
        if($myrow = mysql_fetch_array($result)) {
            return ($myrow);
        }
    }
}

function blocks($side) {
    global $storynum;
    if (strtolower($side) == 'left') {
        make_sidebar("left",$storynum);
    } elseif (strtolower($side) == 'right') {
        make_sidebar("right",$storynum);
    }
}

function HTMLbuttons( $id = NULL )
{
    switch( $id )
    {
        case 1: $id = 'hometext'; break;
        case 2: $id = 'bodytext'; break;
        case 3: $id = 'notes'; break;
        DEFAULT: $id = 'story'; break;
    }

    $targetElement = 'coolsus.' . $id;

    echo '</p><p class="row">';

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('url', {$targetElement} );\" title=\"" . translate( 'URL' ) . "\">" . translate( 'URL' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('email', {$targetElement} );\" title=\"" . translate( 'Email' ) . "\">" . translate( 'Email' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('image', {$targetElement} );\" title=\"" . translate( 'Image' ) . "\">" . translate( 'Image' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('bold', {$targetElement} );\" title=\"" . translate( 'Bold' ) . "\">" . translate( 'Bold' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('italic', {$targetElement} );\" title=\"" . translate( 'Italic' ) . "\">" . translate( 'Italic' ) . "</a></span>";

   echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('literal', {$targetElement} );\" title=\"" . translate( 'Literal' ) . "\">" . translate( 'Literal' ) . "</a></span>";

    echo '</p><p class="row">';

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('quote', {$targetElement} );\" title=\"" . translate( 'Quote' ) . "\">" . translate( 'Quote' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('code', {$targetElement} );\" title=\"" . translate( 'Code' ) . "\">" . translate( 'Code' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('listopen', {$targetElement} );\" title=\"" . translate( 'List Open' ) . "\">" . translate( 'List Open' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('listitem', {$targetElement} );\" title=\"" . translate( 'List Item' ) . "\">" . translate( 'List Item' ) . "</a></span>";

    echo "<span class=\"button\"><a href=\"javascript: x()\" onClick=\"DoPrompt('listclose', {$targetElement} );\" title=\"" . translate( 'List Close' ) . "\">" . translate( 'List Close' ) . "</a></span>";

    echo '</p>';

} // End Function



/******************************************************************************
 *
 * Function: make_userbar
 * Purpose : Builds the userblocks on both sides
 * Input   : $side = On wich side should the block are displayed?
 *             0, l, left : On the left side
 *             1, r, right: On the right side
 *             2, o, one:   Only on one side (
 *                          Call from themes header.php makes all blocks on the left side
 *                          and from themes footer.php for the right site)
 *           $storynum = Storynumber for the oldNews function
 * Output  :
 * Author  : BlackV_Life
 *
 * History
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-07-06  o Initial Version
 *
 ******************************************************************************/

function make_userbar($side, $storynum) {
    global $admin, $user, $mpnTables, $uname, $op;

        if ((($user !="") or ($uname !="")) and ($op!="logout"))
        {
            if (($side == "l") or ($side == 'left') or ($side == "0")) {
                $side = BLOCK_SIDE_LEFT;
            } elseif (($side == "r") or ($side == 'right') or ($side == "1")) {
                $side = BLOCK_SIDE_RIGHT;
            } elseif (($side == "2") or ($side == 'o') or ($side == "one")) {
                $side = BLOCK_SIDE_ONE;
            } elseif (($side != BLOCK_SIDE_LEFT) and ($side != BLOCK_SIDE_RIGHT)) {
                $side = BLOCK_SIDE_LEFT;
            }
            if ($side == BLOCK_SIDE_ONE) {
                $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where category='5' and visible='1' order by weight,bid";
            } else {
                $sql = "SELECT special, position, title, content from ".$mpnTables['blocks']." where category='5' and visible='1' order by weight,bid";
            }
        $result = mysql_query($sql);
        while (list($special, $position, $title, $content) = mysql_fetch_row($result)) {
            build_box($special, $position, $title, $content, $storynum);
        }
        }

}

/******************************************************************************
 *
 * Function: block
 * Purpose :
 * Input   :
 * Output  :
 * Author  : modif for codephp codephp.net
 *
 * History : use function themecenterposts add order by hit or order by date
 *
 * Date        Comments
 * ----------------------------------------------------------------------------
 * 2001-11-12  o Version 3.0
 *
 ******************************************************************************/

function cblock(){
    global $liens_view, $download_view, $artclies_view, $review_view, $bgcolor1, $sections_view;
    /******************************************************************************
    * Gauche
    ******************************************************************************/

    //Kiril: Removed some nested tables and redid formatting on all sections

    $blocktitle ="" . translate("News") ."";

    $boxstuff ="<div class='newsblk'>\n";   //Main DIV

    $boxstuff .="<table cellspacing='0' cellpadding='0' width='100%' summary=''><tr><td colspan='0' style='width: 50%;'>\n\n";

    /******************************************************************************
    * Gauche  download
    ******************************************************************************/

    if ($download_view == 1) {

        global $mpnTables,$nombre_download,$ordredownload;
        if ($ordredownload==1) {
            $ordredownload ="date";
            $sectitle1 = translate("New Downloads");
        } else {
            $ordredownload ="hits";
            $sectitle1 = translate("Hot Downloads");
        }
        $result = mysql_query("select lid, title, hits FROM ".$mpnTables['downloads_downloads']." ORDER BY $ordredownload DESC LIMIT $nombre_download");

        $boxstuff .=  "<div class='center'><br /><div class='cblocktitles'>$sectitle1</div><a href=\"download.php\">" .translate("All Downloads")."</a><hr />\n\n";
        while (list($lid, $title, $hits) = mysql_fetch_row($result)) {
            $boxstuff .=  "<ul><li><a href=\"download.php?op=viewdownloaddetails&amp;lid=$lid\">$title</a>&nbsp;<span class='font5'>(".$hits.")</span></li></ul>\n\n";
        }
        $boxstuff .= "</div><br />\n";

}

     /******************************************************************************
    * Gauche  section
    ******************************************************************************/

    if ($sections_view==1) {

        global $mpnTables,$nombre_sections,$ordresections, $textcolor1;
        if ($ordresections==1) {
            $ordresections="date";
            $sectitle2 = translate("New Sections");
        } else {
            $ordresections="counter";
            $sectitle2 = translate("Hot Sections");
        }
        $result = mysql_query("select artid,secid, title,counter from ".$mpnTables['seccont']." order by $ordresections DESC LIMIT $nombre_sections ");

        $boxstuff .=  "<div class='center'><br /><div class='cblocktitles'>$sectitle2</div><a href=\"sections.php\">" . translate("All sections")."</a><hr />\n\n";
        while (list($artid,$secid ,$headlinetitle , $counter) = mysql_fetch_row($result)) {
            if(strlen($headlinetitle) > 25) {
                $headlinetitle = substr($headlinetitle,0,25);
                $headlinetitle .= "...";
            }
            $boxstuff .=  "<ul><li><a href='sections.php?op=viewarticle&amp;artid=$artid'>$headlinetitle</a>&nbsp;<span class='font5'>($counter)</span></li></ul>\n\n";
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * Gauche  article
    ******************************************************************************/

    if ($artclies_view==1) {
        global $mpnTables,$nombre_articles,$ordrearticles, $textcolor1;
        if ($ordrearticles==1) {
            $ordrearticles="time";
            $sectitle3 = translate("New Articles");
        } else {
            $ordrearticles="counter";
            $sectitle3 = translate("Hot Articles");
        }
        $queryblock="SELECT sid, title, counter FROM ".$mpnTables['stories']." ORDER BY $ordrearticles DESC LIMIT $nombre_articles";
        $result=mysql_query($queryblock);
        $boxstuff .= "<div class='center'><br /><div class='cblocktitles'>$sectitle3</div><a href=\"submit.php\">" . translate("Submit news") . "</a><hr />\n\n";
        while (list($sid, $headlinetitle ,$counter) = mysql_fetch_row($result)) {
            if(strlen($headlinetitle) > 25) {
                $headlinetitle = substr($headlinetitle,0,25);
                $headlinetitle .= "...";
            }
            $boxstuff .= "<ul><li><a href=\"article.php?sid=$sid\">$headlinetitle</a>&nbsp;<span class='font5'>($counter)</span></li></ul>\n\n";
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * Gauche  review
    ******************************************************************************/

    if ($review_view==1) {

        global $mpnTables, $nombre_reviews,$ordrereviews, $textcolor1;
        if ($ordrereviews==1) {
            $ordrereviews="date";
            $sectitle4 = translate("New Reviews");
        } else {
            $ordrereviews="hits";
            $sectitle4 = translate("Hot Reviews");
        }
        $queryblock3="SELECT id, title ,hits FROM ".$mpnTables['reviews']." ORDER BY $ordrereviews DESC limit $nombre_reviews";
        $result=mysql_query($queryblock3);

        $boxstuff .= "<div class='center'><br /><div class='cblocktitles'>$sectitle4</div><a href=\"reviews.php?op=write_review\">" . translate("Submit reviews") . "</a> | <a href=\"reviews.php\">" . translate("View All") . "</a><hr />\n\n";
        if ($result) {
            while (list($rid,$reviewtitle,$hits) = mysql_fetch_row($result)) {
                $boxstuff .= "<ul><li><a href=\"reviews.php?op=showcontent&amp;id=$rid\" />$reviewtitle</a>&nbsp;<span class='font5'>($hits)</span></li></ul>\n\n";
            }
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * Gauche  links
    ******************************************************************************/

    if ($liens_view==1) {

        global $mpnTables,$nombre_liens,$ordrelinks;
        if ($ordrelinks==1) {
            $ordrelinks="date";
            $sectitle5 = translate("New Links");
        } else {
            $ordrelinks="hits";
            $sectitle5 = translate("Hot Links");
        }
        $queryblock2="SELECT cid, sid, title FROM ".$mpnTables['links_links']." ORDER BY $ordrelinks DESC LIMIT $nombre_liens";
        $result=mysql_query($queryblock2);

        $boxstuff .= "<div class='center'><br /><div class='cblocktitles'>$sectitle5</div><a href=\"links.php?op=AddLink\">" . translate("Add links") . "</a> | <a href=\"links.php\">" . translate("All the links") . "</a><hr />\n\n";
        while ($array = mysql_fetch_array($result)) {
            if ($array['sid']==0) {
                $boxstuff .= "<ul><li><a href=\"links.php?op=viewlink&amp;cid=" . $array['cid'] . "\">" . $array['title'] . "</a></li></ul>\n\n";
            } else {
                $boxstuff .= "<ul><li><a href=\"links.php?op=viewslink&amp;sid=" . $array['sid'] . "\">" . $array['title'] . "</a></li></ul>\n\n";
            }
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * droite
    ******************************************************************************/
    $boxstuff .= "</td><td colspan='0' style='width: 50%; vertical-align: top;'>\n\n";

    /******************************************************************************
    * droite  download
    ******************************************************************************/

    if ($download_view==0) {
        global $mpnTables,$nombre_download, $ordredownload, $textcolor1;
                if ($ordredownload==1) {
            $ordredownload ="date";
            $sectitle1 = translate("New Downloads");
        } else {
            $ordredownload ="hits";
            $sectitle1 = translate("Hot Downloads");
        }
        global $mpnTables,$nombre_download;
        $result = mysql_query("select lid, title, hits FROM ".$mpnTables['downloads_downloads']." ORDER BY  $ordredownload DESC LIMIT $nombre_download");

        $boxstuff .=  "<div class='center'><br /><div class='cblocktitles'>$sectitle1</div><a href=\"download.php\">" .translate("All Download") . "</a><hr />\n\n";
        while (list($lid, $title, $hits) = mysql_fetch_row($result)) {
            $boxstuff .=  "<ul><li><a href=\"download.php?op=viewdownloaddetails&amp;lid=$lid\">$title</a>&nbsp;<span class='font5'>(".$hits.")</span></li></ul>\n\n";
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * droite  sections
    ******************************************************************************/

    if ($sections_view==0) {
        global $mpnTables,$nombre_sections,$ordresections, $textcolor1;
        if ($ordresections==1) {
            $ordresections="date";
            $sectitle2 = translate("New Sections");
        } else {
            $ordresections="counter";
            $sectitle2 = translate("New Sections");
        }
        $result = mysql_query("select artid,secid, title,counter from ".$mpnTables['seccont']." order by $ordresections DESC LIMIT $nombre_sections ");

        $boxstuff .="<div class='center'><br /><div class='cblocktitles'>$sectitle2</div><a href=\"sections.php\">" . translate("All sections") . "</a><hr />\n\n";
        while (list($artid,$secid ,$headlinetitle , $counter) = mysql_fetch_row($result)) {
            if(strlen($headlinetitle) > 25) {
                $headlinetitle = substr($headlinetitle,0,25);
                $headlinetitle .= "...";
            }
            $boxstuff .="<ul><li><a href='sections.php?op=viewarticle&amp;artid=$artid'>$headlinetitle</a>&nbsp;<span class='font5'>($counter)</span></li></ul>\n\n";
        }
    $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * droite  articles
    ******************************************************************************/

    if ($artclies_view==0) {
        global $mpnTables,$nombre_articles,$ordrearticles, $textcolor1;
        if ($ordrearticles==1) {
            $ordrearticles="time";
            $sectitle3 = translate("New Articles");
        } else {
            $ordrearticles="counter";
            $sectitle3 = translate("Hot Articles");
        }
        $queryblock="SELECT sid, title, counter FROM ".$mpnTables['stories']." ORDER BY $ordrearticles DESC LIMIT $nombre_articles";
        $result=mysql_query($queryblock);

        $boxstuff .= "<div class='center'><br /><div class='cblocktitles'>$sectitle3</div><a href=\"submit.php\">" . translate("Submit news") . "</a><hr />\n\n";
        while (list($sid, $headlinetitle ,$counter) = mysql_fetch_row($result)) {
            if(strlen($headlinetitle) > 25) {
                $headlinetitle = substr($headlinetitle,0,25);
                $headlinetitle .= "...";
            }
            $boxstuff .= "<ul><li><a href=\"article.php?sid=$sid\">$headlinetitle</a>&nbsp;<span class='font5'>($counter)</span></li></ul>\n\n";
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * droite  review
    ******************************************************************************/

    if ($review_view==0) {
        global $mpnTables, $nombre_reviews,$ordrereviews, $textcolor1;
        if ($ordrereviews==1) {
            $ordrereviews="date";
            $sectitle4 = translate("New Reviews");
        } else {
            $ordrereviews="hits";
            $sectitle4 = translate("Hot Reviews");
        }
        $queryblock3="SELECT id, title ,hits FROM ".$mpnTables['reviews']." ORDER BY $ordrereviews DESC limit $nombre_reviews";
        $result=mysql_query($queryblock3);

        $boxstuff .= "<div class='center'><br /><div class='cblocktitles'>$sectitle4</div><a href=\"reviews.php?op=write_review\">" . translate("Submit reviews") . "</a> | <a  href=\"reviews.php\">" . translate("View All") . "</a><hr />\n\n";
        while (list($rid,$reviewtitle,$hits) = mysql_fetch_row($result)) {
            $boxstuff .= "<ul><li><a href=\"reviews.php?op=showcontent&amp;id=$rid\">$reviewtitle</a>&nbsp;<span class='font5'>($hits)</span></li></ul>\n\n";
        }
        $boxstuff .= "</div><br />\n";
    }

    /******************************************************************************
    * droite  links
    ******************************************************************************/

    if ($liens_view==0) {
        global $mpnTables,$nombre_liens ,$ordrelinks;
        if ($ordrelinks==1) {
            $ordrelinks="date";
            $sectitle5 = translate("New Links");
        } else {
            $ordrelinks="hits";
            $sectitle5 = translate("Hot Links");
        }
        $queryblock2="SELECT cid, sid, title FROM ".$mpnTables['links_links']." ORDER BY $ordrelinks DESC LIMIT $nombre_liens";
        $result=mysql_query($queryblock2);

        $boxstuff .="<div class='center'><br /><div class='cblocktitles'>$sectitle5</div><a href=\"links.php?op=AddLink\"><b>" . translate("Add links") . "</a> | <a href=\"links.php\">" . translate("all the links") . "</a><hr />\n\n";
        while ($array = mysql_fetch_array($result)) {
            if ($array['sid']==0) {
                $boxstuff .="<ul><li><a href=\"links.php?op=viewlink&amp;cid=" . $array['cid'] . "\">" . $array['title'] . "</a></li></ul>\n\n";
            } else {
                $boxstuff .="<ul><li  /><a href=\"links.php?op=viewslink&amp;sid=" . $array['sid'] . "\">" . $array['title'] . "</a></li></ul>\n\n";
            }
        }
        $boxstuff .= "</div><br />\n\n";
    }

    $boxstuff .= "</td></tr></table>\n\n";

    $boxstuff .= "</div>\n\n";

    themecenterposts($blocktitle,$boxstuff );
}

/******************************************************************************
 *
 * Function: visitcounter
 * Purpose :
 * Output  :
 * Author  :
 *
 * History
 *
 * Date
 * ----------------------------------------------------------------------------
 * 2001-11-12  o
 *
 ******************************************************************************/

function visitcounter() {
    global $mpnTables;
        $date=date("d/m/Y");
        $jour=date('j');
        $refresh=mysql_result(mysql_query("select * from ".$mpnTables['visits_control'].""),0,"refresh");
        if ($jour==2) {
        $refresh=1;
        mysql_query("update ".$mpnTables['visits_control']." set refresh='$refresh' where refresh=0");
        }
        if(($jour==1) and ($refresh==1)) {
        mysql_query("DELETE FROM ".$mpnTables['visits_counter']."");
        $refresh=0;
        mysql_query("update ".$mpnTables['visits_control']." set refresh='$refresh' where refresh=1");
        }
        $req=mysql_query("select * from ".$mpnTables['visits_system']."");
        if (mysql_num_rows($req)<>0) {
        $d=mysql_result($req,0,"date");
        if ($d<>$date) {
            mysql_query("DELETE FROM ".$mpnTables['visits_system']."");
        }
    }
        $ip = $_SERVER["REMOTE_ADDR"];

    $req=mysql_query("select * from ".$mpnTables['visits_counter']."");
        $rows=MYSQL_NUM_ROWS($req);
        if($rows==0) {
        mysql_query("insert into ".$mpnTables['visits_counter']." values('', '$date', '0')");
        $req=mysql_query("select * from ".$mpnTables['visits_counter']."");
        $rows=MYSQL_NUM_ROWS($req);
        }
        $rows2=$rows-1;
        $d=mysql_result($req,$rows2,"date");
        if ($d<>$date) {
        mysql_query("insert into ".$mpnTables['visits_counter']." values('', '$date', '0')");
        $req=mysql_query("select * from ".$mpnTables['visits_counter']."");
        $rows=MYSQL_NUM_ROWS($req);
        }
        if (mysql_result(mysql_query("SELECT COUNT(ip) from ".$mpnTables['visits_system']." where ip='$ip'"), 0) == 0) {
            mysql_query("insert into ".$mpnTables['visits_system']." values('', '$date', '$ip')");
        $rows=$rows-1;
            $count=mysql_result($req,$rows,"count");
            $count++;
//            mysql_query("update ".$mpnTables['visits_counter']." set count='$count' where id=$rows+1");
            mysql_query("update ".$mpnTables['visits_counter']." set count='$count' where date='$date'");
    }
}

?>
